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 |
---|---|---|---|---|---|---|---|---|
1,689 |
Hello Hi Everyone Welcome to Channel Irfan YouTube Channel Please subscribe button first so let's solve all the problem partition in terminal number 110 008 123 092 and did not give positive and return positive energy number two for example subscribe for Live video plus two plus 332 how To do is third like very kind of little prince 's problem andheri gas cafe instead and it's 's problem andheri gas cafe instead and it's 's problem andheri gas cafe instead and it's first of all things which have just one digit number which is later 300 Effigy in how many minimum desi boys number vic in the too small dros desi winery to get Free So They Can Have Only Desi Boys Number Validation Line Is Number One For It Will Take Three Vansham Tarf Minimum Policy 351 Number Two That Is Pairs Of All Its Acidity Subscribe 3232 Divide This Video Free Minimum Naveen Dhatu Ko Like Being Can Create Any Day CY Number Date In Flute Solve Which Constructed 501 Digit Only And Listen All The Best Shivanshu Our Number And They Have To Live With The Number One Third Number 1031 Example Of Consent Of Power Line 1090 So This Ball Seam Case Will Divide All This Digit Sub Fuel and Minimum Five and Hair Minimum 7147 Minimum 1-1-14 037 Dominating Swadisht Minimum 7147 Minimum 1-1-14 037 Dominating Swadisht Minimum 7147 Minimum 1-1-14 037 Dominating Swadisht is the Maximum Minimum Seed Minimum Desi Wine Numbers with Water Maximum Value in Our Numbers and Characters with Answers Quizzes Me to the Maximum The Video then subscribe to the Video then subscribe to The Amazing Result B.Sc Result B.Sc Result B.Sc That And What To Caring Chapter Wise Visiting All The Character In This Will Take Result Is This Is Not Fair Of India Maximum Valley Between The Lines From Day One Will Return Result And Sudhir Wide Ball Striking life is not want to write no channel Subscribe Striking returns from his return from main stream of characters on the grid of characters and a maximum of 200 numbers one will dare attack you in a lift slide time decides tomorrow this is taking too much time Have running me also or direction and it don't want to take off this thank you all the best for this map to objects and drop array subscribe Video then subscribe to the Page if you liked The Video then [laugh] [laugh] [laugh] subscribe to the Video then [ Hansi] A for its evil in power and Sudhir and Isko A Ab Se Aadha 6120 How to you can rider don't know what is the time complexity of solutions for the time complexity of which given subscribe and subscribe the Channel thanks for watching
|
Partitioning Into Minimum Number Of Deci-Binary Numbers
|
detect-pattern-of-length-m-repeated-k-or-more-times
|
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not.
Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._
**Example 1:**
**Input:** n = "32 "
**Output:** 3
**Explanation:** 10 + 11 + 11 = 32
**Example 2:**
**Input:** n = "82734 "
**Output:** 8
**Example 3:**
**Input:** n = "27346209830709182346 "
**Output:** 9
**Constraints:**
* `1 <= n.length <= 105`
* `n` consists of only digits.
* `n` does not contain any leading zeros and represents a positive integer.
|
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
|
Array,Enumeration
|
Easy
|
1764
|
26 |
hello everyone in this video we're going to see the solution to the lead code problem remove duplicates from sorted array so we're given a sorted array and we have to remove the duplicates in place such that each element appear only once and we have to return the new line but we don't have to allocate any extra space we must do this by modifying the input array in place so how do we do that let's check with an example suppose i have 1 2 3 so what i have to return is you can see that the unique elements are one two and three so the first three elements should be one two three and we have to return the new length that is three and afterwards whatever it is it's not a problem like it says it doesn't matter what you leave beyond the return level but in the modified area the first those elements should be unique and we have to return the length of those unique elements so the approach which i am going to tell you is very simple so what we have is we have a pointer and whenever we find element which is not repeating then we increment our pointer and whenever there is an element repeating we just keep on going so it will make more sense when i code it out so we'll have in j is equal to 1 which is my pointer so what i'll be doing is for n i is equal to 0 i less than dot length minus 1 i plus minus 1 because i'll be comparing numbers of i with numbers of i plus 1 so if nums of i not equal to norms of i plus 1 then what i would do is i'll say num of j is equal to number of i plus 1 and j plus so what i'm doing here is suppose i have one i'll take the same example suppose i have one two three so initially j is one j is here now i come to a 2 i come to i and 1 is not equal to 2 as you can see so what happens is numbers of j becomes numbers of i plus 1 meaning nums of 1 becomes 2 and j is incremented so now j is this then i goes here it's repeating so it does nothing i comes here it's not repeating so numbers of j becomes numbers of i plus one so this becomes three and the other stays as it is and we return j which is three and the first three elements are unique which you can see okay so number of j and then simply we have to return j so that's it and j will be the number of unique elements because we put the unique elements in their correct position so let's try to run it seems okay so you can see that we're getting a run time of two ms but runtime is keeps on varying with certain elements because you can see that i did the same code and i got zero image so if i made some small if i make some small changes i will get zero again so let's try to do this right to one ms or if i just show you the zero ms one it's pretty easy it's the same thing it is the same thing let's just cap it after return j so anyways it's the same thing i'll just show you by copying that how little space here and there can turn 1ms to 0ms yeah so you can see this which i which have 0ms now it's showing 1ms so 0ms and 1ms is a lot of difference and that is with certain factors which i'm not sure about but this itself is 0ms it runs in runtime is 0ms and the very simple approach is keeping a pointer and incrementing the pointer when we see an element which is not equal to its previous element so that's it thank you
|
Remove Duplicates from Sorted Array
|
remove-duplicates-from-sorted-array
|
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`.
Consider the number of unique elements of `nums` 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 unique elements in the order they were present in `nums` initially. 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\[\] 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,2\]
**Output:** 2, nums = \[1,2,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 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,2,2,3,3,4\]
**Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-100 <= nums[i] <= 100`
* `nums` is sorted in **non-decreasing** order.
|
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
|
Array,Two Pointers
|
Easy
|
27,80
|
1,787 |
hey what's up guys uh this is chung here so today uh let's take a look at uh late code 1787 make the xor of all segments equal to zero yeah so this one is pretty i think it's a quite difficult one so you're given like an array of numbers and an integer k here and the xor of a segment left to right uh basically it's a xor of all the other elements within this range here and you need to return the minimum number of elements to change in the array so that you know the xor for all the segment of size k is equal to zero so what does that mean right so in the example one here so just the basically it's a sliding window right it's a sliding window of size k right and in the example one here sliding the sides of sliding we know it's one here that's why you know it's obvious you know to make sure each sliding window at the x4 is zero we have to make all the elements into zero right that's why the answer is three here and then example two here you know the size of the sliding window is three here so you know the in this case you know we have to make three uh changes as well basically we change uh 3 4 7 to 3 4 2 because you know 3 3x or x 4x5 does not equal to zero okay so this does not equal to zero so that's why we have to make some changes to make it zero so the way this so in this example we change five to seven right and then this one become this one will be equal to zero in this case and after that right now we have to also make uh some corresponding changes for the moving sliding window and then for this one now we have uh four three seven and then for four three four seven and then for four seven here you know we also need to change two into three right and then we change three into four and so on so forth so at the end we have this one the end result is like this so we have everything uh equal to zero right i mean for given like a three sliding window size of three sliding window yeah and here's another example right so we have a one two four one two five one to six so in this case we change this all uh changes three four five six to three and here's constraints the constraint is like so the length of the number is two thousand and here's the important one basically you know the range for the number is only a 2 to the power of 10 which is a 1 0 to 4. okay which means that you know the range for the number is only within this like time within this kind of like number limits okay so for this problem you know at the beginning i was thinking i was trying to solve this one with a greedy approach you know something like you know because i was looking at this example two here you know maybe the first time i saw like uh like unmatched uh like a sliding window size case like we know that's the actual result it does not equal to zero i'll try to make some changes to make it zero right and then later i'll just use that as a base and then to move forward but we always have some like uh some special corner cases here you know let's just take uh take this one as an example here you know what if we have this one let's say we have two four three one two three and one two three right so in this case what's going to be the end result actually we need to change this 2 4 into 1 2. let's say the k is equal to 3 right because this will give us the minimum change minimum operation which is 2. right but i at this point at this moment here two four three we don't know what's because here you know we could have like a lot of other ways that we can make the change right and then we end up with uh doing this kind of change here so which means that we cannot uh we cannot assume right uh what's going to be the best approach here which means we have to try all the possible uh changes here right so that's the first like observation and the second up very important observation is that you know after the changes regardless of what numbers you we are we make the change right so in the end you know actually so as long as you have fixed the first k element let's say we have a lot of uh numbers here no let's say the case is three right so as long as you have fixed the first case element right the rest there they have to be fall they have to be following the same pattern right just like what we have one two three here right which means that you know as long as we have fixed the first case element we can use that one to easily uh deduce right to get what's going to be the remaining numbers here right i think it's obvious because you know once you move the sliding window from here to here let's remove slime window from here moving one forward which means that you know in order to make this new sliding window uh actually equal to zero this one has to be has to equal to this one right because you're you are removing one number from the sliding window which means that to make this landing window equals to x or equal to zero you have to add that same number back right and then so on and so forth when you move like this one basically this two has to be the same that's why you have that's why regardless of what numbers we use we are we're seeing a pattern here so it's a repeating pattern so it's three four seven so for this one it's one two three and one two three okay so now actually the problem has come down uh has changed right we can transfer convert this problem into what so we need to find a combination right a combination of the first case element in this uh nums array here okay right we have a lot of x in later on so let's in this case k is equal to 5 right so now the problem is that how can we find a combination right a combination of numbers that can give us the uh of course you know and give us the minimum changes after we after fixing some numbers here right and of course the final result will be the actual off for this number has to be equal to has e has two has to equal to zero right um cool and to be able to find to do that you know and you know a brutal fourth way is that you know basically we try all the possible combinations right of this like uh case numbers here but that's going to be a too uh too complicated because you know the number of length of case 2000 right and for each of the numbers we have like how many probability how many options one zero two four it's gonna be a two thousand power to the power of one zero two four right this is like a four it's insanely crazy big number right and so and how can we find uh this one right um we can use like a dynamic programming to help us solve this problem you know because uh we can do a pre uh process for all the frequencies you know actually you know since like i said as long as we have fixed some numbers uh at uh in the first k elements you know that the remaining ones has to have has to follow that which means that let's say if we decide we change this x into two right it means that you know for the two plus k and 2 sorry for the 0 and 1. let's see this one is i right the index is i here so which means that the i plus k and the i plus 2k and the i plus 3k they all need to they'll they all need to be 2 as well right so that you know to help us to calculate this uh dp functions we can pre-process the uh and preprocess we can pre-process the uh and preprocess we can pre-process the uh and preprocess the entire numbers here you know we can just count the uh at each of the index right from zero to k what are the frequencies of after each number at this like this kind of index because that can give us the uh some uh helper give us some help when we try to explore what numbers we try to uh change to right because you know let's say we see we already let's say there are like total of a total of 10 numbers uh two numbers at this kind of uh i here right total of 10 and let's see the 2 is 3 2. so we have 3 number 2 here and then let's say if we decide to change all the numbers into if we decide to change the this i into two it means that you know we just need to make what's going to be the cost for that right since we have 10 but we already have two already so it's going to be a 10 minus 2 which equals to 8 which means that if we decide to change this low number into 2 so the operations we need to make this uh make all the this number into 2 is 8 right okay so that's the first thing right and okay now so how about the stp state transition function right and so how are we going to define that the dp uh state so since we need to try basically all the possible solutions all the part the possible combinations here you know we don't know which one will give us the best answer so which means we have to try all the possible results from zero to one zero to four you know because you know so the range for the possible actual result is also one zero what uh zero to one zero two four it's because you know in the end you know we'll make this kind of uh the x the entire sliding window equals to zero so the upper bound is one zero two four so what i'm going to do here you know i'm going to define like a dp function here let's say we have dp i and dpj here so this one is what so it means that you know from basically it's going to be minimum operations to make uh these nums to make the uh eyes to the case maybe k minus one minimum operations to make a ice number to k i minus one numbers uh the x or result right equals to j so that's going to be the basically the definition of this dp here so basically this is what i mean here right so if we have like this kind of uh so now remember we're not talking about the entire numbers here we're only talking about the size case sliding window so let's say if the i is here right so this dp means that you know uh from i to the end of this slide of this case uh window here you know the final actual xor results equals to j right because here you know the range of the actual result actually or xor resort like i said it's gonna be a one zero two four right that's why you know we have to explore all the possible uh results here okay and so why do we need that right so okay that's gonna be the definition of dp so the reason being is that you know when we try to construct this dp state transition function we have this one basically we have a dp i j right equals to what it goes to the minimum of what the minimum of dp uh i plus one right since we're building from the from uh right to left okay to the uh let's see j x or the target i'll call it a target number class plus cost of changing right to target number here so what does it mean it means that you know um where should i start okay so to be able to make the j uh the current uh position at the uh xor right for the current one let's say this one right so let's see we have a this is i right this is i okay so to be able to make the entire actual result equals to j right so what we can do here is that you know uh basically we're going to enumerate all the possible target numbers here you know the uh and let's say we have so this one actually so this j x or target number is the previously it's the actual result for the for this part right for the i plus uh i plus one right which is the uh which is the which is this one and because you know we at the current location you know we have to make a decision right so the decision is that you know which number we want to use at the current location right this with that numbers plus this j here you know we can get the previously uh the i plus one uh xor result and why is that and probably i shouldn't have done this okay so this is because you know let's say we have a question mark let's say the this is the previously actual result so to previously actually resort to xor of what of this target number right of target number equals to what equals to j right so that's the process we have a at this i plus one state the x or result is a question mark right and then we have like this one we decided okay so the for the current number we're gonna change it to the target number right and then after that we have the j here so the j is the current state right now we're trying to get this question mark so how can we get that you know we can do this right so we do actually of the target number we do have another we'll do x or of target number again so and on the right side we also do this one because the target number if you do x with the same numbers here you know they'll be become to zero right so that's why so the question mark equals to this j uh xor with the target number which is exactly this one right so that's how we get that basically you know so this dp state transition function is saying that you know i'm going to try to set the card number in all possible numbers into possible numbers so that uh that which can satisfy the current uh can get give us give me this kind of like actual result for the ice positions and i'm going to calculate the cost of doing that and then i'm going to get the minimum of that so that i can calculate that right the basically explore all the possible scenarios for the current state and in the end right we just need to return the dp of zero and zero so this one means that you know at the very beginning of the numbers of the case uh sliding window here uh what's going to be the minimum cost if i want to make the x or equals to zero right cool so i think that's basically the main idea here you know i'll start coding and i'll explain a little bit more here i think that will also help you understand that so like i said you know we have since we have to uh calculate the cost right by making the uh when uh some by making some position into a certain numbers which means that we have to do a uh pre preprocess the frequency of each of at each of the location right in the size case writing window it's going to be a counter so i'm going to use a counter for this one in the range of k right so here what i'm so we have four i number in enumerate uh numbers here right and then we're going to have like a frequency right frequency of the of what after i mod k right and then this one is going to be a number sorry plus one right so this one i mean i'm basically for each of the location of sliding window k here you know this is the case sliding window right we have a lot of many positions here now at each of the locations since this is a sliding window and i basically we're using this one to represent the entire array here so we could have like a different numbers uh appears on this kind of like buckets or you can call it buckets right you could have like a two three four five or two it doesn't really matter because this is like a repeating right because this for example this one we have one two four one two five and one two six right so in this case uh at the bucket zero here we have three ones here right and at buckets two here you know we have three two and i at bucket three here we have one four one five and one six and basically that's what i'm trying to uh get here okay cool and the next one is that you know i'm going i'm also going to summarize uh the summarize the total numbers at each of the buckets here okay total number count at each of the buckets here is going to be the this one so uh so we're gonna have like a four f in the frequency right and i'm gonna have like some of the uh f dot values right that's how i uh summarize everything for this into this bucket and then we're going to have like dp right so the dp is like this right so at the beginning it's going to be the system.max size it's going to be the system.max size it's going to be the system.max size right so like i said the range is one zero two four and then for this one in range of k right okay cool so and since we're going to use like the i plus sorry the i plus one right we have to pre-process the base right we have to pre-process the base right we have to pre-process the base case which in our case since we're going to process from the end to this to the beginning which means that we're going to uh x or result in range of 1 0 to 4. we're gonna pre-calculate the dp we're gonna pre-calculate the dp we're gonna pre-calculate the dp minus one okay so this one means what it means that you know at if we only have one like a number here you know if we want to make this x or equals to that right what's going to be the uh what's going to be the frequency what's going to be the cost the operations we uh to make that happen so obviously you know for the base case right i mean the operation is going to be a total number count of -1 right total number count of -1 right total number count of -1 right of minus one minus the frequencies of the uh of minus one and then do this x or result right so this is because you know what because let's say if at the last location let's say we have two three and four right so let's see at the last bucket we have these four numbers there and so in order to make a in order to make this kind of x or equals to let's say equals to uh let's see yeah so for this base case it's like as if you know we have this kind of numbers remember so this one means that we want to do actual result you know at the first at the last location here you know since there's no xor with other elements so this one's as if we're changing the last uh position to this number to this actual number here right so which means that let's say if we decide to change this number into two right so that's why you know in total we have four here right so and we have to subtract two here because we only if this x or is two it means that we have we want to change this one to two which means that we have we only need to change this three and four into two that's why the total cost will be this one okay and so yeah and that's how we define the base case right like i said we have to explore all the other possible actual results here and then we can just start our true uh dp loop here so and then we can start from k minus two uh minus one right like i said we have to explore all the results right the actual result in the range of one zero two four and yeah so i mean a naive approach if we just follow our approach here you know for each of if we want to do this right i mean for each of the actual result and we might want to do something like this you know we have a best economic system dot max size and then we might also want to exploit basically we have a change to right or we have like a target number right target number here in the range of one zero two four right and then the uh going to have like the best going to be the minimum of fast dot uh total number count i minus the frequency of i and target number right and then we do a plus of dp i plus 1 and then this x or result right to a and do x always the target number okay and in the end uh we update the dp right dpi x or result equals the best right something like this basically so this is the naive approach right so for each of the actual result i'm try i'm trying all the possible target numbers from 0 to 1 0 to 4 and then we're going to calculate that you know based on that based on this our step state transition function but this will tle because you know this is pretty big right this is like already one million and then if we do another uh if we do a times x multiplied by this number of 2000 that will definitely tle so which means we cannot do this and another uh optimization is that you know we don't have to try all the possible 1 0 2 4 here you know because you know this thing is going to be a sparse like a array here you know it's most likely we'll only have like a few uh numbers appears on this kind of uh ice bucket here you know so which means that we don't have to explore all the one uh one zero two four every time so what we can do here is that you know we can do something like this uh so we can define like the uh change r state here you know so change out means that we're going to change all the numbers into some other numbers so actually this that this is the case you know when whenever the frequency i of the target numbers equal to zero so let's say if at the current position right at the current buckets here if the target number we're trying to explore is doesn't exist at all right and then it means that you know we are changing that number we're changing all the number into that number right so actually we can just uh summarize those cases into one statement which means that you know so to change all the numbers uh the cost will be simply the uh the total number of count uh on i right that's going to be the changing order numbers plus what plus the minimum of the dp of i plus one so that's going to be the case for all the numbers that's that does not exist does uh didn't appear at the current bucket because by changing that numbers you know we have to it doesn't really matter which number we change it to but you know another the other part is that we just need to get the minimum of the dpi plus one because since we're going to change that all the numbers into a different number regardless you know we can simply get the minimum of dpi plus one right then we can change all the numbers and use this kind of formula to that number right so that's going to be the change all uh base case right and since we have this one here you know now we i we can only we can simply just loop uh in loop through the number that appeared at this con at this bucket right so which means we can instead of doing the best equals this one we can uh set this one to change r and then here instead of looping through this one we can loop through the uh the frequencies right so we can just use the frequencies uh dictionary here like for targeted number in the frequency of i right dot keys right since the keys will be that yeah i believe that's the improvements here i think instead of looking through one zero two four we can simply loop through the num only the numbers appear at this current buckets right and yep so i think that's pretty much it is so if i run the code yeah so submit cool so it passed but even though it's faster than 100 still not that fast but anyway so it passed right so and the time complexity for this one and is what so as you guys can see so first i think it has to be somewhere here that's the most nested for loop here right so it's going to be a k right times 1 0 2 4 times basically times the uh the biggest num the most numbers at that's the uh any uh buckets here right so this one obviously is going to be a way smaller than one zero two four here right because that yeah because you know it's bounded with the length right so we have a two thousand uh like the total length and we have this kind of k here basically the bigger the k is the smaller this thing will the smaller this for loop will i mean will be right because this because there will be less numbers in each of the buckets so i'm not quite sure about this final number here you know i'm going to put a question mark here sorry about that and but anyway that's the basic the rough uh time complexity here yep so and to recap what we have done here you know so here we try we pop so first we uh we preprocess right the frequency right of each number at an ice bucket right of size k and here we have this kind of uh dp here basically we have the dp i and j here right and actual result actually this is going to be the uh from i to k right from i to k minimum operations right to make i x or i plus 1 x or i plus 2 dot right x or uh k minus one right equals to the x y result so that's going to be the definition of dp here and in order to achieve this one you know so we have to basically set so that is the base case right the base case is like i said it's just like changing the number right into that number because there's no x y at all otherwise we have to loop through the uh each of the possible xors here from zero to one zero two four and then from there you know we're gonna try to change the card number the current uh buckets to a number right and based on that targeting number and the actual result we can get the xor from the i plus one state and then we can just calculate that right the cost of the current state and then the previous state and we get the minimum out of that right and here's a little bit trick of handling uh some handling all the other the target number who never would never appear at the current buckets okay and then in the end we simply return the dp 0. cool i think that's everything i want to talk about for this problem and yeah thank you for watching this video guys then stay tuned see you guys soon bye
|
Make the XOR of All Segments Equal to Zero
|
sum-of-absolute-differences-in-a-sorted-array
|
You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k` is equal to zero.
**Example 1:**
**Input:** nums = \[1,2,0,3,0\], k = 1
**Output:** 3
**Explanation:** Modify the array from \[**1**,**2**,0,**3**,0\] to from \[**0**,**0**,0,**0**,0\].
**Example 2:**
**Input:** nums = \[3,4,5,2,1,7,3,4,7\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[3,4,**5**,**2**,**1**,7,3,4,7\] to \[3,4,**7**,**3**,**4**,7,3,4,7\].
**Example 3:**
**Input:** nums = \[1,2,4,1,2,5,1,2,6\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[1,2,**4,**1,2,**5**,1,2,**6**\] to \[1,2,**3**,1,2,**3**,1,2,**3**\].
**Constraints:**
* `1 <= k <= nums.length <= 2000`
* `0 <= nums[i] < 210`
|
Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly.
|
Array,Math,Prefix Sum
|
Medium
| null |
139 |
all right so today we'll be looking at the problem word break so this is another common dynamic programming problem so let's just jump right into it so given a non-empty string s and a so given a non-empty string s and a so given a non-empty string s and a dictionary word dict containing a list of non-empty words determine if s can be of non-empty words determine if s can be of non-empty words determine if s can be segmented into a space separated sequence of one or more dictionary words note the same word in the dictionary may be reused multiple times in the segmentation you may assume the dictionary does not contain duplicate words let's look at these examples so s is our string so we're given leak code and then we are given a word dict with Le and code in it and so the reason this return is true is because leite code can be segmented as leite code so that is valid similarly with example two we have apple pen apple and our word dick has Apple and pen so you see there's two instances of apple and then one instance of pen it's still true because Apple pen Apple can be segmented as Apple pen apple and also we are allowed to use uh or allowed to reuse a dictionary word so that's why apple is used twice and then finally we have example three cats and dog with cats dog sand and Cat so for cats and dog word dick contains cats dog sand and Cat while all those individual words are in our string the fact is it still returns false because we can't use all those words uh within our string so we can use cats dog and maybe but then we won't be able to get sand or cats because they overlap each other so that's an issue so like I mentioned earlier this is a dynamic programming problem so we're first going to look at a Brute Force approach and why it's not optimal and then we're going to optimize it by implementing a dynamic programming approach okay so first let's look at a Brute Force approach so the quickest way that we could solve this is we could just use a form of recursion or backtracking to essentially check every possible prefix of that string in our dictionary of work if we find it in our dictionary then the recursive function is called for the remaining portion of that string and if in some function call it is found that the complete string is in the dictionary then it will return true so essentially you just think of the first approach as checking every possible combination uh within our string and just checking or taking all these combinations and looking within our word dick to see if we have either Le or code so as you can imagine this is a lot of overlapping work because uh we're just essentially looping over the string several times to try and generate you know different prefixes that might be within our word dick dictionary or List rather and so as you can probably imagine this isn't the most efficient approach um if you want to take this to the extreme imagine you have an input string like a like this so this would take upwards of O of n to the N power this gets really bad because imagine if we have a word dict with you know a and so on and so forth like different variations of a if we're going through this input string then I mean we' be doing a lot of work because we' be doing a lot of work because we' be doing a lot of work because there's essentially a being used throughout and there's different combinations of a and so we need to calculate all those so definitely not ideal so this is not a runtime we ever want to strive for so how can we improve this well we can implement dynamic programming and is usually the case we Implement dynamic programming when we encounter overlapping sub problems so with uh both of these AAAA and Elite code you can imagine like on a recursive tree a bunch of work being done several times I won't draw it out because it'll take up a lot of space but just imagine like when we recurse on like a substring there'll be a lot of other instances of that substring within that recursive tree uh just so we can look for our matches within our word dick so with dynamic programming we aim to eliminate this by essentially using at least in the instance of this problem we can use an auxiliary uh list and essentially the list will be a list of booleans and we'll use that information to essentially tell us up to a certain point if we have a match within our word dict input so for example if we're looking for the word leite in our string we can start from the beginning and then continuously move and then once we find or once we get to T we can say that this entire substring right here will have two pointers so like I and J you can think and we'll have those two pointers and we'll say from I to J the substring here is that within our word dict if it is then what we can do is Mark the index where T is as true and so with that what true essentially signifies within our auxiliary dynamic programming list is the fact that up to that point we have a match with one of our strings within our word dick so this isn't making sense I'm going to draw this out so it'll be more clear okay so let's create our auxiliary array so I'll just call this DP and so with DP we'll essentially use the last index of a substring that we found within our input string and check if that substring is within our word dict input if it is then we can set the end index of that substring that we found to true because we know that the index where we set true at we know before that we have an instance of one of the strings within our word dict that match so the substring that we found before or up to the points of the true that we just set at that index is within our list our word dict input so how this will look is or with this being said one of the first things is we need to establish a starting point for us and so we'll actually create the DP list one greater than the length of our string and so the reason why we add a plus one buffer to our auxiliary list is because we need a starting point and so the starting point will always be true and the reason why it's true is because the first input represents a null string and so a null string is present in any string that will be where we start and then from there we can move through our input string so we can move through S and we'll be able to essentially keep two pointers and use those pointers to extract a substring from our input and then check if that's within our word dick if it is we'll set the last index of our substring to true to indicate that we found that substring is a match okay so with Le code we have eight characters so we'll put I put T and F uh so T is true and F is false so let me just fill this out and so just to help you guys visualize I'll put the respective characters you know the index that these are supposed to represent all right so we have our starting point right here uh index zero which we set to true and then essentially all we want to do is we want to use a nested Loop so we'll start off with a for Loop and if DP of I so if the current index happens to be true like it is right here then we enter another loop which essentially is the range of I all the way to the end of the list and so essentially what we're looking for here is we're trying to extract a substring uh it's going to be between in the second for Loop the variable will be J and the outer loop will be I it'll we'll essentially try to extract a substring from our string with the outer Loops variable I and then up to J + 1 so what variable I and then up to J + 1 so what variable I and then up to J + 1 so what this will look like is we start off with I right here and then we have J and then J Will Loop through until we find a match or if we find a match so J will come here all the while checking uh if this is within our word dict and then eventually When J comes here this will essentially indicate that our substring at this point is leite and that is within our word dick so what do we do well we set this particular index to true and so what I've been saying earlier is now that this is true so this is the end index of Le right so leite right here and so what this is indicating is essentially all past characters represent a substring that is within our word dict input and so that's what this is signifying right here and so the logic here is that if we do this for our entire list the very last value should return true because that means that we've used up every character within our word digs if at any point we process or we go through our entire list and then we return the final value and it happens to be false then we know that not every match was properly found in our inputs and so we know then that the answer can't be valid so it'll return false and so that's kind of the logic behind using essentially a Boolean array uh because it'll let us know Point Blank like at the end of the day when we process everything did we find our answer or Not So eventually I will come over here so let's say right here as we move through the list and again J will move over and over eventually J will end up right here and so what this is telling us is now this variable right here SI I to the J + one essentially what this is the J + one essentially what this is the J + one essentially what this is saying this is python notation for slicing in this case we're slicing a string so this will say at index I up to J + one so j+ one is not included so it J + one so j+ one is not included so it J + one so j+ one is not included so it stops right before it so I up to J +1 stops right before it so I up to J +1 stops right before it so I up to J +1 what this uh substring will be right here is now code and so we look and we're like okay is code in word dict yes it is and so what we'll do here is we'll mark this as true again indicating that we found another match uh within our work dat and then since we reach the end of our list we return DP we'll say negative 1 and so this is just Python's way of saying uh get the very last value so we get the very last value right here and that happens to be true and our final answer you know is true so we've gone through this entire list and we've been able to identify that LE and code are within the input string so therefore this is valid this actually works and this is congruent with the first example that we saw in the Le code problem so hopefully that makes sense uh we'll be jumping into the code soon but before we do that I want to discuss the runtime and so with our approach since we're using essentially uh two for Loops so we have one for Loop and a second one so for Loop one for Loop two the reason for this is because we use the outer uh to establish I and then the inner for J and this will be essentially our exploration so we can use that to identify substrings like right here and so naturally by now you should probably be familiar with the fact that if we have a nest for Loop it means that we're doing n squ work so that' be o of n squ o n squ work so that' be o of n squ o n squ work so that' be o of n squ o n squ isn't the best runtime but it's still way better than NN where n could be anything so for this particular problem that's about as good as it's going to get so that's our runtime and then our space complexity will be o of n uh reason being is because we construct um you know our auxiliary DP array uh with dynamic programming problems if you have to construct an auxiliary data structure of some sort and it's going to be you know o usually so this is our space and then runtime cool so this is it for the dynamic programming approach so now we're going to go jump into the code all right so let's dive into the code so first things first we wanted to have a layer of safety so what we can do is actually create a set uh from our word dict and so this will essentially remove any duplicates so we can just do that real quick word dict setal set word and so next uh since it's dynamic programming we're making use of a auxiliary list so in this case we're going to call this DP and this is going to be a booing list because in the conceptual walkthrough I talked about how we're using a booing list to essentially Mark the end point of a substring that is found within our set so we'll set this all the false for now and we'll multiply this by the length of s so our input string plus one and so the buffer the plus one here buffer is important because we're adding the Extra Spaces to account for a null string and so that'll actually be our starting point so let me actually set that real quick so dp0 so the very first index will be true and so what DP zero here is saying is we have a string that we're trying to compare in this case you know s could be le code but the one thing that will always remain true is a null string so null string is present in every single input and then from there we're looking at other different combinations and so that's what the plus one is here for we're just essentially setting that as a buffer so we can make sure the first element is set to true and then the rest of the list is of length s and at that point we can sort of build up our approach all right so now that we're iterating what do we want to do well we want to check if the current index within our auxiliary array is true if we encounter true which we will the very first starting point right here is true to count for the null string so we'll start off with a true and then what will happen here is we'll enter another for Loop so for J in range of I to length of s and so I will essentially be right here so we'll start at wherever I is and then go to the end of the string and so that's what J is so essentially what we're doing here is using Python's uh string slicing to determine a sort of window or substring within our string and then checking if that's within our set so that'll look like this if s i j + one in word dict like this if s i j + one in word dict like this if s i j + one in word dict set if we find the word then we want to set the very last index to True J + one set the very last index to True J + one set the very last index to True J + one equals true and so this just tells us that when an index is set to true we're confident that previous to that index we have a substring that matches a word within our set we essentially do this for the entire string and then at the end of it we just return the final value that we've built up in our auxiliary dynamic programming array so we'll just say DP minus one which is Python's way of saying get the last element and everything looks good we have are set we construct auxiliary list set the initial value uh if true then we create a sub window to try and find a word or substring within our string that's in our word set and set that to true so yeah this looks good let's run this and see what we get okay so the initial case with leite code does pass so let's submit this all right so that's the answer hopefully you guys learned something new from this problem and I'll see you guys in the next one
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
68 |
hello everyone today I'm going to talk about question which is a hard level question in Unicode it's caught text justification we're given array of words and widths called max width so you're going to format the text such that the each line has exactly max West characters and it's fully justified and if you look at the example you know exactly what they're talking about you're given list of words and then you need to basically allocate and choose correctly the denominator or maybe how many words should be in each line and reach line there should be a correctly yes spaced between each word the last word is always just closely at the loop at the very end of the every line and except for the last lines of the last line is the exception is one of the quarter case since and if there are extra space extra spacings that you have to take care of they should be there should be more extra spacing for the pair that for the pair of words that just appeared okay there should be if there should be any larger spacing like there you should put 1 5 and 1 for spacing then the 5 should appear first okay that's pretty easy to apprehend let's look at the text let's look at the codes so for me I basically check how many words should fit in each line and when you can't add more word to it you just send all the words into one of the function so I used to function only is to concatenate function which is the regular function and one is the last function because less is easier it just um don't need to care about the extra space and you just need to add a pen word one space and then fill the rest that's basically yeah that's physically the last function and I'm gonna talk more about the concatenate function because there are several common cases as well ok firstly I'm sorry we need to talk about how do you choose the word right so I used a while and you add one word each time and until that either it has hit the final ends or you shouldn't add this word because it's gonna be more than the max with I'm using here comparing the Max was plus 1 because every time I increment account I used lens plus 1 so I considered the normal case that how many words that I can fit as much as I could so there is just only one ones faith that I add to the count and eventually you I compare it with the max was plus one so you do need to worry about the last word like if this is Eve if there are words that are perfectly fit into one line then eventually it's gonna be this equal is gonna you're gonna meet the new coil situation so and then you don't need to worry about whether the last word or not you just compare directly with max Lewis plus one I think it's a smart move here and then if you hit the boundary you're going to send it to the last function if it is not then you send it to the regular concatenate function and then don't forget to update the pref Travis index of starting index I minus one is the ending index of course yeah in the concatenative concatenate function it's pretty clear because I write it pretty clear you first calculate the number for it that's easier that's easy to understand and then the number of extra space the extra space is the max width plus 1 minus count so that's how many extra space that you need to put in the regular space and then if the number of extra space is equal to zero actually it's the same case if the last one because in the last function you just append one regular space between each words right so this fits into that one so I just directly send it there because I'm gonna assume in later lines that this one is not zero and there is also one another corner case if there's only one word a huge word but it fits one in one line then what should we do there is no even a pair of words that we need to consider about the space then you also send it to the less so that's one of the things that I think it's quite smart here so you just use the last line function last function and then after this okay this also is the exception for the arithmetic right here so if you don't take care of the extra corner case you're gonna get an error in compiler that this one hasn't been taken care of even though it usually shouldn't be the space count is gonna be the number of extra space divide it by the word pair spacing the spacing count so plus one if the one is the regular space so the space count is going to be how many spacing a how many spacing should be between words and then I'm gonna use this number for increment this into a regular space a stringbuilder and then there's a larger space count right it's the larger space how many larger space is going to be the modulo of the extra space mod the number of word pair and then this one is another screen boater but don't forget that you should make a new one and then had one extra space and then you're gonna just do it regularly while we're going to append in this order in this fashion that one word is appended and then followed by one space at one spacing that it should be appended and then you leave the last word and then you Pan the last word in the final situation because you don't need to append spacing more so while first these less than last I'm gonna append the word and then if there should be if they should be a larger space and I'm going to pan the larger space stream better if it's not then append the regular space let's say I think it's pretty straightforward right I read it in the way that it's easier to understand after this I'm going to also talk about the last function is also quite easier it's it take thing but if the word the start index last index and the number of Max with and while they're the store hasn't hit at last I'm gonna append the word first and then the regular space and then after this I'm gonna pan with the fun word and no space if the lens is smaller than the max width you're gonna fill it the rest fill the rest phase with spacing that's it I think it's pretty straightforward but you have to just arrange them into great code structure and they use separate functions because that's much easier to understand in terms of the time complexity I think I hear I allocate them into different function it's gonna be Owen and you separate function I'm gonna just check them in Owen time as well so it's Owen in total the time complexity is Owen the space also I didn't use extra space I just if you for every word I'm gonna put it in efficiently into a stringbuilder service strip motor is also oh if you're gonna be very specific you should be the number of words is like let's say the number of words is okay there are K number of words so there are K stacks right and for every K stack this room builders is K times max width so the time compare the space complexity is the word of the words times the max width but you can also say just 0:01 I think not can also say just 0:01 I think not can also say just 0:01 I think not really short maybe you should be more specific and the stack in terms of because I used a recursive function it's gonna be it's not a vacation I'm sorry yeah this tag is that most one static so that's it I think it's pretty straightforward and from the super mission to see that my submission is really good thank you
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
1,952 |
hello guys my name is Ursula and welcome back to my channel and today we will be solving a new lead code portion that is three divisors with the help of python let's read out the question and the question says given an integer and return to if n is exactly three positive devices otherwise return false and integer m is divisor of and if there exists an integer case such that n is equals to K into M so what are devices I would like to tell you that devices has number which are divisible by that particular number for example the nth number is here too so if it is it's its devices would be one and two because they are divisible by 2. and if we talk about four you if we divide a 4 we will be getting three devices that are point two and four because they are divisible by 4 means it's they give a remainder of 0 means if I divide two by one I will be getting the remainder of 0 similarly if you divide by 2 I will be getting a remainder of 0 so if I get the remember of 0 that those number are considered as uh divisors so let's start coding this and just before starting coding this section guys to subscribe to the channel hit the like button press the Bell icon button so that you can get the decent updates from the channel so we have to actually return a Boolean value here true or false if it has exactly three positive devices we have to return true as we have written false so if you have to attack check this value 4 here it has exactly three values but here we have only two values so we will return false here and true here so let's start solving this question guys I will be creating uh value I is equals to 1 and then I will be creating result is equals to an empty array and or you can uh in Python you can call it a list empty list then while I will be creating a while loop while n is greater than equal to I then I will be saying if and mod I is equals to 0 means if n is divisible by I then return sorry result dot append I sorry n so exactly just before just like I have to talk about what are uh divisors are so if it is give it if it give us a remainder of 0 we will we should return it uh we should append those values of nth in the result uh list or you can call it array so when I have written this value what I will be getting is uh in my result list I will be getting result just I am talking about the two of these two example n is equals to 2 and S equals to four so if I talk about n is equals to 2 I will be getting result is equals to 1 and 2 in the result array and if I talk about result in the second section I will be getting one two and four when and is equals to 4 n is equals to 2 okay and I am just forwarding this one thing here that I have to increase the value by 1 as well because it will Can it can give us a error so I have to increase value in each Loop by one okay now just I have to return result dot length is equals to three so I have written this because if you see here we have to exactly check for three devices okay so it cannot be greater than 3 or less than three it should be exactly three so that's why I have written right if you see here result is length here is 2 and here it is three so you see that it is 3 here and if I could talk about n is equals to 6 maybe I will be getting uh result one two three and six that would be false actually so let's run this code and check our code invalid syntax while n is greater than okay so I have n is greater than equal to I it should run down l e n g t h okay so I have put a syntax error here so I will be saying Len result you see that it's working now and I have put I will put one more value here which is of course 6 here which will return as a false value because it has four value in it so it should return false you see that our expected value and output value are both same so this was all in the question guys hope you liked the video I hope you understood the concept here and if you have liked the video please comment in the comment section that you have understood the concept and you have liked the videos thank you guys for watching the video see you next time
|
Three Divisors
|
minimum-sideway-jumps
|
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Example 2:**
**Input:** n = 4
**Output:** true
**Explantion:** 4 has three divisors: 1, 2, and 4.
**Constraints:**
* `1 <= n <= 104`
|
At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane.
|
Array,Dynamic Programming,Greedy
|
Medium
|
403
|
1,184 |
uh so this question is distance between bus stop so basically you give integer array and also the starting and destination so what you're doing is you know Traverse the integer array the distant array right so in this Z represent what the distance between bus stop Z to one this represent one so two will represent another three four so this is a distance between uh bus stop right so we have a starting and we have destination so the dist is not going to just you know um written in the increasing order it might be just a random order so we have to know is the in clockwise is shoulders or counterclock way right is shoulders so you want to basically Traverse two uh two ways to get the you know the shortest distance right so uh this is a trick like using I +1 by n and represent trick like using I +1 by n and represent trick like using I +1 by n and represent L of the integer array to know um even though you are doing the counterclockwise you are still you know in the interval right you are still in the interval so I will have a helper function so I'm going to say public in get distance so in this helper function I have a distance array I have starting I have the ending right so it some represents destination if you want to use all right so okay so I need a result value and I will return result so for in I equal to starting and then I does not equal to the destination I'll just keep traversal and I will plus equal to this right uh it's going be this guy so represent the distance L right so you're still going to add you know increment one per time but depending on your counter clockwise or clockwise right if this is clockwise should be easy you know just increment one by one at some point you reach your destination right so you are not allow to say okay I L than distance right length like you are not allow to type this because you might need to you know um so just for example so imagine your starting is three and your ending is one right so you might you know hit you know Traverse uh I mean this is already last one right last one in Array index three so if you want to Traverse the clockwise you are you know you're not going to get the value uh the distance value right you access the full loop so it has to be does not equal to the destination and then how do we do this just PL distance I so this will be pretty much the entire solution for helper function so if you want to do the clockwise and conter clockwise it's straight for we swap the starting and destination inside distance right so I have a return M mean get distance so distance start destination and then comma so it's going be exactly the same idea but you swap the starting to the destination to the start so this will be the whole entire solution uh all right I know what happened so I shouldn't use a plus equal just equal like increment one by one right plus equal your you know um you accumulate every single time so it's not good all right so there's a you know I just have a type over here whatever so okay so this is the time so all of them right space is constant so whole entire space is constant times all of them right you definitely have one full you know four iteration inside the distance array right for the worst case so it's going to be all of them so this is all of them but they do it separately so I would say it's all of them I mean if you want to say n Square go ahead but I don't think it's n squ should be all of so this will be the solution um space is constant again time is all of so if you have question if a comment see you next time
|
Distance Between Bus Stops
|
car-pooling
|
A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given `start` and `destination` stops.
**Example 1:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.
**Example 2:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.
**Example 3:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.
**Constraints:**
* `1 <= n <= 10^4`
* `distance.length == n`
* `0 <= start, destination < n`
* `0 <= distance[i] <= 10^4`
|
Sort the pickup and dropoff events by location, then process them in order.
|
Array,Sorting,Heap (Priority Queue),Simulation,Prefix Sum
|
Medium
|
253
|
1,372 |
Ajay said that hey guys now in this site for wedding and in today's video we will learn to solve a problem basically which is called long, it is only for 15 days, first tip so let us understand this problem, what is this problem and then move towards its solution. Okay, let's see, first of all you will get the question here on your finger portal. By doing inventory pass by language, the name of the question is, you have got the return function and you have got the palmistry in which you have to tell the cigar pass. Binary Tree S Defined S. Follow issues including a boundary and direction left to right you can benefit use this question choose lie down go right go stick to direction his left day there right side order and if they on this issue left side scenery from left to right end Right to Left, so basically we want to say something like this, if you are right, if you are going towards the right, after that now you will go to NET, then you will go to the right, then left, then right, then left and right, on the left side, left and so on. If you aim at the start then you will go towards the upright then left then right then left or right and by doing this Shoan was able to make the biggest Sharif coffee. Inside the Home Ministry he just told you the length as if in the case If I start then I will travel by doing left right. Kumar and if I start towards right then I will go through traffic doing right left like this and the biggest problem I will face in this is this. If I want to tell you an example, I already have an external life, so let's look inside it, what kind of thing is this, then I move myself a little to one side and say, let's come here, see, most of the parties have talked about this on our left. The second color we use is green, this is our left right, now why can't I go right, I should be late to you, right left right, left and right, this is the biggest of people, when the path is still there, I get this, if I just go on the route, then right Amit If I can go left right left now I am not coming tomorrow. If this tree was not there, if this structure was not there then right left right. Now I am not able to go anywhere. I have to stay here, so this side is the best. It is not necessary that you always get the blog global path only from the root. Well, it is a matter of solution. This is the question in which you are left and right. The biggest clove teacher has to tell you the pass. Next. SRK will go to the right, if it starts from the right, then the network now sees its service whether it will do social money. Okay, so think of the object once, see how to normalize it, inside this question, we will customize it again like a note, okay. Okay, if these people should be included inside the see, if any person wants to be included inside the leaf, then what should he ask for on his left and right again, now this note Why would you want to become in the long A to Z pass? Basically long jump, you were coming from below. Okay, now I have come to this note and stopped. Now this note, if you mute yourself. Wants and wants to get included through his referee, then these people want to make respect pass because if he is left then he will ask for something like this from him, I am distinguishing two types of people here, this is the long as way pass through starting right. For example, for the rest of the people who are just starting, it would be more correct to say abortion, for the people who are just starting from 15, their two types of typing can be slow, either like this or like this, police typing will be slow, where did you go first, to the left, in one. First of all, there can be two types of people towards diet, so I open both these apps and take some names, I call this type of slots as forward slope and to this type of people, I tell the pack chords, show me the types of mine. One nearby is forward and one is backward and I also have a forward block and West year people, so I ask for both the time slots from the left side, I tell him, I also have left for it people who you have from the forward block. Please return to me the biggest Jigar Pattu that can be made while keeping the forward slow poison starting and also return to me the biggest thing that can be made while keeping the backward slow poison starting. Why am I doing this? Because I will need it on the right side, look at it, now he can have his friends on the side near this note, now this note is forward slow for the one who returns and this is backward slow for him, now the person on the left. The last person who will use its backwash logo is the light which is in it will waive the back Oslo loan but add the same time. If this child was placed on the right and not on the left, then I don't know who is its parent. He is next. Going deeper into it is its parents, it is that parental love, child rights and method in us, only then, if Mala's parents were here, if it had parents, then to make its own long as way, the parents include themselves inside such a long jackpot. To get it done, the way to use it for weight loss depends on which direction of the parents the child is enrolled in. If this style includes the blood pressure of the parents, then it will use it again and if it is The point is that if this parent is on the right side of the parent, then it will use its forward class to make the long way pass, then I will have to return two types of people, I will keep the fat from each note, meaning from my left and right side that Listen to me, I am a Naxal influenced person, considering myself as the starting point, consider yourself as the starting point, ask for long dress jug pass casting vote and give me the longest path that can be made from forward flat. At the same time, take out the largest long way pass made from the forward line and give it as soon as the largest language made from the forward line is 15 from one plant, but after the largest non-pass made on the backward class, after the largest non-pass made on the backward class, after the largest non-pass made on the backward class, how many lenses does it have? 1234567 If there is length with it then it will turn me according to two types - is length with it then it will turn me according to two types - is length with it then it will turn me according to two types - 1st length and 7th along with this someone will say that and I should not find myself starting like this i.e. lunges keeping the starting like this i.e. lunges keeping the starting like this i.e. lunges keeping the starting point of the abortion, while keeping the starting point of loan as the starting point, it will return me 25 and then one from forward. The longest character to be formed and the longest mention path to be formed from the backward classes. So what is the forward pass with the forward block? Here two lenses are made and one length is made from the backward classes. So I got the complete answer here. Now this root note or think this note will definitely think that if I want to include myself with this answer then what will I have to see what will I ask from my left side to become the longest Jik pass of its backward classes. That is, if the longest Vijay Ko Aatma is formed from its backward class, that is, the answer for me is what will it become from OnePlus One or what should I ask from its right side, who knows, the velvet pass pushes it and I, what do I know that Mukesh can do long back later on the right, so it is also possible that he will tell me one thing, at that time I will tell the right side that you should return me the longest is it back pass made from your forward slice along with it. By doing plus one, I commit the biggest sin. Okay, now only one of these two can be a maximum. This is true but there is an activist in it. On the contrary, if we assume that in future something like this will happen. Is it necessary to improve the route, think about it, since then the Belong web part is formed here, juice from here to here, or will you be successful, teacher pass unites here, now meaning my biggest longest easy one path should be like this It is possible that the root can be created by including toe and it can also be possible that it can be edited inside my factory and it can also be possible that it can be integrated inside Raj-3, then integrated inside Raj-3, then integrated inside Raj-3, then where will I get the long wait thing? I will say now I have fathered two types, I am going to get 350 liters, I will say three things in return to the left side or tell me who is the greatest teacher you have, tell me its value then I will say along with me in my forward glass The one formed by including Tere, considering Tere as such a starting note, the one formed from forward line considering Tere as the fastest starting note, the one formed from the forward line, wherever he returns, and the one formed from backward classes, considering Tere as such starting note, the greatest, formed by backward classes, on return. It is not necessary that the language product, I have told this that starting yourself is free, as it is clear that there is a press at the place of sir, it does not happen, I do this by clicking on this thing, do not make yourself such an officer, starting yourself like this. Considering the point, considering yourself as the starting point, with the forward slice, the biggest mention to me, considering yourself as the starting point, with the backward class, the biggest music passed, along with returning me one more thing, inside which it will tell. That which is the biggest cigarette pass inside your referee and I will stay here with the right too that give me forward slabs considering yourself setting a powerful s biggest longest day considering yourself starting such backward class biggest norms Give it to your wife for free and also return the biggest long this is it path. I am going to make three wellingtons. Here, I lightly roast it once and add this code to it and yours to that. We will present it on a small decision and see, okay, I will give you three paper questions inside the court, if you are enjoying this paste then it will be successful, let's see it once, so first of all I Here I am creating a class, tenth class, so friend, this is the setting class that we are creating here, I name it as repair, inside it there is a pinda vicho to keep, number one is, forward slice is 100 and word people say forward slow very. Slow is and Year Loop is Slow Professional 8.0 and Year Loop is Slow Professional 8.0 and Year Loop is Slow Professional 8.0 Candidates A Key and Backward Oak is Oak and Max Length Deputy Chief Minister has done that now if we call from here then call a function and what will its return type become Appear in pair 30 There will be a return, a long teacher pass is going to return and after that, if you consider your career as the starting point and your house as the starting point, then the one who is going to become a forward tow, then sitting and hiding the longest, first of all, take the same as constipation. Now the value of reporting is - one Now the value of reporting is - one Now the value of reporting is - one saver, I am keeping the tin number of educate them, which number of customer things are taken out, then its recording is kept minus one in the editor, if the number of note system is taken out in it, then its report is Now let's keep it zero. Now come here, if suppose my form becomes null, what does it mean to be null? Simply return it. Okay, now I keep the phone on my channel or do this, don't pinch me, return it then pair left it. I asked for 3 things, two-three pair left it. I asked for 3 things, two-three pair left it. I asked for 3 things, two-three things, which day, those three things, I have one, the largest object path with forward slot, considering myself as the starting point, and one with back support slot, considering myself as the starting point. The biggest bill is passed and the biggest Max Planck soldier is mentioned in his love story, so root dot net loot, with this, I was right to it, only then I go and take it out for the right, now pair my Answer is equal to two new pairs. Okay, now let's put our biggest coin. First, what can be the biggest teacher park of my answer, that is, I have drawn my neck length, inside which I am saying that I want to improve myself. It is important. It is not necessary that by improving me it becomes the maximum length, it is not necessary but I want to mute myself, then how should I speak? Send a light message. I want to mute myself, so I speak to my left side. Now I If I want to improve myself, then how should I ask for something from my lifestyle? While making it, send it to the address of two types: slow, forward and backward, While making it, send it to the address of two types: slow, forward and backward, typing is slow pack, forward, one is back but forward and backward, so if I want to improve myself then Left side return me the biggest J5 of your stupid flap backward follow back butt slot pack and I will add a plus one inside it so it will be one length more apps because you were finishing on the back foot and I If I am forward then here the pass is stopped, you are finishing on the right and I am going to the left, then doing left to right will become the most famous pass, so basically here I will say like this, Apne left ko left tere paas jo back or slow hai na a That if I come to Lok every year then it can be plus one but first I take out from method 8 maths of net that was Lok Maximo maybe that I have to see that I am making the biggest producer with this of my lifestyle. Along with this, it is not necessary to have a charioteer on the left side along with the right side, as here I am making the highest blood pressure but it is not compulsory, if I had more slots here, then the biggest coin would have been made in 15 Sterlite. That's why if it is not necessary, then you can also get benefits, if you can get my rights, then who would I like to go with, I myself, cigarette password, starting with whom, if you are the longest present on dislike, then because now I am going to become a shooting note, abortion. For the sake of respect, I will have to watch the match of these two to see whether I should make myself a starting idol with the left side or I should make myself a starting idol with the right side. So, what is the pack year for the left and forward verse for the right? So forward block for right is forward block right and at plus time will it really be a lunch? Think about it every time, is it necessary? Will including root toe make me a Max Planck instructor part? No, I am in left. It is also possible that it is also possible that not only from the referee but at the most I can get five and I get the subscription path for free, so I cannot say anything, I will get it here, which means I will have to add one more math dot maths, this one. You will have to install Metro, inside which now you will say here that brother, Maths Length, first check which of the two is in the electrolyte, then start Maths, is it Maths Length of left or Max Planck of A, now look in the laptop. The parts found in it were the biggest sin or the five found in the lighter were the biggest sins or either I was included, Root is becoming the biggest producer by muting me, so I will have to see all three of these, who knows Left Atrium Subscribe Who knows if I get a pass in this journey, who knows if I get the biggest coin pass by inputting such a fruit, then I came here, now by controlling myself, I know that wherever the entire route will be, I have got the highest pass. Is that tempered glass 24th right or is it made by including me? Now the question arises that I have to return the rally in the future, now who will be my parents, like this one may have parents at some point and this one too may have some parents, human ballot. I click somewhere in the unit, if it feels a cigarette, then why would it not do it, hoping that now you consider yourself as such a starting note, I consider me the biggest forward, I consider myself your accounting note, make yourself difficult with the forward block, accounting Let's say return pass with back crops, if you are on my right side, then side, if you are on my right side, then I will use your forward class and if you are on my left side, then I will use your backward class. I don't know which side I put my feet on, left or right, so I do 2 buttons from here, forward and backward, with people o my answer dot, what will the answer become with forward block and see how I automatically do with forward block. If I want to make a return, I will use the fact slot to make myself a clean and year location return. I am left don't pack word lok plus one. And if I want to make myself such a backward and slope return, I will make it from the backward slot. If I want to see most of the product, then where will I get the back one, I get the backward slot because this is the table cloth people, this MLA forward toe would have stopped the playback, I would have got this from the forward of divide, then I will get this from ka or right's forward safe and finally from here I will return my answer. Now see, where you call, what do you have to do? Pair answer is equal to long s, the score inside the decided path was root and answer dot maths lab. This has been done, so whatever question we have here. Inside, whose is it here, this is the whole game in this thing, you have to make belly fat in which way you want, if you get the returns in a good way, then you will get it absolutely right, let's see, now there will be a tab, then we will do it right 10 Sentences Hey, it is not there and I have passed it to you, okay, I have passed one strip and we are getting this done now Dona, I will tell you another way of doing it, we have written a lot in it, by the way, it is too much GD, absolutely this one. I had told this in my house world class, on which in the video, I clarified that this code is readable, hence we should do it, I should solve this question in the same way, but I will tell you another message method, which will be a little less interesting. The number of wearables will also be less and then that is not considered good, so the point of test is OBC vote is very correct, if you are giving the test somewhere, as if a company is giving water, what will you do with the deal within the online test itself. But I will do it to you in this way: As quickly as will do it to you in this way: As quickly as will do it to you in this way: As quickly as I can run this cord, how quickly can I type, how quickly can I make the skin tight, can I make a grand, do that. Inside the next question, our target is there, time is ours here. If I am sitting on an interview in target voice, my target will be to explain the person in front of me as best as I can. Now let's try something else, in which we will have to write a little less sentence. What am I doing? Bluetooth Settings Admin. I am making Static and Max Plank Pimple 204 public joint, now I am making 200 admins. Friends, let's see its history. First of all, the longest is the secret. This is my solution. 102 that inside this, now you have got the root of Prelude. Now let's see here. In this path, are they returning, after this, one of the saif forces will be our forward verse and one will be placed on the pack world no 1 in dr, forward will be placed on 0.1, back forward will be placed on 0.1, back forward will be placed on 0.1, back WhatsApp comes here first of all if my root is null. If you have gone, return it. New tent - Wave - Wave - Wave is time - This is the Yagya of our ancestors. is time - This is the Yagya of our ancestors. is time - This is the Yagya of our ancestors. Value of 100 - One. Let's come here Value of 100 - One. Let's come here Value of 100 - One. Let's come here first, we will make the left corner. Longest is a cigarette. Here we will do the root dot left main pin. Longest mentioned path is a root dot right and this is done for me ur right side now look F7 all done right settings just done now I want to say with my purpose so when I start the static name here not in the starting The special light is what is happening in the settings, then the largest clove on the left, when the largest clove found on the left, stores the valid boosted first and the longest clove found on the right, Vijaypath, opens the settings and opens its Play Store. So he already has the maximum of both of these, so what I have to do at every state is to make sure that you have updated it long years back by including me, every time I want to chat. What will I do after coming here? First of all, I will check my Max Planck in math dot maths of max length comedy. Left of Abdul with you. What will I see? Now I will check celebs tweet here. Aa loot tablet strip. I will find two types of people in it. One is forward. Back then this looter will use whose birthday, if he uses index two, then life of one index and other elements, the owner used to live, he will get it on life, that plus one is maximum, that is, I put a match dot match here and maths. Class 8 Maths of I left or torch light off 051 inscription is ready if I want to break my how I do n't want to see you will take from inputting my teacher pass my update what so how to do for this I am here But I will check something like this, I have two slopes, this is what I have, forward back, world player of hero, take care of, increase, this is healthy, this and off birth is dark, my name is that, and my answer to this is 0101. It is possible that if you come here, this is called 'Yaar Nice', this is called ' possible that if you come here, this is called 'Yaar Nice', this is called ' possible that if you come here, this is called 'Yaar Nice', this is called ' Left', this is 'Left Office Left', this is 'Left Office Left', this is 'Left Office E-Rot', this is 'Left Half One', this is called 'Right E-Rot', this is 'Left Half One', this is called 'Right E-Rot', this is 'Left Half One', this is called 'Right of Proof', of Proof', of Proof', I will call it 'Right of One', now I will call it 'Right of One', now I will call it 'Right of One', now coming to this note, what will this laptop one do now? Will you try doing plus one with this, should I do this? Considering this note as the starting point, back notes can be improved with many people because my left side is left, so left side, brother, if the pace of the input is very slow, then back. And with the slot, am I able to update the match live score and am I able to update the live score of the match with the forward block? If it is on the right side of the list, am I able to update the max plan with the forward block? So whichever match happens, plus one. Try and see if max live update is done, if not then return it to Delhi from here or return it from here. Enter two types of values in that new inch. To Enter two types of values in that new inch. To Enter two types of values in that new inch. To increase the for I because this is my forward and this is my back door. To increase the forward of backward, you have to look at the descendant of backward i.e. left. Laptop one plus one and right of two0 plus one right and why only plus one because if you If I want to see, I will have to see the white one forward, then it will become backward, then it will be near Florida with forward block, because of the location logic, let's do jewelery like rota, now when I will get the answer, then the answer will be found in the 21st. It is a long country from A to Z and here I have no use for this tent. My answer will be found inside Max Planck. I will update it with this Max Planck. Now see its sentence, its center, this sentence is very It is short, I wrote it very quickly, but what is its disadvantage, it is not just a code, it will be considered as dual core, so this is our prime code and this is our secondary code, so this is how to do good cup, I told you whenever you You are giving tension where even the doorman does not do it for you, then you should do this type of code because no one is going to do it, then what will happen to me there, I should submit the code as soon as possible but the cyclists who are not able to do it. First method: When will the job interview be held? First method: When will the job interview be held? First method: When will the job interview be held? You are sitting in front of the person, you have to show the product plan, then make a class there, it is good to go to the class, making a class will also become a good support model, I have created functions by breaking it down and then you will be given the rear It's too much, I hope you liked the video, if you have learned anything from this video, then do like this video. If you have any doubts, please tell us in the comment box and share as much as possible with your friends. Tell them that this is a channel where there is free content. They should know that by mixing something like this, it becomes difficult here and we make preparations for big attacks. So tell them this and for the first time on the channel. If you have come then maybe you liked the video then subscribe this channel and do not subscribe without any song, see you in the next video.
|
Longest ZigZag Path in a Binary Tree
|
check-if-it-is-a-good-array
|
You are given the `root` of a binary tree.
A ZigZag path for a binary tree is defined as follow:
* Choose **any** node in the binary tree and a direction (right or left).
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction from right to left or from left to right.
* Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return _the longest **ZigZag** path contained in that tree_.
**Example 1:**
**Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\]
**Output:** 3
**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right).
**Example 2:**
**Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\]
**Output:** 4
**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right).
**Example 3:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 100`
|
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
|
Array,Math,Number Theory
|
Hard
| null |
1,704 |
hey everyone welcome back to our coding Series today we are going to tackle an interesting problem that involves strings and a bite of a character counting if you are ready let's get D it this is a problem statement you are given a string this is our problem statement determine if Str helps are like means you are given an string of s even of length s split the string into two halves of equal lens and lets a be the first half and lets B is the second half and today the strings alike they have same number of vels let's take examples illustrate to make things clear let's look an example suppose we have a thing book suppose we have strings book now if we split into two2 and uh B and okay we see that both halves have one Vel each this is a Vel one and this is a v two the consider alike so the output is our examp this example be true this example is true like next another example s is equals to textbook we have to split here text and another B is equals to book but there is another the second example is there only one vels and only B therefore they are not alike they are not a like but here they are likes let's take an approach this is our problem statement and examples and let's take an approach first Define a set of o means we have to define a V here Define a set V means both upper case and lower case upper case and lower simply we will check out W here and check W number two initialize a count variable we have to initialize here count variable to track the difference between number of V means track the between numbers and Vel if the first half a and the second half b means book let's take an example this is a book we have to initialize here count variable and check here to the number of WS and divided for first half and second half and uh we have to divide here a equals to V first string and another is b equals to okay means these are two vs here but another strings so they are like a like and the return here true return true I through the first string and both and simultanously update the account based on the presence of V if the count at the end I trate if the count and I trate we have to return here return true your false we have a like otherwise written a false let's do it the our code implementation we have to we code in uh C++ and also python we have to implement C++ and also python we have to implement C++ and also python we have to implement both language how to solve this coding problem let's do it first of all we have to initialize here and an order set and we have simiz upper case and lower case and this is uppercase and we have to utilize a low first we have to count equals to Zer our end I is equals to always zero y IUS 1 find s I is equals to V do end we have to return here count Plus+ and return here count Plus+ and return here count Plus+ and we have to increase it i++ I ++ another Dot and find S we have incre length I vs dot count minus Plus+ and return dot count minus Plus+ and return dot count minus Plus+ and return here zero equal to Z then return this code is accepted here and then we'll have here return submit let's take another we have to solve a python code also written let's take this is a python code and we have to solve first we have in slid let's take we have to initialize bubles and return count it equals to zero I is equals to zero and while I is less than = to length s -1 and - I If s i in = to length s -1 and - I If s i in = to length s -1 and - I If s i in equals to 1 if s length s -1 and minus G sorry I invs here -1 and minus G sorry I invs here -1 and minus G sorry I invs here count minus is = to 1 and i+ is = to 1 count minus is = to 1 and i+ is = to 1 count minus is = to 1 and i+ is = to 1 and return is equal equals to zero then and submit accepted and submit this is today problem of the lead code of the problem of today and uh as you are there you have it we have successfully solved that the problem of determining if you a string halves are alike based on the count of vels I hope this explanation was clear and if you have any questions or suggestion feel free to leave then in comment below don't forget to like And subscribe for more coding challenges and explanation happy coding thank you
|
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 |
311 |
uh lead code practice time there are two goals the first one is to see how to solve this problem and then put in some code there a solution and then the code and the second one is to see how to behave during a real interview uh suppose you're given the question so let's get started so remember always the first step is to try to understand the problem uh what the problem is asking you to do and also um ask some questions to let the interviewer clarify in case there is anything you feel unclear and also think about some ash cases at the very beginning so let's see what this problem is so it's called sparse matrix multiplication and given two sparse matrix matrices a and b return the result of a b okay so you may assume that a's column number is equal b's row number okay yeah that's for sure otherwise you cannot really do this matrix multiplication all right so each matrix has the dimension uh so the issue of the dimension is between 1 to 100 and the number is between minus 100 to 100 yeah so it says it is a sparse matrix so it will so what it means is that most of the elements are zero so regarding sparse matrix um they're always um so usually you use some hashmap to represent it so the hashmap is something like um so the it's a hashmap of the hashmap usually it's something like this so it's hashmap it's the row idx and then the hashmap this is a column idx and then the corresponding value and all the values are not zero are non-zero non-zero non-zero um for this one let's see so let's see for this one we have the row index and the column index for this and then we would need to find so for this row each of the number we are going to get the corresponding uh columns okay uh yeah i think i got it sure so um yeah so like i said we will turn the matrix uh a matrix into this one and b matrix i would say it is first one first key is the column index and then for the inner hash map the key is row index this is for the easiness of the multiplication and okay so the next thing so okay so uh what about this what is the runtime for this so we are going to go through each element um uh it's hard to say it depends uh so first of all when we go through all the elements for a and b it is going to be uh let's say there are numbers in a and an m number is in b so it is o n plus m something like that and also what about the next step which is the multiplication so multiplication really depends how many non-zero many non-zero many non-zero numbers are there so yeah it really depends on that um so it can vary depending on the inputs like how sparse it is um but yeah i don't really have a good way to do it but let's start to do some coding and then maybe you can leave it as a to-do then maybe you can leave it as a to-do then maybe you can leave it as a to-do thing so first of all for the coding uh cargo the practice of the code and the readability of the code and of course the speed of the code so first of all you're going to say um map from the integer and this map of the integer to integer this is a matrix let's say just that it's called mayhem it's your new hash map this one and then uh we have the b we also defined the b so here so for each row each column okay so um uh okay and i is equal to zero i smaller than um a dot less and then plus i for j equal to zero j is smaller than a zero dollars plus j all right so um we will say this one it is um am dot put which is row index and new hash map yeah so this one we are going to say okay am dot get i dot put this is the j and a i j uh we need to have a condition so if a i j is equal to zero you just simply uh continue very similarly uh you're going to do the same similar iteration for it smaller than b dots lens plus i so remember how the arrays are stored during our commuter science class so we don't really want to like iterate by the column on the other loop so the inner loop is a better way uh for the re from the run perspective running perspective the runtime perspective for it consider uh the underlying storage for the computer so for this one if um let's say if a um m dot if not am dot contains key j then what we are going to do is um sorry this is vm so this bm will put um the j here and the new hash map all right so and the at the end we are going to say bm.get going to say bm.get going to say bm.get j dot what um i and then it is b i j and uh and it should be within it and uh we should also have a if to see if a bij if it's equal to a zero they simply continue all right so we are done with um transforming the matrix of the 2d array to the corresponding hashmap so the next thing is to compute each of the elements so we are going to say um in um see let's say the let's say let's call it a b it's equal new int um so it should be equal to a dot less and uh okay so what is that it is actually b0 lens the lens i think okay so it's p zero dollars okay um sure so okay so i is equal to zero i smaller than um a dot lens plus i is for means j is u0 j smaller than b 0 dot lens plus j so we are going to compute the element for i so for a b i j it is actually uh the ace column sorry the a0 and the b's column so uh so we are going to get um map integer to integer so it says arrow is equal to am dot get and the map in theater integer beer b column is equal to bm.j is equal to bm.j is equal to bm.j and then we are going to go through uh one of the things so we are going to say um okay so we are gonna say uh for keys uh so this is the column yeah so this is a column index so this is a column for a row dot key set uh yeah so if uh we need to have the sum say let's say the cell is equal to zero so if um b column. contains uh key this is a column then we are going to say all right cell plus equal to um a uh row dot to get a call times um b call dot get a call all right so uh it's like a row times the column okay yeah so and finally we are going to set a uh ij as you go to cell and then we just simply uh return a b uh it's abi abij actually or we don't really need to do it uh because uh it is a b i j is actually that so it's just a b i j equal plus equal to that's just enough all right so uh remember after the coding i always do some testing using doing some scientific check by going through this example uh by going through some example and do some sending check at the same time explain how this piece of code is going to work and then try to some set up some different test cases so for this one let's go through it so we will have am let's see the first example uh actually there's only one example here so it will be am equal to something like um zero uh if it is equal to this other than that okay so it's zero to one and then we have another thing which is one uh and the first column is one sorry zero and then minus one another thing is uh two three okay so that's the am and then the bm would be something like bm is um so it should be j as a key and i as the inner key so it is we are going to say okay so the first row is zero so we will have zero and then this is uh zero seven and then we have the one certain one will be so actually don't have the one here that is because we have already skipped that um yeah so that's um that's interesting uh yeah that's interesting so if that's true then we may it may result in some kind of bug because this guide is going to try to get something that doesn't look the other nick doesn't exist in um it doesn't exist in the bm so if that's the case uh what should we do um yeah so i'll say if bm dot contains uh key so if it doesn't contain the j row then we are going to simply continue yeah so that's it and this set the last one is 2 to the 2 1 so that's the thing okay so let's go through this piece of code to see if the fix is really going to fix the issue so for the for zero we are going to get the first row zero first row and the first column get them together uh for zero we are going to for sure compute the we are going to have arrow and uh zero b column okay then we try to get a key and which is zero and then we get seven touch up okay so a zero is seven let's see a zero one so a01 is going to be this row plus this press the empty column so if it is empty column they just simply continue all right so i think it mostly seems to be right to me um let's give it a shot all right so it's um okay some title here all right so it looks good um i would say yeah and it looks good so i would say um yeah this is pretty much about the question and the regarding the test case setup i would say if you have an example like this it should be if it should be perfectly enough for uh for this all right so that's it for this uh coding question uh if you have any questions regarding this puzzle or about the solution feel free to leave some comments below and if you um if you like this video please give me a thumb up and subscribe to this channel i'll see you next time thanks for watching
|
Sparse Matrix Multiplication
|
sparse-matrix-multiplication
|
Given two [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix) `mat1` of size `m x k` and `mat2` of size `k x n`, return the result of `mat1 x mat2`. You may assume that multiplication is always possible.
**Example 1:**
**Input:** mat1 = \[\[1,0,0\],\[-1,0,3\]\], mat2 = \[\[7,0,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** \[\[7,0,0\],\[-7,0,3\]\]
**Example 2:**
**Input:** mat1 = \[\[0\]\], mat2 = \[\[0\]\]
**Output:** \[\[0\]\]
**Constraints:**
* `m == mat1.length`
* `k == mat1[i].length == mat2.length`
* `n == mat2[i].length`
* `1 <= m, n, k <= 100`
* `-100 <= mat1[i][j], mat2[i][j] <= 100`
| null |
Array,Hash Table,Matrix
|
Medium
| null |
380 |
Hello hello guys welcome to good that medicine today will go through the date when problem in all delete random please like video any fear you don't forget to subscribe to our channel this mixture plate design data structures in operation in which light from inside your mind and intellect And Elements Of Duplicate Values Of Complexity Of Using Function In No Mood To Have That's Why Swap Window Current Which Viral List Smooth Duplicate Keys In Exam And Average Complexity Of Doing Research And Elements Of Fun But A Random Function Needs To Have Same Probability For All Elements They need a relaxed and can not be used on time lon show with this combination with control 3501 one so let's see who wins and element which gives the limited system app not withdrawn in the elemental states and also in map with elements done index in least S Value Day UK True Value Has Presented In Force Also Support 1974 Elements And Have A Blessed And App Settings For Prelims Updated With The Latest And Important In Map With Value 10 And Return Form Elements That Existing In To-Do List Elementary Already To-Do List Elementary Already To-Do List Elementary Already Existing in map element Existing in map element Existing in map element person video latest and updated on the coming ulas function will see how will remove the element let add one more person the best site for elements support need to delete sex with value teen map divya last index play list jai Hind is case will simply delete element from the map and list no what is the element id is 7s value amazon vinod it is not the last element will not disturb interview with flute and update the last element with current president the list by value Of and nor they will update the induction the last value with current index in the map in this case also update valley of pain in map 21219 valve * is delete the current element from valve * is delete the current element from valve * is delete the current element from map last element from list that belgarh tamil actress is person distance map 10th Seed Element at Index Sessions Index of List of Its Not Take Place and Current Value in List Velvet Glass Index 10th Updater Index The Last Value in Map with Current and Actions and Digital Art Index and Current Value from Hills They Need to Just Did the Last Date From lust and current value from day uk true value did not exist when will return forms exact same pattern method in java coding description in that time complexity forget random function is always of mind insert and delete will be open in every time but half man in verse Case Scenario Space Complexity Will Reopen On Thank You For Watching My Video Flag Video Please Like Share And Subscribe Our Channel Platinum Infection What They Think The Video
|
Insert Delete GetRandom O(1)
|
insert-delete-getrandom-o1
|
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Medium
|
381
|
724 |
hey guys like guys let's look at seven to five find the pivot index we're given a array of integers we will find the pivot index which means the sum of the left numbers is right to some of the numbers to right if note not exist we should read term minus one if there are multiple we should return left most favorite index so like this is three four because this one is 11 this one is everyone okay let's first tribe rule for it I think it will be time limit exceeded but this is free it's free Astrid for let's say for let's I it's just the baseline is that just start from left to right from lace maybe it's okay so 0 I swear that names and I plus so that's some left equals zero for net J equals I minus 1 J a speaker than minus 1 J minus nice son left plus equals J let some right 4 0 4 let J equals I plus 1 a spot I got Nam started us some right plus equals 2 while Island is different anyway this cake let's make it cake oh hi this is okay if some have holes some right we just returned I and there were ten - one should be and there were ten - one should be and there were ten - one should be working James 95 it's possibly to have all its fattest accepted it but it's run very slowly let's say what you came to know it's not a problem about some we must remember that we some most of it I'm not support it's a high possibility that we came proof by not just something about but cash to some or substract substrate from different sounds ok so let's say when we try out covers through array like we choose 77 we calculate some here some of some three six seven choose three sum of seven one say with someone here actually really it - actually we don't actually really it - actually we don't actually really it - actually we don't actually that these horrid oops it's actually is Oh N squared I'm complexity we can if we choose the people here we can use the some here versus reverse on here right yeah so that we don't need to this one and for this one we have okay we can accomplished by Oh N and yeah we have we can just uh Wow I've got it's very simple okay we first calculate it gets the some array you okay so it's uh some that sound equals zero so we are saying some plus coulombs some left that someone write equals zero for that Jay cause mom's minus one secret that nice one Jay right okay this is the first round so and then the last round I'm K equals zero case one announced then okay plus if some boost okay equals zero then it should be zero if not there should be some left K minus one that's the Sun right because K equals minus 1 if it is it should be 0 but if not some right to list count from this one so we should be recounting minus k plus 1 and this is the count here so the index should be minus 1 maybe not sure wish push about shift in that case we should say okay some son uh-huh okay password even do compare comparison I hope you would be faster any proof lot but not the fastest have we improved it better just continue from last problem with it's the subscription of the salmon so if you calculate this here we will calculate it actually the sum is sum here ah yeah actually we don't need to sum list we only need one yeah some list sounds ok so we don't need this gray you'll miss this loop so you first came out okay so some left if sure you should if not should be psalms k minus 1 but it's alright if K is there's no right but if not there is a son nice one - songs there is a son nice one - songs there is a son nice one - songs okay yeah Wow okay we improved a little bit but still cannot match top 50% we need to still cannot match top 50% we need to still cannot match top 50% we need to improve when you improve actually sanctuary actually we need to need this extra we don't need this actors face honestly giving me some discount we only use it once so we don't need to store them for all the time we only need the Sun okay and we can do the math yes the sum is zero so sum plus this one so we get the total sum all the gates and all and then we when you're traversing left next some left:0 so the some left if K is bigger than zero some left plus equals K okay so what did it and so we can do just direct calculation if some left plus if some last I think yeah it's bigger than one is okay because if the heat bigger than zero how bigger than yours is okay to zero I can count it this one right some lips 2 plus K equals some return cake hmm doesn't change much like sort of thing come complexly yes it's a oh and for one we need to quickly compute the sum of values to left or right so let's say we knew answer the some our numbers they ran in X we knew the some of them that numbers are to the today and then the other some of the right index will be s is nice as such we only need to do in there for some the sound left some for anti now some and then there's some snake some return yeah this is the same as this one but why let's we are slow let's look at the fastest solutions what they did reducer reduce what they're doing particular get the fastest one this if zero minus one if one flips one it's left some my son okay my son plus lumps hi this only was right son which ones I counseled I smaller than this they have some class personally cause this is so revives home why they're so fast left my mad right from - let so Muslims if their son my son which while this why this is fast much faster than I than my solution will be the at the edge cases and it's goes 1 return-1 oh yeah it's and it's goes 1 return-1 oh yeah it's and it's goes 1 return-1 oh yeah it's actually yeah it's the edge cases wow this is missing affects our performance yeah so our solution is not bad maybe this one is better it's very easy to understand this is better to understand I think we just need to f-stop them equal 0 return -1 if f-stop them equal 0 return -1 if f-stop them equal 0 return -1 if constants because 1 return 1 ok submit this is our Wow this is slower yeah we don't need some we don't need the extra array we wanna needs us to meet the some somet hmm yes we anyway it's this is good enough I think so thanks for listening hope to see you next
|
Find Pivot Index
|
find-pivot-index
|
Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
|
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
|
Array,Prefix Sum
|
Easy
|
560,2102,2369
|
771 |
Hello viewers welcome back to years and this video will see jobs and stones problem Vishram list to day two of the match challenge so let's look at problem statement problems youth springs representing the life to those were present in stones character in life you have You want to know how to change a rented u and all characters in j&k sensitive way is considered to be u and all characters in j&k sensitive way is considered to be u and all characters in j&k sensitive way is considered to be different from capital so let's look at some examples in do subscribe must subscribe to city sensitive way itself is always different from this capital that distance of different 9 2010 Tone Speedy Stones So You Want To Find How Many Bones To Do You Will Make Each And Every Time You Will Not Available On This Value Computer subscribe The Channel and subscribe the Channel press The Amazing Center And You Will Pass All The Best Practices Free Number of justified indigenous sample approach and what will be the time complexity for this time complexity will be the length of is multiplied by the length of the sense for each of the stone in every character of the con is of interest for the Time Complexity Minimum Should We Do The Time subscribe The Channel and subscribe the Channel Question Every Stone Swadesh A Will Represent This Capital Will Also Be Present In The Small Civil All President 9th Singh All Types Of Waves Continue Set You Will Participate In Every Storm Which You Have And You Will Also Give Very Short Dresses Width subscribe The Channel subscribe and subscribe this Total Time Complexity of Subscribe Understood As Very Simple Latest Cases The Code Simple Court Which Have Written Using Map Hair Receiving Strange and Winous And Take Off But Map Android Stone Witch In Turn Will Take A Counter In This Zar-Zar Acid Present In This Present Zar-Zar Acid Present In This Present Zar-Zar Acid Present In This Present And Finally Bigg Boss Subscribe Different Languages Like Share And Subscribe
|
Jewels and Stones
|
encode-n-ary-tree-to-binary-tree
|
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.
**Example 1:**
**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3
**Example 2:**
**Input:** jewels = "z", stones = "ZZ"
**Output:** 0
**Constraints:**
* `1 <= jewels.length, stones.length <= 50`
* `jewels` and `stones` consist of only English letters.
* All the characters of `jewels` are **unique**.
| null |
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
765
|
853 |
hey everyone welcome to my channel so in this video i'm going to try to solve this problem try to put some code in and also at the same time i'm going to follow the general interview steps while trying to solve this problem so first of all let's read through this question to get a good understanding so there are end cards going to the same destination along a one lane road the destination is target miles away so each car i has a constant speed i and the initial position towards the target along the road so a car can never pass another car ahead of it but it can catch up to it and drive bumper to bumper at the same speed so the destination between the two cars is ignored they are assumed to have the same position a car fleet is some non-empty side of the cars driving some non-empty side of the cars driving some non-empty side of the cars driving at the same position and at the same speed so note that a single car can is also a car fleet if a car catches up with a car fleet right at the destination point it will still be considered as one car fleet so how many car fleets are there that will arrive at the destination so let's see the example we have targeted as 12 we have 10 8 0 5 3 as a start point for each of the car speed are 2 4 1 3 so the output is three let's see the explanation so cars starting at ten and eight become a fleet because they meet each other at twelve okay so it makes sense because car one is two miles from the destination speed is two and the car eight car two is uh at the position eight which is four miles from the target and the speed is four so they're going to depend spend one hour uh to arrive at the target so they are going to be arriving at the target at the same time and similarly uh we have the following cars and we have three coffees at the end so let's see the constraints first we have n which is number of the cars anywhere between 0 to 10k so okay so if we have zero or one car then we don't need to do anything we can think about that as an ash case but i think it should be also it should also be covered by our general solution as well so target is anywhere between 0 to 1 million speed is 0 to 1 million and position is anywhere between 0 to target but not at the target so all the initial positions are different so we don't need to worry about same uh different cars starting at the same place all right so i think that makes sense in general uh the only ash case i can think about currently is if there are zero cars or one car then we just need to return and without doing any further computation so let's see how to solve this problem in general so i think the most important part is this sentence which is uh sorry this one so okay which is this one so a car can never pass another car ahead of it but it can catch up to it and drive bumper to bumper at the same speed so essentially saying suppose we have a slow car and the faster car once the first car catches up with the slower car then they're going to go with the same speed which is the speed with of the slower car so this arrives us at a first solution i can think about which is um so let's say each of the car has a corresponding position so uh the condition for a car for a faster car to catch up with a slower car is the slower car is ahead of the faster car and the faster car can catch us up with a slower car before the destination or at the target or at the destination so what we need to do is uh we just need to sort the car based on the position so if we are thinking so essentially we are thinking about the distance sorting by the distance to the deck to the target to the destination as any other so in our case we can also sort the car using the position in this and the other which is the same effect as i talked about so this the solution is first of all we are going to sort each car by position so this is going to be descending order and then for each of the car we also have the speed so we could use the distance from to the destination divided by the speed then we can uh we can compute how what is the hour how many hours are there uh for the car to arrive at uh the target place or the destination okay so it's something like for we are going to sort each card as position and also we are going to have and for each car we will have the time to arrive at target so for this example let's say we have 10 8 0 5 3 so i say we are going to sort it so this is 10 and the second one is 8 and then the third one is 5 and then 3 and then 0. so for car one it's going to take one hour to arrive at target car two it is one hour as well so for cars three it is going to take 12 for car i'm sorry for car 5 it's going to take 12 and for cars 3 it is going to take uh so sorry this is okay so 5 the speed is one so this is going to take okay this is going to take seven and four so for this one it is going to take because it is nine so it is going to take three hours to arrive at the destination and for this car starting at zero it is going to take 12 hours so essentially after we sorting uh our to resort by or by the car position and then we just see uh we just do a linear scan towards from the beginning uh towards the end of the array so we see okay the first car uh it takes one hour the second one takes one hour so we can merge the two cars uh to the same fleet and the third car it takes seven hours which is longer than one hour so it is going to be a separate fleet then we start to form a second fleet and we see okay the fourth car arrives uh kind of can potentially arrive at the destination before the third car then we merge them into the same fleet and then we see okay 12 uh it takes 12 hours for the last car to arrive at the destination which is longer than three then it is going to be a separate fleet so essentially it is like after resort um we do a linear scan and then once we see the hours we spend to arrive at the destination is longer than the previous one then we start a new fleet car feed so that's essentially how we solve this problem the runtime is going to be unlocked and so the most time consuming part is the starting part okay so i think we can get the general solution so let's try to do some coding work for this uh for this approach so as i said if we okay so we don't have an n so it will be something like if position dot once is smaller than two then we just return uh position the ones that's the ash case i talked about if there are zero or one car then we don't need to do any uh competition and then the next thing we are going to do is we will define a class let's say have a private clause let's define it as a car and then it is going to have the position and also if you have the let's say the time is how many hours to spend to arrive at the final destination so you have a constructor for it say this is the position the time so this is quite boring code is equal to time so that's the uh definition for the car and then we are going to have an array for the car so let's see if we have um yeah so this would be car cars is equal to new car this would be position dot plus and we are going to fill in each of the car so i is equal to zero smaller than position plus i so let's say uh in time is equal to target minus position i divided by the speed i then we have cars i equal to new car uh first of all it is a position i and then it is time so after that we are going to sort the array so we are going to sort the cars with new comparator character so this would be a new comparator this would be public out over at public compare i think and then this is car as car one car as car two so first of all we are going to sort by the position so if the position so it's going to be this any others so first of all it is going to be indecent okay so we are going to sort by this by the position because the condition says that each of the position is going to be different we don't need to carry think about the condition that two cars starting at the same position so what we just need to do is we just need to return car one dot uh car two dot position minus car one dot position all right so after we sort i'll do one linear scan from the beginning towards the end to see the number of weeks here so number it's starting at zero so uh okay so let's starting at one so we just we need to start from the second car actually because we want to leave well like a one offset for our comparison so if the position let's say if uh car i dot speed it's if it is larger than cars i minus one dot speed then we are going to plus num fleets and then finally we will have num fees to be returned all right so i think we got most of the code let's i'll just rely on this platform to help us to do the debugging work um okay so line 16 which is oh okay so private static privacy clause car so it says compare illegal start of aspiration this is protected or i'm not sure or it is compared to uh okay so i think it's really public uh so let's see java override new car um well there is i have some java custom swords okay so erase java collections those swords okay so it would be so this is okay so i think i missed a yeah i think i missed a uh no yes i did miss something there sorry i think make some mistake about the syntax uh let's try to see another thing okay so this is not speed this is time another typo after we fix it okay so now it's accepted let's do a submission for it okay so it is wrong answer let's see why it is wrong so we have six and eight and this three and two so we have six which is two hours to the destination and well let's see so 10 and six this is 1.3 hours this is 1.3 hours this is 1.3 hours this one it is going to take two hours so we should get uh so we should be able to output as one well so we have eight to ten which is two miles away it takes one hour to arrive at the destination and this one oh okay so it should be double like actually yeah so it should be double um yeah should be after we have we just need to have like a yeah i think it should be double i think so this time is going to be double let's change it to be otherwise it's going to do the floor stuff for the weight for the division yes let's run the other task case which is this one yeah let's transfer it okay this one it works uh okay let's see this one why the output is two but we are expecting as one let's see why so we have ten zero two uh so this one is going to take five hours this one is going to take uh six hours this one is going to take okay so let's see so we should after sorting we should have five sorry four and this should be six it's going to take six hours and this one to eight it's going to take eight divided by straight this many hours and then the last one is going to take 5 hours so output is well 10 and 2 1 so why this one it takes eight okay eight miles away this is so we should be able to merge the first one the second one together but okay so i think i made a mistake that is because after the first car and the second car meet with each other they're going with the same speed and then after they're going with the same speed essentially the comparison should be between the first car in the fleet and the further and all the other cars okay so let's see how they do it um okay so let's say we have uh fleet uh first car in fleet so let's say this is going to be zero and then we have if car.i that time is if car.i that time is if car.i that time is larger than the car first car in fleet then we are going to have plus num fleet and first car in fleet as equal to i all right i think this time i think is going to solve our case here all right let's do another submission here okay so this time it's uh accepted sorry i made some mistakes here uh so in general uh when we do the comparison we should actually consider the first car in the fleet with the rest of the cars because uh the first car can be slow and slow down the car that comes after it so that's it for this uh coding question in case you have any questions regarding the solution or regarding this piece of code feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Car Fleet
|
most-profit-assigning-work
|
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away.
You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour).
A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).
A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.
If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.
Return _the **number of car fleets** that will arrive at the destination_.
**Example 1:**
**Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\]
**Output:** 3
**Explanation:**
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.
The car starting at 0 does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
Note that no other cars meet these fleets before the destination, so the answer is 3.
**Example 2:**
**Input:** target = 10, position = \[3\], speed = \[3\]
**Output:** 1
**Explanation:** There is only one car, hence there is only one fleet.
**Example 3:**
**Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\]
**Output:** 1
**Explanation:**
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.
Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
**Constraints:**
* `n == position.length == speed.length`
* `1 <= n <= 105`
* `0 < target <= 106`
* `0 <= position[i] < target`
* All the values of `position` are **unique**.
* `0 < speed[i] <= 106`
| null |
Array,Two Pointers,Binary Search,Greedy,Sorting
|
Medium
|
2180
|
129 |
Hello friends today I'm going to solve liquid problem number 129 some route to Leaf numbers in this problem we are given the root of a binary tree and each of the node consists of values starting from 0 to 9 only and we have a route to Leaf path and for each of this root to lift path if you represent the path in the form of number that is for example a rooted Leaf path from one to two to three represents a num number one to three then what we need to do is for all the route to Leaf pads we get a number and then what we do is we add all of those numbers and return the value of that number so let's look at this example here in this example we have the root 1 and V node 2 is a leaf node because it doesn't have both left and right child children also three is a root Leaf node so we have two root to Leaf path one is from one to two and the another win is from one to three so from one to two we have the root to lift number one twelve and from one to three we have root to leave number 13 so when we add both of those numbers 12 and 13 what we get is equals to 25 so that's our result here in this case we have three leaves which means that we will have three root to leave path so One path is four nine five so that would be a number four nine five another one is four nine one so we have next four nine one all right and next one is four zero so that's four zero and we take the sum of all of these three numbers and the resulting sum is equals to one zero two six so that's what we need to do so now we understand the problem let's see how we could solve this problem so if you look at these numbers What's Happening Here is we are starting from the root and we are going each depth right we are going each depth flow so from 4 we went to nine from nine we went to five and then since it is a leaf node we constructed the number out of that and we that number would be added to the next lift to root node so what we'll do is We'll add this to our result value and then now we go backtrack and we go towards its next child which is one and that would create a new number that is 491 and then we add that to our result we chat the value 495 and we get the result of these two sum in our result and the next case what we do is now we backtrack from one to nine and from nine to four and then we go to its another child which is zero and then since it is a lift node we get the number four zero and then we add to our resulting sum and that will give us our final output so that's what we will be doing so we'll be using depth first search in this solution so let's start coding our solution using the depth first search before that let's also look at the constraints so what are the constraints the number of nodes in the trees in the range from 1 to 1000 which means that there is no empty node so we do not need to check for an HK square root is not also we don't need that however we could still do that so what we will check is if root is known so if not root then return 0 because there is no numbers we are going to return a zero but since the range is from 1 to 1000 we want to encounter this however it's good to have the H cases in our functions and next is the value ranges from 0 to 9 all right and then depth will not exceed 10. okay so now we know that depth will not exist 10 and the range of the values we can now construct our dipped first search so what are we going to do is let the fs equals to function and for depth first search um we will need the root that we are currently at and also since we are constructing the number from um root node to its Leaf node so from root to Leaf node we will also need to keep track of the paths that we are following so basically we will be um keeping track of these numbers so we will have to pass two arguments that is the node that we are currently at and the number root two Leaf number we have encountered so far and now here we are going to check for the h cases if we have reached our Leaf node that is if we have reached our Leaf node would mean that it doesn't have left and right children so if not node left and not node right that would mean that we have reached the end so let's create our resulting integer so in that case we will add to our result the number but since our number will be a string we need to pass it into an integer so we pass it into an integer if not then what we need to do is we keep on going to each of its depth so we check if note left is present then we go towards the left Note and Note that left and we add the value to our num so we update the value of our num so it okay what we can do here is num plus equals to node value here so that we will just pass our num here and then similarly if in case not right is present then we'll pass DF as the right node and the num so num would be the path that we have encountered so far and when we'll call our DFS function we'll pass our root node and an empty string and then finally we are going to return our result so let's awesome so talking about the time complexity since we are it going to each of the node towards both the left node and right node and traversing each of the node in the tree that is the time complexity becomes o of N and the space complexity is constant
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
307 |
what's up everyone today we're gonna be going over Fenwick tree and then we're gonna be going over leak code through 0-7 now this video is gonna be a little 0-7 now this video is gonna be a little 0-7 now this video is gonna be a little bit longer than my usual ones because I'm gonna actually explain the data structure I have to derive it and draw out the diagram and then I'll use that to solve 3:07 so before don't just to solve 3:07 so before don't just to solve 3:07 so before don't just ignore just leave know this and you know this so before we even talk about a Fenwick tree let's look at an array and two very common operations we do on the array let's take this guy for example so two very common operations we do is we want to find out the sum between the beginning and some index there right so from zero one two three four so whatever index we say we want int sum and we give it an X like that like a index X and then we say int results and we say for int I is less than X I plus res is incremented by let's say this array was a are incremented by a R and then we return result so that's one commonly used thing and then another commonly used operation on an array is increment so R into X rather an interval so someone this is nine if someone wanted to increment this by ten I can just say they are of X is incremented by about oh this is void actually this void so okay so before even a Fenwick tree before we can talk about that here's an array and two common things we do is we find the sum between beginning and some index I and we increment whatever value what whatever value and a given index X by the argument develop so the runtime for this is o and the runtime for this is o of one which is not really bad however if we want to constantly get the sum and also we are going to constantly increment it and the array is not going to be static then we probably want to do better than open and O of one so that's where Fenwick tree comes in we're going to improve the some time complexity by giving up a little bit of the increment time complexity so regular array and we have a Fenwick tree array so some is it gonna be open increment there's gonna be of one and this thing is gonna be of log event that's the improvement and this is a log of it that's the trade off now cool so I already explained why we want to do this if the array is really long if there's constantly changes being made to the array and we're still trying to query the sum that's when we would use a Fenwick tree now the cool thing about a friend wick tree array is that it doesn't use any additional space apart from the Fenwick treat array itself and even though it's called a Fenwick tree the data structure is actually an array it's just our logical representation of it in our mind is kind of shaped like a tree and cool so the question is how do we go from Oban to log event now before I even draw the diagram of the tree I'm going to show you how that happens how we're getting love in so once again let's take our helper are all right we are getting extra by doing this so first we group them everything together in groups of two listen I go six this is 24 this is 6 this is 10 this is gonna be 18 and this is gonna be 16 and this is gonna be 34 so we're pretty much pairing them together in our original code if we needed the sum from the beginning to here we'd have to add this and I'll be O of n but in the Fenwick tree yeah if we want the sum till here all we have to do is add this guy and this guy we're just 18 plus 4 is 22 if we add this here to here oh sorry from here it's here let's see what happened 1 plus negative 7 negative 6 plus 15 9 plus 9 18 plus 4 is 22 plus 2 is 24 and we're getting this is how we're able to go from our end time into log of end time cool this is just to help us gain the intuition the actual Fenwick tree is like a vertical it's not put together like this but now you can see how we're able to improve that some time complexity so much know so now it's when someone gives us a regular array let's figure out how we can get a Fenwick treat array from that now when Fenwick introduced this the trick he used was first by making the Fenwick tree indexed by 1 so we do that by whatever length of array we get we make our fender tree one thing bigger so if there's 8 this is gonna be 9 so just total of nine spots right 9 blocks so 9 blocks I'm gonna be represented by 4 bits it's gonna represented by 4 bits now a I've seen different implementations of how to initialize Fenwick tree a lot of them you might have seen might be an N log n but the way I'm going to show you is initialization in o n time so we have to use 4 bits to represent 9 blocks because we can't use 3 no in the Fenwick treat the first one the first note is always gonna be a dummy node right so this guy and we're using 4 bits this block is gonna be this block now that's the first level now we're gonna have level 1 on level one we can only use one bit on level one it's gonna be we're gonna get one it's gonna be represented by 0 1 now we have 2 here 0 1 0 then we have 4 0 1 0 then we have 8 and this is 0 1 0 alright so on the first level all our blocks are only consisting of numbers which use a singular bit now cool so this is 0 is this buck is this block this 4 is this block this one is this block now we have 0 1 2 there's no number between 1 & 2 right okay now we number between 1 & 2 right okay now we number between 1 & 2 right okay now we do 2 & 4 is there a number between 2 & 4 do 2 & 4 is there a number between 2 & 4 do 2 & 4 is there a number between 2 & 4 yeah we have 3 so we need 2 bits to represent the number 3 so that's gonna be in our level 2 oh wait this guy comes here 3 & 0 1 oh wait this guy comes here 3 & 0 1 oh wait this guy comes here 3 & 0 1 no sorry 0 1 0 yeah adding 1 so 0 1 2 3 4 now between 4 & 8 do we have numbers yeah between 4 & 8 do we have numbers yeah between 4 & 8 do we have numbers yeah we're 5 6 7 we can represent 5 & 6 using we're 5 6 7 we can represent 5 & 6 using we're 5 6 7 we can represent 5 & 6 using two bits so they're gonna be in level 2 5 right this is it who's 0 1 and then 0 1 0 it's gonna be 6 now we still have 7 we need 3 bits to represent 7 so that's gonna go on level 3 cool now we pretty much about the skeleton of our Fenwick tree this is just initialized and our tree diagram is a logical representation of which blocks are connected with which blocks so this is zero is this one is 1 two 2 three 3 four 4 five 5 six 6 seven 7 eight 8 the parents of 8 is 0 a parent of 7 6 a parent of 6 is for the parent of 4 is 0 the parent of three is two the parent of two is 0 the parents of 1 is 0 now you might be wondering why is that now the very core trick behind the Fenwick tree is that to go from a number to its parent you have to remove the rightmost one in other words the rightmost set bit so to go from 7 to 6 you just take away this one to go from 3 to 2 you just take away this one the little code for that is this parent equal to I minus I and negative I let's do that for 7 we have to apply if I seven we have to get the parent we're just 6 so 7 is 0 1 negative I or negative 7 in two's complement is it gonna be 1 0 1 so what do we do with these we're gonna do an end on them right so this is 1 0 so this part breaks down to 1 and then initially I is gonna be 7 so 7 minus 1 is 6 and that's how we get there you can feel free to try for whichever block you want but that's the trick for to go from a node to its parent cool so that's why the parent of seven is six and the pair of six is for us because we can go from this number to this by taking away their right most set bit now hold that thought for a second let's begin building our tree now before we get our final Fenwick tree there's gonna be one intermediate step which is a very self-explanatory is we need to a very self-explanatory is we need to a very self-explanatory is we need to cumulatively some everything that's in here and put it in the Fenwick tree so this is 0 plus 1 plus negative 7 negative 6 was 15 9 plus 9 18 eise to 22 was a 24 it's 24 and this is 34 cool but this is not our final Fenwick tree it's just the intermediate step remember I told you this block is these blocks are representative of this so let me fill that in negative 2 is negative 6 3 9 4 is 18 4 5 is 22 this is 24 there's 24 cool so right now our friend wick tree holds a cumulative sum of all the integers incrementing upwards but isn't on our final to make it final we do one little thing we take a node and we take away the value of its parent from that node so what I mean is from 34 we subtract 0 24 we subtract 24 from 24 we subtract 18 on 22 we subtract 18 from 9 we subtract negative 6 and from 1 we subtract 0 now we can do that easily because of that little trick I showed you earlier with the parent cool so let's fill that out so what you go from here to here all we have to do is remove the rightmost bit so we remove that no now let's remove the values so 24 minus 24 is it gonna be zero let's gonna be six they're gonna be four 18 minus zero is 18 9 minus negative 6 is 15 and this is gonna stay this as it is now why did we do that we did that for two reasons one we can give it a node we can easily access its parent by removing the right one set bit which I already explained and 2 if you notice something to get let's say from here to here right what's the sum gonna be right now we have 24 right we didn't we updated this is our final fun with tree but we have to make this one match this but let's just take it for here from here to here is gonna be 24 so what is this number it's gonna be a 6 right so when we're trying to go from here to here now keep in mind our friend with trees indexed by 1 so if we want the value from 1 to 6 oh sorry from 0 to 6 we have to tell our friend retreat 7 because everything is incremented by 1 so when we want this you go to 7 and we go up the tree 7 plus 6 plus 18 plus 0 plus 6 with 18 plus 0 is 24 and that's what this number is cool so now you we can update our array with the values in our tree so 0 1 is 1 this negative 6 is it gonna be 15 threes 15 4 is 18 5 is 4 6 is 6 7 is 0 cool so this is our final fan with treat and this is what our final Fenwick tree looks like and this is the integer array in the code what it's gonna be filled with the code for this is gonna go in here but hold on for that a second now that we have our Fenwick tree into your built out of integer array built out the two main functions from before remember is a sum and increment we can start implementing Posehn so first let's write the code to actually figure out how this figure out how to make this one so let me see did I cover that and did I cover okay I updated that one and the things at the top we have these like that and yeah let's get into the code of actually writing the Van Wyck array so we can initialize our so let's say int n is the length of the array and then our fenwick tree isn't gonna be new int n plus 1 right it's one larger what we're gonna do is Fenwick of one is gonna be a are of 0 and then for int I is equal to 1 I is less than n I plus f w I plus 1 is gonna be F and W I plus AR of I and that's the intermediate step remember we did the cumulative functions up with a cumulative sum up so that's the intermediate step now we're gonna do the part where we remove the value of the parent node from the given node so that is gonna look like this for int I is equal to n is greater than 0 I'm - - parent is it gonna be I minus I'm - - parent is it gonna be I minus I'm - - parent is it gonna be I minus I and the negative I so given a set if I 7 or is 8 all right the parent is gonna be the corresponding thing so for the parent of 7 if you recall is a 6 the parent of 8 is 0 so if the parent is greater than equal to 0 then the fenwick i is decremented by the Fenwick parent value and then that's it that's how we initialize a Fenwick tree array and oh of n time it's pretty simple so that was it that's the hard part now we can do the easy part so I just take a look at that cool so now let me remind you why we even started using Fenwick tree in the first place it's because of the two functions some and increments of the just a regular integer array now I'm gonna draw them I'm gonna write them out side by side so you can see how it's done with a integer array and how it's done with a friend wick tree array so regular array for some it's uh Oh end time right so it's just gonna be int with some 2x I know I wrote this before but this is just to help weaken X what we've learned result is zero and result is incremented by a are I and we return result so this is done it all anytime but with the Fenwick this is done in so it's gonna be the same method signature however we're not using the ARRA we're going to use it FW great Fenwick array now okay yeah so remember Fenwick is incremented by one so we have to always add one before we start now we're gonna say X is greater than zero this is because when we're adding we're gonna be when we're summing we're gonna be going up the tree so if I say seven there's gonna be seven and then it's parent six and then its parent four and then it's parent so this one goes here and then its parent goes here and then it's print goes here so if we want some from here to here right you'll be doing we already counted that this is 24 so 0 plus 6 plus it's parent 18 when is 24 in this period is 0 I guess maybe it might not go there because we're writing it like that but the point is the same thing well X is greater than 0 what we do is the result is incremented by Fenwick's X and then how to turn this into its parent X is assigned to X - X okay so that's how we go from Oban to vlog event now for increment we have void and I is gonna be the index and gamma is gonna be the value and this is done in all em but I'm gonna have a are oh I just incremented by a bell so that's using the AR array if we're using the Fenwick array would increment and I when we're incrementing we don't go from the bottom up literally we go from the top down of the tree and when we're summing we're finding the parent so when we're incrementing what we're gonna do is find the next now if you remember how we found the parent we just do the opposite of that to find the next node so it's gonna look like this is gonna be plus I was always gonna be plus with Fenwick tree because we indexed by one while I is less than or equal to n Fenwick of I is incremented by Val and then I is gonna become I plus I and negative I so when we found the parent we were doing I minus this but when we do the next we do I plus that and the runtime for this is log n this is all of one that's the comparison between the two cool so now we can use our increment function and our sum function from our fender tree to answer this now let me go into 3:07 so the constructor is just the regular constructor it you can just it'll be the same code as I wrote before but for this we're gonna have to use our helper method so for let's say for example what some range means so int I think J means they want the sum between I and say like J inclusive so if I is 1 and J is for they want us to return this Plus this how can we get that well we can use our sum function from our Fenwick tree and say J minus sum of I minus 1 it's gonna be I minus 1 because it's inclusive so if they want this what we're gonna do is from 0 to 4 and then 0 to 0 so that's how we're gonna get back 1 to 4 inclusive that was summarize now update is a little different than the increment of the Fenwick treat at least and what the problem is describing update it's called a point update where it's like you've been have an array a one three eight and they call update on it and I want to make this a twenty they're just gonna pass in two because this is a zero one two this is gonna be twenty and this is gonna come out to be so how do we use our increment function from our Fenwick tree is we were simple it's just this void update and I know is it gonna be first we get the difference between this and this is it gonna be sixteen right uh twelve sorry twelve so int is well - a R twelve sorry twelve so int is well - a R twelve sorry twelve so int is well - a R of I and then all we have to do is just put a R of I as the vowel but we have one final step we change the initial ARRA but we have to also update our Fenwick tree array we do that by simply calling increment I and a difference now the increment function already is going to take care of the index by one plus so that's already that's all we have to do so that's pretty much how Fenwick tree works and the Lee code 3:07 Fenwick tree works and the Lee code 3:07 Fenwick tree works and the Lee code 3:07 is just gonna use it so if you liked this video please subscribe and like it and let me know in the comments if you have any doubts or problems or something was I'd like to elaborate on it and follow up let me know yeah so thanks for watching
|
Range Sum Query - Mutable
|
range-sum-query-mutable
|
Given an integer array `nums`, handle multiple queries of the following types:
1. **Update** the value of an element in `nums`.
2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `void update(int index, int val)` **Updates** the value of `nums[index]` to be `val`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "update ", "sumRange "\]
\[\[\[1, 3, 5\]\], \[0, 2\], \[1, 2\], \[0, 2\]\]
**Output**
\[null, 9, null, 8\]
**Explanation**
NumArray numArray = new NumArray(\[1, 3, 5\]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = \[1, 2, 5\]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-100 <= nums[i] <= 100`
* `0 <= index < nums.length`
* `-100 <= val <= 100`
* `0 <= left <= right < nums.length`
* At most `3 * 104` calls will be made to `update` and `sumRange`.
| null |
Array,Design,Binary Indexed Tree,Segment Tree
|
Medium
|
303,308
|
19 |
I really don't understand why this problem is categorized under medium difficulty or rather I can tell you guys a sweet little trick that can make this problem super simple so let's find it out Hello friends welcome back to my Channel first I will explain the problem statement and we will look at some sample test cases going forward we will start off with the most obvious way to approach this problem and then look upon the fact why it may be under a medium difficulty after that we will find a very efficient Solution by a neat little trick and then as you usual we will also do a dry run off the code 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 actually it is pretty straightforward you are given a link list and a value of N and you have to remove the nth node but from the end of the list so what does that mean for example in our first test case I have my list like this correct and the value of n is 2 so you have to remove the second node from the end of the list that means this is the first node this is the second node so you have to remove this node when this node gets removed my new list will look something like this right so this is what you have to return similarly in a second test case I have a list that only has two elements and the value of n is one what does that mean look at the nth node from the very end so this is the last node and that is what you have to remove once you remove it your list looks something like this correct and this does not stop for example in my third test case I have a list that only has one element and the value of n is also one so if you start to look from the back this is the value one right that is the node you have to remove so as soon as you remove it what do you get you aren't let left with anything right so you just have to return a null you can be quite sure that the value of n is within limits that means that if my list only has two elements you will never get a value of n that is greater than two and all of these limits are mentioned in the problem statement itself so if you feel that you have understood the problem statement even better now feel free to stop the video over here and try it out on your own otherwise let us dive into the solution I have the sample test case with me right I have a list where head points at four and I have five elements in my list correct I also have a value of n usually in problems involving link lists you are asked that okay remove the fifth note from the beginning remove the seventh node from the beginning so in every question you are asked that okay remove from the beginning because in a link list you do not know where does it end you are just given a head pointer right so your link lists could be very long and then how do you determine hey what is the second note from the very end so the most obvious way to approach this problem will be that okay you make one traversal just to pass the entire list and find out its length so you will start from the head and keep on going until the very end until you get a null so that will give you a count right for this particular example you're going to find out that okay this list has five elements and you are being asked to remove the second note from the very end that means 5 - 2 and that gives you a that means 5 - 2 and that gives you a that means 5 - 2 and that gives you a three so technically what you will do is you will make three jumps and then you will land at the node that you have to remove so then you can easily remove this node and you can return your answer right so this method is correct and it gives you a correct answer every time but I guess this problem goes in the medium difficulty because they want you to solve this problem just doing one iteration of the entire link list that means you're not allowed that okay first you travel the link list and find its length and then again start from the beginning and then determine that okay I have to remove this node so this is the only thing I can imagine why this problem is categorized under medium difficulty so now you try to think that okay I can solve the problem using two iterations how can I just switch to one iteration let us take up a more generic example and then try to come up with a solution this time you have a bigger list and the value of n is three correct so if you just look at the list you know that you have to remove the third node from the very end right that means you have to get rid of the node that has the value 42 but you only have to do it in one iteration when you have to Traverse a list what do you usually do you take up a pointer that starts from the head and then go all the way up to null right this time what we're going to do is we are going to take two pointers and right now both of them start at head correct now there is very tiny number Theory involved try to think what will happen if I move one pointer n spaces ahead so I will take one of my pointer and move one 2 and three what did I just do I maintained a gap of n spaces between these two pointers right and try to think what will happen now if I try to move both these pointers in the forward Direction let us just do that so these pointers will keep on moving ahead like this correct and where do you stop as soon as the next of second pointer is null so you have identified that okay the next of this pointer is null so that is where you stop now just watch what happened look at this pointer now the next of this pointer is the node that you have to remove right so literally Things become so simple you just take two pointers move the first pointer n spaces ahead and now move both the pointers ahead until the next of second pointer is null after that the next of first pointer is the node that you have to remove and removing a node is super simple you know that link list works on pointers right so all you have to do is just say that the next of this particular node it should point at the next of the next node and that is all you have to do just return the head now what will happen if someone tries to Traverse the list from four they go to 8 then 15 then 16 then 23 then 7 and then five and then null so what did we just do we got rid of the node 42 and this was the third node from the very end of the link list right so this makes things so simple correct the only other doubt that you guys can have is that okay what about all the edge cases what happens if the link list is very small or it just has one element won't it get out of bounds or won't you need any such special handling so that is where I always take the help of a dummy note and I always advise that when you are encountering problems with link lists always take the help of a dummy note because a dummy note is something that you can easily discard at the very end when you're done with it so let me tell you what I mean by these two examples for example I have this particular test case right my list is very small and the value of n is one so the idea of a dummy node is just create a dummy node and it can have any value just assign the next of dummy node to your head what this does is when you're done with all of the iterations just return dummy. next that way you will always preserve your head value and as soon as you do dummy. next this Dy no longer exists you are just left with your head so once again let us try to follow the same approach you have two pointers right the value of n is one that means I will take one of my pointer and Advance it one space ahead correct now if you remember what did we do now you have to move both the pointers until the next of second pointer points at null so I move both of my pointers and now the next of the second pointer is pointing at null so that is where you stop and which node do you have to remove the node next to your first pointer is over here and you have to get rid of this node so it is really simple right just remove this pointer and then you can simply update it after you are done just return a dummy. next and then you will be returned with this list if you notice you start from the head and then you go to null so you only have one node remaining so you see how the dummy node made things so much simple correct let us look at the second test case now this only has one node and it is a very borderline case so once again we will do the same thing first of all create a dummy node and assign the next of dummy node to head after that to follow the algorithm what do you take two pointers and assign both the pointers at the very first note of your list correct now you have to advance the second pointer n spaces ahead so it got one space ahead after that you have to move both the pointers until the next of second pointer points at null it is already pointing at null so you don't have to do anything and which node do you remove the node next to your first node so you know that you have to remove this node and once again it is very simple just remove this reference and point the next of dummy node to the next of next node and then what do you return dummy. next so dummy. next is null and you just return a null so that is simply your answer so once again our dummy note was really helpful and it will help you to avoid all of those error all of those index outof bound exceptions and it will free off your mind with handling all of these special test cases now let us quickly do a dry run of the code and see how it works in action on the left side of your screen you have the actual code to implement this solution and on the right I have a sample list where I have a head value and I have the value of n that are passed in as an input parameter to the function remove NS from end now to begin the dry run what is the first thing that we do first of all we create a dummy node so I have this dummy node and I do dummy. next equals to head so this is going to help me out when I'm done with everything I will just return dummy. next and then I will have my remaining list for The Next Step you assign two pointers to the very beginning of your list right so that is what I do over here I take up two pointers and I assign it to the very first node correct that is what I do if you remember our algorithm you have to take this second pointer and then move two spaces ahead that is n spaces so when it moves two spaces this next pointer will be pointing at this particular location so right now my list looks something like this correct that is exactly what we do right move the second pointer and spaces ahead and after this what do you have to move both of these pointers until the second pointer next is null in our next while loop that is what we're doing over here right until the next of second pointer is null keep advancing both of these pointers so this pointer will go on and it will reach over here and this pointer will keep on continuing and it will reach over here right now which node do you have to remove the next node to your first pointer that is node number 16 and if you check once again this is the second node from the end how do you remove it is very simple just watch this line very closely I am saying first pointer. next that means the next of this pointer where should it point to it should point to First PTR do next so first PTR do next is this right now and its next is 23 correct so I am reassigning this variable where does it point now first PTR do nextt is first PTR do next I have now altered my list and to return the answer what do I return dummy. next so dummy is over here and the next of dummy is pointing at head so when this list gets returned how do you Traverse it you start with four then you get 8 then 15 then 23 and then a null so one of the nodes got removed the time complexity of this solution is order of n because you will be traversing the entire list at least once and the space complexity of the solution is order of one because you do not need any extra space to arrive at your solution I hope this trick simplifies the problem a lot for you as for my final thoughts I just want to say something out of experience you might have solved a lot of lead code problems right and it is not necessary that if a problem is categorized under medium difficulty then you have to think of a complex solution it can be very simple just try to look at the basics and at least try to form a solution rather than discarding all together so this might be the only tip that I may have for this particular problem because it is more about how quickly you are able to visualize it so while going throughout the video did you face any problems or have you seen any other such problems which look tricky at first but are really simple to solve tell me everything in the comment section below and it will be helpful for anyone else also who is watching the video as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also a huge shout out to all the members who support my channel this really keeps me going as an update I am soon launching my playlist on graph which has been requested a lot so until then stay tuned
|
Remove Nth Node From End of List
|
remove-nth-node-from-end-of-list
|
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`
**Follow up:** Could you do this in one pass?
|
Maintain two pointers and update one with a delay of n steps.
|
Linked List,Two Pointers
|
Medium
|
528,1618,2216
|
1,078 |
foreign welcome back to my channel and today we guys are going to solve a new lead code question that is occurrences after big Ram so guys let's understand this question uh given to the strings first and second considering considerate occurrences in some text of the form first second third went first second comes immediately after first and third comes immediately after second return an array of all words third for each occurrences of first second third so let's hope that most of you have understood this question but still some of you have not understood this question so let me explain it to you what is this question actually asking from us so uh we will be given three input first is a text second is first and third is second so we will be given three inputs all right and we have to give an output of the third occurrence so in the first in the text we have to search for pattern which is which includes first second third so we have to first of all search for first uh so we can see that here is the first a then if the second matches immediately 8 if the second but if after first what matches with this immediately after this mark my word that immediately after this then we can say that the word after second is the third word so this is the girl and we will just append this in our we will just push this a girl string a girl word in our output and then again we will just search for a if it matches with first and the immediate word after first occurs the second occurrence should be good if it's good then we can say that the next word should be the third word so that is the student we have to open it similarly in question number example number two you can see that we will rock you first is we second is Bill foreign equals to second word if it's equal to that then we can just append this push that value in our output and same goes for this rock see you can see that V is matching with first word second is matching with Will and the third word is definitely Rock so we can just append it and or push this inner result so guys just before starting to solve this question out do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so what we will be doing here is first of all I will just create light result is equals to an empty array and Next Step I'm gonna follow here is I will just create text is equals to text Dot split and I will just convert this text into buddy which will give me set of words like Alice is a good girl g-i-r-l girl uh she is a good student so I know it that it's time consuming here to write each and every word of here but to make understanding to make things clear we just I just have to write this so that you can understand and this question more better so now I will create a loop for let uh let I is equals to 0 is less than text dot length early and GTA minus 2 I plus and now I'm just gonna check first of all I will let me explain it to you I have taken minus 2 because uh we have we will be just not going to till the end of the array we'll just going till the length minus 2 so if its length is one two three four five six seven eight nine ten so we will not gonna append till now we will not I trade till 10 we will just gonna iterate till uh 10 minus 2 that is 8 so till here we will be just gonna we will just gonna what I trade and if we still here we will just check if it's this value uh let me explain it to you with this what I'm gonna do here for if text I is equals to First that is our this if it's equal to First and text this is first so the next immediate word would be I plus 1 of course so it will be second and if these is conditioned this condition is matching then I will just say that result Dot dot push what I'm gonna push here is I will just push text I Plus 2. okay and I'm just gonna say that uh return result and I will run this code and show it to you what I have got so see it has been running successfully what we did here is we just created a we just convert this text a string into an array and then we just checked for that word that are matching with first and second and if it's matching then the next immediate would be third and we just push that into our result array so after this we just have returned this result and we have got our answer this was all in the question guys I hope that many of you have understood this question so if you guys have not understood this question ask me in the comment section that what were you doubt thank you guys for watching this video and see you next time
|
Occurrences After Bigram
|
remove-outermost-parentheses
|
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`.
Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`.
**Example 1:**
**Input:** text = "alice is a good girl she is a good student", first = "a", second = "good"
**Output:** \["girl","student"\]
**Example 2:**
**Input:** text = "we will we will rock you", first = "we", second = "will"
**Output:** \["we","rock"\]
**Constraints:**
* `1 <= text.length <= 1000`
* `text` consists of lowercase English letters and spaces.
* All the words in `text` a separated by **a single space**.
* `1 <= first.length, second.length <= 10`
* `first` and `second` consist of lowercase English letters.
|
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
|
String,Stack
|
Easy
| null |
299 |
Bluetooth adjustment - Support Bluetooth adjustment - Support Bluetooth adjustment - Support and request of rebels So let's see the question, this is the question. Okay, so let's see the question. We have the question of the crossroads game. Okay, so in that house, this mistake, the soldier is in it for him, so what are you saying, the tension in it. I am not going to like the language from other films, so go and check it out. First of all, do not post it here, so those of us who are watching it on line, that is, if you have downloaded the video then if that video is If you are looking at it, then basically what is being said here is that you and you are playing a game with a friend, which is the booth numbers are there, okay so here it is Russia, okay what is Russia or that before taking the first rule I Tell you that you will be given a friend loan, for this you will have to act secret and there will be gas, for this you will have to act a secret at one time and gas will be lion, for that you will have to return a format from here Rostring, you will have to return it today from Off date is fine 11 air and bye here will be one your boost and air will be your cow is fine and to TRP you will have to write your ad and soon you will have to improve in Arya Samaj and what was said here that for me How do you take out this person who says this to you, friend, you will have to earn money so that it is known that if you see here, this is your smoking cigarette and you are a guest, if you take out A bulls from here, then he is like this. If you come out while completing its service, 714 is ever going to be, then this is your sequel and one and raw tauriyan and is a bit equal, after that here I will talk to you which character is for watching, then the error is one, that is why above. If you follow this, then even an egg white is like a seeker, forget all this, it is okay, so if you want to remove all that, then for this you see here, Apna is one for everyone, so for this we have only one matching here. If you have matching ears then by the way here he is going to be the one who gets irritated and yours is like this forum of bank and yours is like this if you have the reason for Rinku's return then by the way you are the one who is going to come and get rid of you otherwise how will you get rid of the idiot If you want to further improve your IB, then for that you will have to do whatever you want on the call, if you take the time to release your juice and release your anger, then you definitely do not have to take the Mercury that was holding you, right. If you are taking this means this and I have taken this here then all you have to do is not to take this i.e. 8:00 and if there is a not to take this i.e. 8:00 and if there is a not to take this i.e. 8:00 and if there is a matching here then you do not have to take this here, please assure me. Do n't take it and what should you do that whatever is coming inside it, means whatever is coming inside it, send it inside it, if but I leave the et and talk, you are the matching Kanhaiya Paswan from here, inside this here, God is here. There is life and whatever is there here too is different from here but here, don't go for the work position, just check whether you have to do English in it or not, in Banaras you had understood it twice. If I repeat this, then for this you do not have to remove two things here which we have Bose and Ka. Okay, then how is the alternative, the way to do them is that you will have to match the character, now if you don't do it like this then this I will search this entire casting with Vansh, it is not so, if you have this opposition to every position, then this juice is another juice, inside this you will have to massage while going to the required position or you will have to write one etc. and you are fine on that. abp were made and see, you will have to do it like this, if you become a Buddha and become a friend, it will be easier for you if you use it, then you check that the forest is yours, which means that I have added it here, should it be used in it or not? It is right to do, isn't it, and there is another thing in business Russia that if you cannot catch the tears of a person who has fever, if you agree with the High Court, then let's go towards the court, what will we do here, animal slaughter, the two things that we have, the people who exclude us from playing the cow? Sir Boostier, if you talk about these two things, then you are this cream, how will this player's pizza not be used in the office and if we will have to return you after exhausting us, then definitely give employment to him, then I think if you understand a little logic, then how should he say Singhania? Those services of district should follow quickly, so this and you have to extract the juice of agar, so here I am, you are the AB riders who use it, so look at this, friend, the code for this, wash them, roasting is given in it, which we have for cigarettes and If there are guests, then friends, there are more of us here I have to take one cigarette for them, firstly we removed it and the gas and electricity, we left it inside the exam, what did we do after that and took the test and secondly and that From that zero, we selected these and PAN, we followed the gas, searched inside it, then I compared again, there is nothing, okay, I just compared that if it is equal then comment and look inside it, cigarette, Noida, Jain and Even now inside the vinegar, after breaking the door, I copy an example, if you understand the whole idea, I got it done enough, then for this you are not getting the message of 1 liter in the first character, I hope I want and the second one. If you want matching then basically what should we do, this is the first secret one, here we will take this halwa and this one which we have, you can also do it in a different process, there is no problem, but I have made it work like this. Okay, so I brought CR here and here I also put this boiling second one, so its 0 is 151, all this is sorry to you or not capable, then you Redmi something to you, if after this operation your string has become some part. After death, what did I do, I took a map for the secret one and a match player is being given by our gas seller, so look at the initial map wine which is here, I have put that if this note is equal to this house, this is the character, then right now there is sperm. Don't do some work or the other, it's okay Rajasthan Sujas Plus do it otherwise we do n't have anything to do with this one, which is what I told you, if you have any boobs, you don't have to take a break, you don't have to account, I caught the watermelon, I don't have to take it now. I hope it is very easy to make, okay, so I am saying that I have to set it up a little, so that it will be understood that it will move forward here, when I gave the scooter, I referred it to someone, if I talk about it, then by the way, you It will appear something like this that I am coming and talking about the value of Havan for Rahman at home and there will be a forest for it. Come, I will space it out and purify it. Neither will it be a forest for 120 rupees. So if I get it done at your house then it will be worth Rs. For this, first of all, you see I on the side, inside the lineage is the jewelry maker, inside there is your maker and inside China, you will see some of the work of the maker, if I talk about it, you will see something similar here, okay If he asked, he is going to come in sweater for the world too, so I put one inside one, 113 inside one, 147 inside one, here I checked that those two don't want to Raghbir were there, so I went inside till the main host. After handing over and you will see something like this, I have used this trick here inside the files, it is okay, take it from here, put it in here, then see, if you definitely see, then you will understand this much. So here is the white china which we have the minimum God which means I am closing the one and which is IT to which is the one who wakes up in the morning and rough medium to means MP vancho hai Vijay ko aap hand which is closing the cigarette and Open the Gas MP3 2018 This trap I put on him, just the work I got him done here, but I made him do my work to get this account, I feel it is okay, so see, we started through this, we started it, we completed it. How much is the account made in it, what is your cow inside it which is working here, how much work is being done, whether this work has been done or not, if I tell you about the format then why is the format of the screen that we have and not the format of others? Do you know friend 16 and brother AB you will have to return like this or like this, neither will be one, your bull and wise will be but control, now you will have to add, so for this I have two strings to Australia here and the interval is interesting. If you want to convert into, then you will have to make two strings like this and see what is the account of yours, what was this boss of yours, that arrangement was a solid arrangement of yours, Africa, Russia and the account was yours, they say two chords here, I had made the account plus here, that is why the account which You are okay with aa bol and yours which you are my boss will post it through test taste or more students to what is this to-do list which account means this to-do list which account means this to-do list which account means pors i hogi become the one who is strong in law and order That's where editing is needed, Ashwagandha, okay, so I made it dependent on you, after that, it is S2, this WhatsApp app and destroy woman means Fateh, it is such a portion and 1 0f increases, so if I don't do it, then you especially need all this. Something is going to be left, see, you have CR and if I submit, it will definitely be the same disgusting, Bloody Mary, it was folded, it was very simple, there is so much top, otherwise it is very simple, then definitely our literature is clear, yours finished in 10th. Okay, so what I am going to bring after this is my favorite office which is Data Structure Algorithm, which if I tell you that brother, if you do not eat food, if you drink water, then it will look like a scientist, okay, so if If I talk about threat in data, it is your food. Till now you were managing your work by drinking your water. You have seen your C Plus. Okay, you were eating water. Okay, now you are going to eat food. We have the data structure and algorithm. So, it is okay. Even today we encourage you that the body of these 10 questions is also over, okay, subscribe to the channel, friend, you people subscribe means not subscribing till you stop the majority, friend, please subscribe and also like it. Because you have to work very hard, you should use it. Okay, so today I made gram flour and two videos a day in a total of 2 hours, as you see in Next9 Oil, I myself have just made time today, the director is not there, the team went crazy a day ago, but It's not like I do videos every day, now it takes a lot of time to shoot these two videos. Of course, you seem very happy. If you have to drink water at 12:00, your voice have to drink water at 12:00, your voice have to drink water at 12:00, your voice becomes very sore, okay, some people are smart as heroes and you Meet the latest album course courses
|
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 |
408 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 408 valid word abbreviation a string can be abbreviated by replacing any number of non-adjacent non-empty any number of non-adjacent non-empty any number of non-adjacent non-empty substrings with their lengths the lengths should not have leading zeros for example a string such as substitution could be abbreviated as but not limit to s10n because we have the s then 10 characters and then an n so that's what the 10 is it represents this part s u b 4 u 4 so that would be sub then we get these four we get the u then we get the four characters at the end we could just have 12 so we just the entire length of substitution gets abbreviated as 12. we could have su 3 so su 3 characters i one character the t u two characters ti and then on substitution we don't replace anything and here are some non um valid abbreviation s55 so um we can't have two adjacent substrings like the problem says so that's why this one doesn't work we can't have a leading zero on this one so this is why this one doesn't work this does not actually replace anything as you can see they're still the characters of substitution in here the zero just doesn't do anything uh and then given a word and an abbreviation return whether the string matches the given abbreviation so a substring is a continuous non-empty sequence of characters within non-empty sequence of characters within non-empty sequence of characters within a string so if we have the word internationalization and the abbreviation i12 iz4n is this valid so we have the i here and then we need to go 12 characters so 1 2 3 4 5 6 7 8 9 10 11 12. okay we have the 12 characters there and then we have i z okay that's fine and then we have four characters so one two three four that's gonna be four characters and then we have our n and uh we're at the end of both strings we've processed the entirety of our word and the entirety of the abbreviation therefore that's fine we can return true then we have the word apple so we have an a here that's fine two characters okay let's get rid of it and then we have an e which doesn't match with the l which is where we're currently at in the word uh therefore this is not a valid abbreviation so as you can see what we want to do is basically just have two pointers and what we want to do is we want to compare two things so we want to compare whether the current pointer in the you know word equals to its corresponding character in abbreviation so for example we have the eyes here and they match so we're good to go to move forward into the abbreviation so the abbreviation we need to parse out any numbers that come and remember we can't just parse them one at a time we have to parse entire numbers because right it's not one and then two it's actually 12 that go together so we'd have to parse out 12. once we've parsed this 12 we want to move our word pointer up whatever 12 spaces is so in this case it ends up at this i here and then we can check the next thing in our abbreviation which is this i z 4n so the eyes match that's good the z's match those are good then we can move four characters forward so we go a t i o n so now our pointer would be here and then the last thing we have to compare are these two ends and they match and at that point we have finished processing our abbreviation and we're at the end of our string so we can return true if we finish processing the abbreviation and there's still left things left in the string then that's not a valid abbreviation because the abbreviation doesn't cover all the strings so there's a few edge cases here that we want to cover uh and you know namely they kind of told us them up here right we can't have um oh sorry that is a valid abbreviation my bad um so we can't have like two substrings that are adjacent because remember it's not adjacent we can't have leading zeros we can't be replacing an empty substring uh so we have to watch out for those in our solution but it's really not that bad it's gonna be a two pointer solution and it's pretty straightforward this question is marked easy although i would say it's probably more of a medium because of how annoying it is i don't know who graded this on leak code but i think they're wrong anyway so let's go to the code editor and code this up because it's really not that bad back in the editor and it's time to write the code remember that we need two pointers to track our progress through the word and through the abbreviation so let's set those variables up so we're going to say word pointer equals to abbreviation pointer and these are both initially going to be at the index zero so let's initialize it like that now remember that we need to parse through our entire word and our entire abbreviation and we're gonna do that using a while loop so we're gonna say while word pointer is less than the length of our word oops less than the length of our word obviously we don't want to access things outside of our word or abbreviation so we need to make sure that we're actually within the bounds here so we're going to say and the abbreviation pointer is less than the length of the abbreviation so far pretty straightforward what we want to do is check whether or not our current um character in the actual abbreviation is a character or it's a digit because if it's a digit then we need to parse out the digits and move our word pointer up otherwise we want to compare whether or not the two are equal in the abbreviation and the word so we're going to say if abbreviation of abbreviation pointer so basically the character at abbreviation pointer in abbreviation uh if it's a digit then what we want to do is figure out how many steps forward we need to move our word pointer to deal with you know however many numbers are in our kind of number here so we're going to say steps equals to zero uh and one thing that we want to check now is actually if we have a leading zero remember this is not allowed so this is a invalid abbreviation so let's double check that so we're going to say if abbreviation of abbreviation pointer actually equals to a zero then that means that we have a leading pointer and we can simply return false because this is not a valid abbreviation string by the definition of our problem here now what we need to do is we need to parse out the number of steps which just involves parsing out this number here it can be you know multiple digits long it's not guaranteed to just be one number right you could have 12 you could have one thousand it doesn't matter uh we just need to parse it while we can so what we're going to do is we're going to say while abbreviation pointer is less than the length of abbreviation obviously we don't want an index error and while the abbreviation pointer whatever character is at that index is a digit that means that we still need to be processing is digit whoops what we want to do is we want to say steps equals 2 steps times 10 plus integer of whatever the abbreviation pointer is this is how we're going to parse it and what we're going to do is we're gonna say abbreviation pointer plus one oops plus equals to one we need to move our pointer forward and then we're gonna continue now once this breaks either we reach the end of our abbreviation or we um we hit a character that's no longer a digit so we want to stop parsing things so at this point what we want to do is we want to say the word pointer needs to get moved up by this number of steps because obviously you know we have the 12 so we need to move you know 12 characters forward so then we can compare the next things in the actual abbreviation so that is the case where um the current character is a digit so we're going to parse out all of the digits up until the next like actual character and then we're gonna move our word pointer up otherwise if we have characters we just need to check for equality so we're gonna say if word of word pointer so we need to make sure that the two are actually equal so if word pointer uh sorry if word of word pointer does not equal to the abbreviation of abbreviation pointer then what we want to do is simply return false here because obviously the two characters don't match therefore it's not a valid abbreviation otherwise if they do match all we want to do is just move our word point pointer up by one and we also want to move our abbreviation pointer up by one and that's all we need to do for the actual loop now remember at the end we needed to make sure that we had processed the entirety of our word in the entirety of our abbreviation if it's a valid abbreviation then the indexes of this word pointer and abbreviation pointer they're going to be equal to the length of our word and the length of our abbreviation respectively if they're not then that means that somewhere we didn't use up uh the entirety of the word or maybe i think yeah i think it means that we didn't use up the entirety of the word therefore the abbreviation was actually too short so we need to make sure that we actually reach the end of um both of these strings here and that would mean that we actually abbreviated everything correctly so we're going to say return uh whether or not word pointer equals to the length of word and whether the abbreviation uh pointer equals to the length of abbreviation because that you know these two statements here together are going to indicate whether or not we abbreviated everything so i'm just going to run this make sure i didn't make any syntax errors and embarrass myself looks like it is fine so let's submit this and it works so what is the time and space complexity of our algorithm here well we can see that we need to process uh oops sorry we need to process our word and our abbreviation so in the worst case the abbreviation is going to equal to the word right they're going to be the exact same word which means that it's going to take big o of end time to basically compare every character in both the abbreviation and the word to check whether or not the two are equal so that's the worst case where the word and the abbreviation are the same so the abbreviation isn't really abbreviation it's just literally the same word and that's totally fine we can have the same string and that's okay as you can see substitution is a valid abbreviation for substitution no substrings were replaced and that's totally fine so for the space complexity as you can see we don't actually define any sort of data structures here we just have two integer pointers and that's it there's no lists no sets no dictionaries nothing it's just those two pointers and that's going to be a big of one space allocation so that's going to be how you solve this problem as you can see it's pretty heavily downloaded i think it's a little bit interesting i don't think it's an easy question this is probably more of a medium just because it's a little bit hard to figure out all the edge cases um but regardless this is how you solve it's pretty straightforward especially once you've seen the answer i think once you've seen this video you should be able to you know conjure this up if you see it in an interview so that's the end of this video if you enjoyed it please leave a like and a comment it really helps with the youtube algorithm please subscribe to my channel if you want to see more videos like this i really want to grow my channel and your subscription helps me reach more people so please do that so more people can access this content otherwise i want to thank you so much for watching and have a great rest of your day
|
Valid Word Abbreviation
|
valid-word-abbreviation
|
A string can be **abbreviated** by replacing any number of **non-adjacent**, **non-empty** substrings with their lengths. The lengths **should not** have leading zeros.
For example, a string such as `"substitution "` could be abbreviated as (but not limited to):
* `"s10n "` ( `"s ubstitutio n "`)
* `"sub4u4 "` ( `"sub stit u tion "`)
* `"12 "` ( `"substitution "`)
* `"su3i1u2on "` ( `"su bst i t u ti on "`)
* `"substitution "` (no substrings replaced)
The following are **not valid** abbreviations:
* `"s55n "` ( `"s ubsti tutio n "`, the replaced substrings are adjacent)
* `"s010n "` (has leading zeros)
* `"s0ubstitution "` (replaces an empty substring)
Given a string `word` and an abbreviation `abbr`, return _whether the string **matches** the given abbreviation_.
A **substring** is a contiguous **non-empty** sequence of characters within a string.
**Example 1:**
**Input:** word = "internationalization ", abbr = "i12iz4n "
**Output:** true
**Explanation:** The word "internationalization " can be abbreviated as "i12iz4n " ( "i nternational iz atio n ").
**Example 2:**
**Input:** word = "apple ", abbr = "a2e "
**Output:** false
**Explanation:** The word "apple " cannot be abbreviated as "a2e ".
**Constraints:**
* `1 <= word.length <= 20`
* `word` consists of only lowercase English letters.
* `1 <= abbr.length <= 10`
* `abbr` consists of lowercase English letters and digits.
* All the integers in `abbr` will fit in a 32-bit integer.
| null |
Two Pointers,String
|
Easy
|
411,527,2184
|
297 |
hello welcome back to my channel and today we have leeco 297 serialized and deceiving binary tree and this question is often asked by a lot of companies like facebook amazon microsoft is a really popular question and it's also rated as hard question so let's take a look at this question now so now as you read this description and saying that um this is the treat right here one two three four five and we have to make it uh serialized by making this tree become a string and then we use this string and make it an exact same tree back like here is example the code will be initialized and call as such first if you make it like a string first and then later deserialize it and then still lies back and deceive lies to the same note so to compare the original answer same as the serialized anti-serialized node serialized anti-serialized node serialized anti-serialized node so that's the example here so let's take a look at the serialized one so how do we make a note into a string so there's a lot of way in here you see one two three they look it like top and then from different row you can see one two three and then no after this four five but we are reading this in different way so when we see one and we put it there and two i mean read the note first and left right let's take a look like um so if root is no then we return a string is called no so this is a recursion function so now we return we put the root value first plus and separate by a comma coma and plus we will have a serialized see we left side which is root dot lab plus and separate by comma plus serialize dot right side so now we put this after this we will see the example here become 1 which is the top note and that will be two node and i will draw it out like this left and we will frame the lab left node and right node right here so always form it like this format so for this triangle right here so we have top note and left and right so this is a really important concept by using this one we can it looks like something that we can read through from the lab to the right which is using a cube to solve this problem now we serialize into a string so we have a string as input as data now we make this string let's put it to the queue right now you will put us we keep that string go to new language and in this linked list we'll keep that data well as list we'll bring this data down by splitting it with comma sorry so we split that so we see it looks like exactly like this string we break it down with the comma and then put it into the cube so now we know the first thing is the root and later we look through the left side and right side now we have the queue set up and return that we need a helper function that put the q in there and this helper function oh um i erase this first sorry about that let's take a look at it uh we have a helper function that return a treat node for the serializing so we'll put in a list linked list that keep that string so we call this a queue so we now we need to capture the root node it which is q dot pool so if as equal close no which is nothing there so in this case we return no as a retreat node so this is the edge case as we consider so if s is not no there's something so that's something we need to build which is the root node right here we have the root node we'll build a tree node for return so we know the root node is the s right now s currently is 1 so we make that integer r dot s so now we build this back based on this input we captured one build the first node now we know and the left over q will look like this and we'll have the left portion will have uh the lab node so output.lab will equal to a recursion so output.lab will equal to a recursion so output.lab will equal to a recursion function helper put in the queue in there which is the remaining part and after we loop through the left cue which is this part and then we have the remaining part starting from here then we need to capture that to the right side do the same thing and help her function so we have this left side put to the left right side to the right as a recursion function done with this and we have the output no output tree right here built up now we eventually return the output as a tree that we built and then it should be the answer cool and this is the three function that we built to serialize and deserialize it and that should be it and there's still a lot of way you can do for this question but this is just one of them and hopefully that helped one of the idea for this question if you still have any question please comment below and i will see you in the next video thank you so much bye
|
Serialize and Deserialize Binary Tree
|
serialize-and-deserialize-binary-tree
|
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,2,3,null,null,4,5\]
**Output:** \[1,2,3,null,null,4,5\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
271,449,652,765
|
766 |
I'm having a really good hair day alright let's get started hello everyone this is programmer Mitch coming at you with a nether algorithms data structures problem today we're gonna be talking about leak code 766 so a relatively recent one called the top blitz matrix which I had not heard of before doing this problem matrix is top plates if every diagonal from top left to bottom right has the same element now given M by n matrix M rows and columns return true if and only if the matrix is top 'lets so let's pull in this matrix and 'lets so let's pull in this matrix and 'lets so let's pull in this matrix and kind of show so we have three rows and it's easier to kind of like look at it this way and the above grid the diagonals are nine so this is 9 is 1 then 5 a pulsating thanks for stopping in today 5 then 1 here 2 3 and then 4 is its own diagonal and this 1 2 that I don't want to a different element so we don't do this so that's though there's some examples you probably want to think oh well you know this is an M by n matrix so it's means it's a rectangular matrix could be squared it doesn't have to be it's not something called the skew matrix where we have different numbers of elements like different numbers of columns like this that generally makes problems a little bit trickier you don't often see that in data structure algorithms problems so the note the matrix will be a 2d array of integers the matrix will have a number of rows and columns in the range of 1 to 20 and cells in the matrix will be integers in the range of 0 tonight that these are really good questions to ask to kind of like clarify in an interview setting if you're interested yeah so let's hop right into an approach without touching the code first we want to think okay will it be good to walk over all the rows and all the columns and for any given element what are we thinking about what looks important hey Eli I think you're stopping in today so what would cause us to return false well something these are like these type of diagonals top left to bottom right we're not doing top right to bottom left which is actually how I originally read the problem and makes a little bit more difficult in that's not the problem that they're asking something that would cause this to be false is if this five was therefore right then this diagonal is not entirely at the same number and let's say this three what was not this one but so we have to think about this okay so that's the case but what about the top row well there's in under no situation when we would we disqualify the top row right because we're that's kind of like establishing the trend so this is three two three four five one once we get to this one's not the same to see then we return false we wouldn't return that at this point so basically yeah we just walked through it there's a nested for loop between rows and calls we have to say that the row is greater than zero and the call is greater than zero and then we just make a comparison if we're at it where the row is greater than zero and the call is greater than zero we can just say okay we're kind of looking at it that the same is the thing in the row minus one and the call minus 111 or JMK thanks for stopping in today and if it's not then we return false so anytime we that were not in the first row first call we want to say can we look over here above it and if it's not the case then we want turn false and then we return true so let's go ahead and code that out this should be a short episode but you know it doesn't mean it's a bad episode so we say foreign range of lengths of matrix and actually I'm gonna keep this up and I'll do that in a second for row in range of lengths of matrix and for call and range of lengths of may tricks of zero so in a rectangular 2d array matrix to delist you might say in Python this is the format for own range of like matrix for column range of length of matrix of zero then we're going to say if Rho is greater than zero and call is greater than zero and we want to say and the where we're currently looking matrix of row call is not equivalent to the matrix of the top left corner that type of corn with the top left cell matrix of row minus one and call minus one family to say return false and otherwise we want to return true so let's comment out this and go ahead and submit the solution and hopefully that is a quick pass the code is really thinking about it really thinking about that login oh good and we're finally accepted so we walk in through each row we walk through each called out down the line and we say if the road is greater than to hear the call clearer than zero and the matrix the real call does not equal made you to row minus one to call my one turn false otherwise return true this was a quote real quick one let's go ahead and do this one in JavaScript some people have been asking for a little JavaScript let's give it to him so is totally clicks matrix so we say for let I equals 0 I less than maybe I should have practiced this beforehand but we're doing it live I less than matrix that length and I plus and we wrap that in for let J equals 0 J is less than matrix of 0 length J plus and then we just say if Rho which case we call I here I is less than my default I iyslah is greater than zero and double ampersand in JavaScript as opposed just the word and Python 5 greater than zero and J is greater than zero and matrix of I J does not equal matrix of I minus 1 J minus 1 then we return false not capitalized in JavaScript and JavaScript junkies you have to wrap your conditionals in parentheses in JavaScript you don't have to do like this on a one line in JavaScript you can you do not need the curly braces you can just say return false and otherwise we return true also not capitalized in JavaScript cool so let's give that a spin that looks to be good let's see that makes make sure that works in JavaScript as well runtime error unexpected identifier in line 9 hmm they did not like this 5 grand 0 and Jacob is your and cheese I'm getting confused double ampersand and matrix of IJ does not equal and also for in JavaScript bang equals is type checking I as opposed to just this not equals this doesn't have a type so you might as well use that let's try that again once more into the breach good and we're accepted so we walk through each row through each column if we're greater than the first row and the first column 0 indexed if the where we're currently looking at is not less when you return false in return trip we did leak code 766 so click the top lids and matrix in both Python and JavaScript so leak code easy it's a little bit of a newer one so I thought of doing something a little bit newer it's time complexity we walk through every element so it's M by n it's space complexity is constant it's not linear we don't keep we don't make another matrix so this is a pretty nice solution for us there and this that is it for me programmer Mitch this was once again leak code 76 that oklets matrix hope to see you next week at 5:30 p.m. for another data structures at 5:30 p.m. for another data structures at 5:30 p.m. for another data structures and algorithms problem in Python but maybe we'll do little JavaScript as well if we have a little bit of free time see them
|
Toeplitz Matrix
|
flatten-a-multilevel-doubly-linked-list
|
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._
A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.
**Example 1:**
**Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\]
**Output:** true
**Explanation:**
In the above grid, the diagonals are:
"\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ".
In each diagonal all elements are the same, so the answer is True.
**Example 2:**
**Input:** matrix = \[\[1,2\],\[2,2\]\]
**Output:** false
**Explanation:**
The diagonal "\[1, 2\] " has different elements.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 20`
* `0 <= matrix[i][j] <= 99`
**Follow up:**
* What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
* What if the `matrix` is so large that you can only load up a partial row into the memory at once?
| null |
Linked List,Depth-First Search,Doubly-Linked List
|
Medium
|
114,1796
|
208 |
hey everybody this is larry this is october 7th but we're doing eighth day of the leeco dairy challenge hit the like button to subscribe and join me in disco let me know what you think about today's farm and all that other good stuff did i quit on i thought i did okay um yeah and i usually stop this live so it's a little bit slow just fast forward or watch on 2x you know the technology exists i believe in you okay today's problem is implement try or a prefix tree okay so they explain what a try is and then just implement it okay i mean i don't know what to say about this one for now i mean there's a lot of literature on tries of course even they even give you a link to the wikipedia page so i definitely recommend looking into it i have for certain gotten interview questions relating to try before and i had to implement it from scratch or at least rough idea of it from scratch so definitely practice it up and stuff like that and yeah uh so without further ado i will get started on the implementation because i don't know that there's anything else to say that uh that you can't really google on i try to kind of for these videos i try to bring some perspective that i think is unique sometimes and depending on what it is but this one it is just literally you know you could probably read the wikipedia page and that'll be mostly okay so okay let's get started um yeah so this one we have letters ref so what up what is our api we have insert we have search and starts with so that's basically it okay um yeah okay so there are different ways to do it and especially in competitive programming i definitely have seen people take shortcuts in implicit notes uh for this one i like to do it in especially if you're doing for interviews or but just like for self learning and good oop type things i would just implement my own node type thing i would also caveat that there is a contest at some point where there is there was a content as at some point where um where i did use the this abstraction with a node and it actually timed out where i had to replace it with some more hard-coded things but yeah but we can hard-coded things but yeah but we can hard-coded things but yeah but we can just do edges as you go to do and then uh solve that is n is equal to sn maybe uh yeah and basically what this note is that it is rather um this is the end of a word uh i am a little bit lazy today and it's really hard in my apartment for some reason um to kind of visualize it for you but you can imagine there's a tree there's a node but every node doesn't represent the end of a world it just means that it's a prefix of a word so we have a boolean flag to kind of um show that as the end there are other ways to represent this as well um i know that you know for example you're going to have an edge to a star character or that star a dollar sign character or something like that but effectively it does the same idea um and then now we can also just do insert for um what do we want to do yeah i mean we can do an implicit thing or not but so ch for character maybe so then we can i don't know it depends on how expressive and implicit you want but here we're going to do some edges dot ch is equal to um no maybe and then we can also what uh get maybe this assumes that it has edge so we can either um oops something like that right i mean you can make it as complicated as you want but that would be my i think these are the core functions for me um and maybe we can return the node just for a little bit easier but yeah so now we have a node at the root so solve that root as you're going to know and then here for insert we just start with current is equal to sub that root and then for c and word current is equal to um current.insert of c and add the way and current.insert of c and add the way and current.insert of c and add the way and maybe you could abstract that with uh you know we can you can abstract that a little bit further but i'm just gonna do it for now maybe you can you know do what feels right for you at home right um this isn't quite right in that we what we want is actually if sub that self dot has edge of ch or if this is not true otherwise yeah you can also write this in with a default dictionary kind of way but that's the way that i'll make it more explicit uh so current is gonna solve that for c and word um if kern has edge of c or if this is not the case then we return force and then we return it with uh current is n right because it has to match there has to be an end to this um but yeah and then lastly uh yeah so i would also say while i'm typing this um if you struggle with tries i think i give the same advice that or i would give the same advice that i would for linked list which is draw things out you know use a pen and paper pencil or paper if you want to erase uh draw it out draw where each pointer is draw for every iteration of loops what happens and that's what i would do yeah um and the difference is that this is returned true so maybe you can kind of play around with um this api to kind of maybe you know dry it up driving don't repeat yourself but that's you know that's up to you i think i mean i would actually recommend it by i do not uh prefix whoops but i'm a little bit lazy today i suppose uh because i gotta i'm not gonna lie this is dope uh the ti 10 on dota's got happening so uh go yg reboot but yeah that's what i have for now okay let's see so obviously i'm having a wrong answer uh on oh hmm what does oh insert is supposed to oh no that's not true dude oh search so search for apple is false huh that's weird so insert reinsert this one hmm let's see the problem is that i don't really have a yeezy framework for printing things out but maybe i'm off by one somewhere that happens a lot sometimes let's kind of take a quick look apple search did i misunderstood uh okay no search is the word right and start with a star with okay yeah no i think i'm right here uh with respect to the understanding but what is going on do i have a print statement somewhere did i do it no wait oh yeah we insert correctly so let's see hmm that's awkward so that means that we return force way earlier hmm okay i mix up something so we look at root if it doesn't have an edge to see then okay let's take a look then this was awkward okay but a and then p and then after the p it fails um well maybe at the p it fails do i not insert correctly let's see let's take a look at my api so if we doesn't have it we create a new node as edge not gonna lie usually i get this pretty quickly and correctly but you know sometimes it happens so for debugging um in real life debug i would actually have i would actually oh no this is just me being dumb i get it um because i don't set this for anything i don't yeah okay current is going to turn that is it to have get here i don't know how i forget this but yeah you just have to move the pointer and of course because i did copy and paste that means that whatever i'm writing was not good because i should not have copy and paste um but yeah uh let's go okay let's give it a submit now look i did it a year ago a year and a half ago and this one looks good too day streak 556 yay um yeah i mean this was pretty straightforward other than the mistake let's see what i did last time um but am i going over the complexity yeah for each character we you know let's look at every everything right so this one it's going to be linear in the size of the input word this one's going to be also linear as the size of the input work because we have a for loop and this one is the linear and the size of the prefix so you can't really do better than that because that's just your thing and all these other has edges over one and get is of one so yeah um what did i had last time i oh i guess the other time i did use the star thing oh sorry i see i say star but i mean dollar sign thing um that's interesting but uh but yeah that's all i have for this one um linear time for every part of the api let me know what you think uh hit the like button to subscribe and join me on discord and i will see you later stay good stay healthy to get mental health have a great rest of the week and maybe weekend is coming up so i'll see you later bye
|
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
|
1,824 |
hey everybody this is larry this is me over q3 of the weekly contest uh 236 or something like that uh minimum sideway jumps so for they're actually you know this is the shortest path problem as you may guess by just the minimum station uh and yeah um but this is a little bit tricky uh i to be honest this seems very uh straightforward of a shortest path however in python at least um i try well the breakfast search is not going to be correct um but you can definitely if you can use dicer and it's going to be correct but it time for me at least in pi find it time limited exceeded so i think um yeah it's uh um yeah and during the problem i also misread just a little bit in that i didn't realize that you can uh jump over rocks i need to slow down um because on the reading because i just missed that part completely and if i had noticed that my initial intuition was to do it with dynamic programming and in the end i did start with dynamic programming to get it to be fast enough uh faster than dystra but i had to but it i didn't think about it because i missed the part where you have to jump a rock um so yeah so the idea is that okay you know we have a dag in this uh situation if there's no cycles um if you change the graph a little bit um because basically what you want to do is just fog you want to move from left to right every step of the way um so you so yes there's a cycle you jump up and down and you know back and forth but as long as you kind of uh factor that in you can do dynamic programming and that's basically the idea here um the way that i did it um yeah so this is just setting up the dynamic programming and basically the what i'm saying here and i did it bottoms up uh because i was worried about time limit exceeded at this point but the idea is that okay so going from one column to another column what allows you to connect those two right well the two components one is that it costs one if they're on the same row then there's no cost okay so and then the other one is um uh you can look at each move as you know instead of going diagonal from say to you know let's say you're jumping from the zeroth row to the second row um instead of looking at it as a diagonal you could look at it as a intersection of moves and what i mean by that is that you can go from zero to from row zero to zero two and then move forward right and in that case you cannot make that move if there's a obstacle in the current column or the next column so that's basically what this is saying because you cannot jump to a row and then go to the right because you because that's basically the composite move that we're doing and then after you do that after you realize that then it becomes very straight for a dynamic programming translator uh the transition um because you just take the previous you know this is the previous row this is the cost of the previous world and then that's the cost of jumping to from that row to this uh this current xy row or x row and y column and we just check that the obstacle is not um on the current column or in the previous column for this row um and once we do that then that's all done and of course we set up in the beginning by setting uh the first row one to be zero and yeah and then we take the min and this is the dynamic programming resolution uh and you can kind of see very clearly what is this um what is the complexity here right well it's gonna be r squared times c um which you know because the number of rows is going to be constant so this is going to be linear time uh because c is constant right uh oh sorry rho is constant so r is constant so you have of c where c is the input and also um the time in terms of space is the same thing but it's all of r times c instead for space and yeah so you have o of r c space and o r squared c time uh where r of course is going to be a constant way um yeah so i got some wrong answers or time limit exceeded because i did things um using dystra uh and i had a greedy i tried to be too smart with a clever zero one bfs but i missed a case where that's not true and so i got a wrong answer from it but to be honest i just missed the point where you can jump over the rocks um because i thought that you have to jump because i thought that it cost two to jump um to jump that way so then it made things a little bit awkward um and then you can jump over rocks because i thought you have to i didn't know that you can jump over rocks i think for the first part uh that's why i spend a lot of time so i need to read a little bit clearly and stuff like that but yeah um cool uh let me know what you think let me know uh how you solve this and yeah you can watch me solve it live during the contest next um point so um surprise no one's finished already but no didn't know two things in each block so okay oh someone like that is a bad case okay i'm doing it just too fancy just do a breakfast search this okay it you mm-hmm this is not even right but why am i getting i got messed up to water that's why obstacle next this one oh okay why is this infinity oh man i'm totally misread oh wow i totally misread this okay what am i doing now hmm okay that's good this is hacky i don't know i like it but let's see is this right let's go wow really a lot of people got this one already this is two yeah why is this why am i doing two hmm dang it but here first but let's see hmm it's weird did i mess that up again obstacle minus one so this is no this is right why is this a cause of two hmm oh still long though but that is odd hmm that's fair and then two one is okay that's so two is one that's good but why is two three two oh because we're going because it could go from the bottom up or just straight forward i have an order of operation weirdness i should have just done dijkstra i was trying to be too clever um okay um okay pop leftovers okay so that's good 202. oh man come on friend oh no oh come on doing a contest this is like paid to win okay 202 let's go don't tell me it's too slow please this is too slow because this is i don't understand why this would be too slow though this is a python thing i think this would be too fast enough in other languages this is a this is just heap half a million yeah i might be writing just another language again how many people have uh wow smacks has finished it already has he um this is really annoying that i keep on having to change the different languages but do can i optimize this in a easy way actually i don't know you see everything oh geez what a mess today why is this wrong though i think i didn't really think about this enough i give two on that one the y what do you think two that's fine let's see well one we put zero two on four okay so two we put oh chris two three because you could get to the bottom in one step so that it tries to put the 03 in the next step maybe this is good enough this is faster 56 milliseconds this is so annoying that i'm trying to optimize like very minorly i think in other languages this is fast enough but maybe i'm wrong i mean this is faster so i don't even know if this would be fast enough i mean yeah even this thing is not that fast so i don't get it okay c plus then i think maybe there's a slick away this way annoying though hmm does that compile i don't even know anymore so many languages in my thing i forgot what language i think i'm like trying to do different languages for some reason so it is very confusing okay fine um i guess there's the dp solution but i was oh like i guess there was that dp solution that i was thinking of which i think i missed right for this problem so that was very dumb okay fine let's try that one okay you that's not good what whoops that's not good it's because i didn't do if um is that white this is wrong here how because you can't go diagonal that's why i was thinking that way hmm obscure hmm that's not good um but we want to only go let's see uh okay let's try again i've done that first but i missed red yeah thanks everybody for watching this video hope this helped uh and hit the like button to subscribe and join me on discord let me know what you think about this problem and how did you do during the contest or just afterwards uh of solving or whatever uh i'll see y'all next time yeah stay good stay healthy take care of yourself take care of others to good health and to good mental health i'll see you next problem see ya
|
Minimum Sideway Jumps
|
maximum-number-of-eaten-apples
|
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way.
You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point.
* For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2.
The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane.
* For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.
Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._
**Note:** There will be no obstacles on points `0` and `n`.
**Example 1:**
**Input:** obstacles = \[0,1,2,3,0\]
**Output:** 2
**Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).
Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).
**Example 2:**
**Input:** obstacles = \[0,1,1,3,3,0\]
**Output:** 0
**Explanation:** There are no obstacles on lane 2. No side jumps are required.
**Example 3:**
**Input:** obstacles = \[0,2,1,0,3,0\]
**Output:** 2
**Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps.
**Constraints:**
* `obstacles.length == n + 1`
* `1 <= n <= 5 * 105`
* `0 <= obstacles[i] <= 3`
* `obstacles[0] == obstacles[n] == 0`
|
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
|
Array,Greedy,Heap (Priority Queue)
|
Medium
| null |
1,897 |
hi everyone welcome back to the channel and today to solve Le code daily challenge problem number 1,897 redistribute characters to pick 1,897 redistribute characters to pick 1,897 redistribute characters to pick all strings equal so first we're going to look into the problem statement then we'll check out the approach which you're going to follow and towards end we'll see the code as well so talking about the question uh they have said that we will give we will get a array of strings wordss and the objective of this is to check if we can make all the strings equal or not if we can then we'll return true and if not we will return false for example in this case uh we have received ABC a BC right so if we move this a from uh word at index one to word at index 2 then we will be able to make all this string equal this that's why we are returning true over here right so this is the question uh let's check out the approach which we can use so talking about the approach it can be easily solved with simply just counting the number of uh occurrences of character or you can say frequency as well uh so for example if I calculate how many times I have a b and c in all the words then I'll be able to Simply solve it so how we do that is first I'll check out or I'll count all the frequency for all the letters we have for example over here we have done that a b c right 333 next comes uh the condition which we'll have to look at so this is the condition so uh we can only return true if for all occurrences for all number of occurrences if these numbers like 3 is divisible by n okay is perfectly divisible by n then only we can say that uh yes we can make all the strings equal and this n is nothing but number of words in the given array okay so this is the simple logic which we're going to use talking about the code uh this is a very simple code if you just uh you know check it out we have used a hashmap to get to you know count the number of uh frequency or to count the frequency of each alphabet so this is a dictionary for that number of words will keep a track of how many V we have in vs array and what we are doing over here is we just simply iterating the words one by one and within each word we are Ting the characters here we are using get method so to make sure that we don't get any you know errors while checking for any of the key for example if the CH is not present in counter we'll get a error right so what we are doing over here is we using get and we passing a default value of zero so if the character won't be present we will initialize with zero and we add one into it so this will be used to uh basically keep a track of frequency of all characters and at the end we're just incrementing one in the number of vs okay after that what we are doing over here is we just simply taking all the values from this counter and as discussed we just have to check if all these values is perfectly divisible by number of words or not if not for example over here if any of the Valu is not divisible by the number of uh vots in the array then we will return false and if all the values are divisible by this we will return true so let's check out the uh basic test cases so as you can see the test cases got clear let's submit it for further evaluation and the solution got accepted and I would say like we have performed uh fairly well so yeah this was the eest solution guys thanks done for watching of the video and stay tuned for the upcoming ones don't forget to uh like the video and subscribe to the channel thank you see you
|
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
|
434 |
this is lead code 434 the name of this coding challenge is number of segments in a string giving a string s we have to return the number of segments in the string a segment here is not exactly a word it's not like in plain language we would have a sequence of characters consisting of words and we exclude the punctuation so if there is a word like students comma we would read students as a word and we skip the comma but in this challenge a segment is defined to be a contiguous sequence of non-space contiguous sequence of non-space contiguous sequence of non-space characters meaning if non-space characters meaning if non-space characters meaning if non-space characters are chained together it doesn't matter if they are letters from the alphabets or consolation marks what matters is that the unknown space characters so if they are bunched together if they are put together in the sequence then the form is segments so in this example hello my name is John the five segments will be hello with the comma here so we have hello and comma six characters then we have a space right here meaning that the next segment is this one mine m y then we have a space here the next segment is the word name then we have a space here the next segment is the word is then we have a space and then the last segment is the word or the name John so there are five segments and therefore we need to Output five so in this case there is only one word hello and there are no spaces so the outputs would be one we only have one segment if you check the constraints the length of the string is anywhere between 0 and 300 and the string will contain letters from the alphabets lowercase and uppercase as well as digits and one of the following characters so they have here A bunch of special characters but actually they are not including one of the characters that you will encounter in the test cases the character you will encounter is the null character which has a decimal representation of zero but here they say the only space in s is an empty space like the space character which actually is uh 32 this one here it depends how you solve it you might not need to consider the null character but the way I'm solving it I'm going to consider it the first thing I'm going to do to speed up my processing if the size of the string is zero then I don't process anything I simply return 0 because if the string is completely empty it means that we don't have any segments in the string otherwise I create an input string I'm calling my input string stream extractor so that is a custom name you can name it anyhow you want and I pass it the string s which is the parameter here that is the string for which we need to count these segments then here I create a counter variable I'm calling it counts to count how many segments we have in the string s i initialize this to zero because I haven't started counting yet then I create a string variable called words and I need this one to extract the characters from my input stream so you've seen me use that technique before which is very common in C plus when you want to extract tokens from a string so I use the get line function here I pass the stream here the extractor so this is holding the characters in the input string stream then here I have a temporary variable when we extract a sequence of characters it's going to store it in set of this temporary variable and then this is the delimiter meaning extract characters until you hit a space so that is how it's going to extract and then check again if we can extract some more and it's going to keep extracting the tokens using that technique so here I'm going to increment my counts anytime I am extracting Tokens The Tokens again are the non-space Tokens again are the non-space Tokens again are the non-space characters in contiguous sequence that is what is happening here but I'm only doing that for non-space characters doing that for non-space characters doing that for non-space characters except for the null character so because word here is of string type if I want to access the character if you look at this as key table here these are characters if I want to check if I'm dealing with the null character I can access it using the index 0 meaning even if it's a string and it's only one character I can access that character like this so that I can compare it with the integer 0 which is the one for the null character so if it's not this one then I'm going to increment my counts otherwise I just skip it and then I return the counts so let's see how this works I'm running these sample test case and we pass the first lead Code test case now we're going to submit this and we pass everything how fast the algorithm works again it depends on lead code's back end sometimes it's zero milliseconds other times it's five milliseconds it doesn't really matter but we've passed everything so that's it for the test case called um number of segments in the string lead code 434. if we look at the details here how many test cases we had then we're only 28 so that is not the challenge that is extensively tested but I think that my logic is still good enough to meet what they were expecting from us which is why we passed all the test cases so if you like my C plus solution my tutorials and you want to practice more coding interview questions please subscribe to my channel and I'll catch you next time
|
Number of Segments in a String
|
number-of-segments-in-a-string
|
Given a string `s`, return _the number of segments in the string_.
A **segment** is defined to be a contiguous sequence of **non-space characters**.
**Example 1:**
**Input:** s = "Hello, my name is John "
**Output:** 5
**Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\]
**Example 2:**
**Input:** s = "Hello "
**Output:** 1
**Constraints:**
* `0 <= s.length <= 300`
* `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.: "`.
* The only space character in `s` is `' '`.
| null |
String
|
Easy
| null |
901 |
hello quarters today I'm solving liquid problem number 901 online stock span um so we are asked to design an algorithm that collects daily code prices and then return the span of stock price for current day so what's in Span or span is um the maximum number of consecutive days uh for which all the prices are less than the current stock price so for example we are given stock price for the 70s and span for uh day one which 100 which is equals to one because 100 is uh either less or equals 200 right so the span is equals to 1 and for in case of 80 the minimum value will always be one there's minimum value for span is always be one because it always uh count itself as well and then we look uh for all the prices before that uh day and since we only have one day which is 100 it is greater than 80 so the span is only equals to one here in case of 60 um we have a 1 and then 80 and 100 both are greater than 60 so the span is only one in case of 70 UH 60 is less than 70 right so the span for 70 is 2 um in case of 60 here this pan is only one because before 60 we have a 70 so there is no consecutive um price less than 60 before that day um in case of 75 we uh 60 is less than 75 70 and 60 these are all less so the span is full and in case of 85 this is the span which is equals to six here so now in this question uh we need to initialize the object of the class which is stock spanner and then we need to um write algorithms for the next function which actually returns this pan so we need to return the span for this function so how could we solve this problem um so let's look at this example here so when we Define the stocks Banner we are actually um we are then inserting all of these values next whenever we call next where we need to save these values in a consecutive manner so that we can access those values to identify this pan right so the best way to save these values are by using array so we are going to use array for our stocks Banner where we will save the prices in consecutive manner so we Are Gonna Save the value 100 here next again uh We Are Gonna Save the value 80 next we are going to save value 60 and so on so if I uh have until 60 if I have all the prices until 60 so what's the span of 60 when I uh perform this next function here um the elements in my area so far are 10 and 80 right and 60 is the element passed just now so of course the span of 60 when compared with itself is equals to one and then when compared with 80 since 80 is greater than 60 um it's 0 and then we break here because we do not move forward because it should be consecutive right so the span here is only equals to 1. now um when we reach here uh the values in our area will be something like this will have a 70 here we'll have 60 here uh 75 and then an 85 right so to calculate this pan for 85 now I what I need to do is I need to check for all the values before it so I compare 85 with 75 since it is less well this pan is always initialized to the value of one uh so I'll actually compare 85 with 85 also so span is equals to 1 then and then I compare 85 with 75 then span increases from 1 to 2 uh since 75 is less then I compare 85 with 60 which is also less than 85 so I increment this pan and compare it with 70 increment my span and then again compare it with 60 I increment my span again then I again compare this with 80 and increment my span here again so what I'm doing again is in comparing it with 100 and since 100 is great as I stopped there so my span here is equals to 1 2 3 4 5 and a six so it is six pan is equals to 6 here so if I were to find a span of 70 then I would be doing the same thing here right so the span of 70 would be compared with 75 um span of this element would be a comparison of 75 with itself which is equals to 1 then with 60 is less so the span is equals to 2 70 is also less the span is equals to 3 Now 60 is less than a span is equals to um for now and now 80 is greater right so span is equals to four only so we stop here the span is equals to four so here in this case the span is equals to 6 here the span is equals to four right what about 80 um it's less than 100 so the span here is equals to one or about 100 it has a span of one right uh let me use a different color here okay let me just clean things up um that's why it will be easier for us to ah okay great um so spam per 100 is equals to one span for 80 is equals to one span for 75 here is equals to one um and span for 85 is equals to 6 as we calculated from here right so um from here um we could see that to calculate the span of 85 what we could do is we could add um we could just check is 75 less than 85 yes it is then we add a 1 to this four um initially so we will just initialize span for 85 as value one and then since 75 is less than 4 less than 85 so we add this pan of a 75 to this value so we add 4 here and then we do not check for all of these values which directly come to this value and we check is 80 less than 85 yes it is so we add a value um add the span of 80 here and then again uh check for this one because we have the span for this um is 100 less than 85 no it isn't so we just break from the loop and then our value becomes equals to 6. so what are we actually doing here is we are only keeping the track of all the values um keeping all only the track of the values with this pan maximum span so far so um I'll create a new array here I won't have this array because this would take me off and time complexity if I were to find the span by going through each of the values one by one so um what I'm gonna do is I'm gonna create an array and then each time I call a next on a value uh what I do is I check uh for any uh spans any values and this pan of that value before uh inserting this value since there is no element here so I just insert my value 100 and this pan Which is equals to one year and then next what I'm gonna do is next time when and next is called with the value 80. then again I'm gonna check all the values prior to that with our which are less than 80 if those are less than 80 then I'm gonna add this pan of that value because that was what I did here did you see like since 75 was less than 85 I added a span of 75 to this pan of 85 since we do not have any value less than 80 here so I'm just gonna add 80 with its pan Which is equals to one next when I call another element which is 60 I'm also going to do the same thing so since 80 is greater than 60 I'm gonna add insert a to my array and then when I call the next element which is on 70 now I see here 60 is less than 70 right so what I do is I pop this element out of the array um and I add this pan of that element to my current price so my current price is 70 I add this span which is equals to one two the span of 70 which is always initialized as value one so minimum value is one so I add this one to my minimum value which is equals to 1 so this becomes equals to 2 here so my new element here is 70 comma 2. so similarly when I add my next element which is 60 here now again 60 is greater right less than 70 so I add 60 comma 1. and then again when I insert another element which is 75 well 75 is greater than 60 so I add 1 I add this pan of 60 to my minimum value of span and then again I add this seven values the span to my value for 75 because 70 is again less than 75 and 80 is greater so I don't add anything here I pop up these two elements and then I add 75 and 2 so when 85 is inserted I do the same thing since 75 is less okay it's not two it's actually four this is equals to 4 right so when 85 is inserted here uh 75 is less than 85 so I popped this off I add four to one and then again 80 is also less so I pop this off and then add a 1 to this and then since 100 is not less so I add the total value which is the span to this is equals to 6 and I return this value the last value so let's now dive into our code so we are gonna create um an array here and then I'll let and equals to one which is always initialized to one let P equals to an empty element here and then um I'm gonna push price to pee and then while um this plant is greater than zero and there's the length dot um length the last element that is this okay sorry this last element length minus one will give us the last element and the price of that last element which is index 0 is less than or equals to the current price then uh what are we going to do is we're going to pop and we are going to add n equals to um this dot pop the element and add this band which is at index one that nice pan plus we are going to add it to this pan and return this pen now also we need to here we need to push our value um Peter push pan and then they start push um key they start here that is the terror that proves this they are dot length push okay let's run our code here okay so here our DOT we need a DOT here as well great so um let's use all our example cool let's submit this so time
|
Online Stock Span
|
advantage-shuffle
|
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`.
| null |
Array,Greedy,Sorting
|
Medium
| null |
140 |
In this video we will discuss the problem of the word break, in this problem you have been given a string, a gift has been given and you have to make a sentence from it. After the word valid dictionary means that which is before the word off space. Will you consider, that word should be in your dictionary. We understand it like this in some examples. Cats and Lo and our dictionary can do this and we can add space between them. Two. This is what our dictionary can do. Similarly, if we see this example. Our link is Wine Apple Pen Apple There are some words in Apple with their help how can we break our string Fine is present in our dish So first of all I can break the point Apple Pen Apple in this way Our dictionary Fine and Apple These three words are present and we can do the same, like we have divided Apple into two big words, first, how did we split Apple, so in this way, you can make your string in all the valid combinations, all of them will be output to you. If we look at another example, in this we have given that send is our present but that is our story is also not present. Second if we look and this is not our present then we can replace this ring with any value sentence from life dictionary. If we can't convert it then what to return along with it. This problem is a follow up of the one which we discussed in the last video. In this problem, we have been given the life string and we are using it by selecting the train in this way. It is important that every word formed should be present in our dictionary. If it is useful then we have to maintain it. If it is not useful then we have to turn it into a fruit. What do we have to do in this problem ? How will we make our sentences? All of them will be valid and we will be returned. If ? How will we make our sentences? All of them will be valid and we will be returned. If ? How will we make our sentences? All of them will be valid and we will be returned. If you want to do this, then if you liked the last video, then first try to try this problem yourself, we just have to modify it a little in Recon and this problem will be solved and if you did not like that video, then we will try to solve it now. We will talk about uploading, how can we solve this problem, we have to return all the valid sentences, wherever we are returning all the sentences, what should be the first approach in our mind, the philosophy of All possible combinations will strike. We will write a function from cricket which will try all the possible words. All of all. Is it present or not? Zero seven zero to tu zero to three zero to N. In this way we will create our strings and each string will be We will check whether it is present in our dictionary or not. If it is present then what to do. Like if I have cash presentation, then enter 'Cats' presentation, then enter 'Cats' presentation, then enter 'Cats' and then add a space. What we had to do was whatever is our valid word, after that base. Had to add and then make the rest of the parts, then if we find a valid one, we will store it in the stream and by opening the space in it, our child Sting is our force and will take it from force to end and try to divide it into pieces. Check whether we can select it from Jeevan Dictionary or not, so basically we can store these parts in the prefix, what will become of these two, can we break them into pieces or not. Then what will we get? So we will combine it and as soon as our last one goes basically out of it, we will store it in our answer. We got one body and two cats but we had to store all of them. If we have to store all of them, then we will have to check each one, like will we have another combination, cat, we will store it, add space to it and then apply for the child part tomorrow, then we will get send, we will send it to And we will join it, we will also join space here, then what will we get, we will get disease and we will go out of mount, that is, what will become our another string, then in this way we will try all our possibilities in Ekadashi function and whenever we We will get a valid sentence and we will store it in our answer. What will it do? If the C dictionary is present then what should we do? Add a prefix and catch CAT and space. In this way, my string is stored. Plus now I have children. The parts which are my part from here, for this, for my third index, I need from third to last till here, I find out all of them, I have seen that I also got cats, there is space, now check from here till further. How can we speed up the ki bachcha hua stand? Apart from this, if we look at any other word, if it is our dictionary, then how will our two branches be formed as the base, one cat plus, these were the questions, one is not a cats plus, one is not present, like this, it is not present. If this egg is a present then what will we do with it, which was our string, what will it become with the cat's face that it is not a present, if it is a present then what will we make of it because we do it, we have got these, what is the meaning of the next index? That I got a valid split, what was my valid sphere but I don't want this space in the answer so whenever I go to outer point I have to install this string in my answer but before that what to do I have to remove this piece so What I will do is I will pop the last space from the string and then I will store the child string in my answer, this is mine, not one, after this we will do it here, we did not have any other branch apart from this. If there was no other branch nearby then we will come back here till now give us an answer then we will come to this branch in this branch i.e. from here we have to consider a so what will we do plus what we have to do is to recen for intake That brother, we have got only one valuation for Cats and Space. Let's look at the children's part whether we are going to divide that also or not and apart from this we will have some other brand A and D. This is the present A and Di. And this is also not present, so we will have only one branch from recession four, then we will come to recession, what will happen here again, we will not get B, we will not get return, how do we see another one in which our answer is, no string will come. Also removed one of our strings. Earlier it was cats and dogs. Now we have cats and dogs. We did not remove one. You see whether we get any volume split or not. Again our question is how do we do this? We will get CAT, we will get one CAT, that is, in the beginning, we will get one branch, CAT + recreation of get one branch, CAT + recreation of get one branch, CAT + recreation of three, and what will we get, CAT + three, and what will we get, CAT + three, and what will we get, CAT + recreation of four, this will be, what will we get from 3, we will get send, and what will we get from four, and we will go here. Then we will get OG in between the two, otherwise what will happen to us, we will never get a valid split, we will never come out with a valid word, so what will happen to us, we will never have any value in the answer, so like this If we can have any valid split, it will not happen, no, but is there a structure of distraction or not, how can we do this, so what is one method in which we are considering, we should apply a loop and compare it with each word. Compare each word in writing to see whether it is present or not. What is the second method? We can do it by using a data structure. Basically, we do a set or try. What do we do? Whatever are the words in our dictionary, we call them one of our Push it into the data structure, then whenever we have to check any string, we check whether that word is present in our data structure or not. If we have done it through the map, then whether it is present in the map or not. If it is stored in the set, then check it in the set. If it is stored in the try, it will be checked whether it is our present or not. Earlier we had to put a loop for each word or not. No, I find it very difficult to map it. So I will do it in the court. If you want, you can do set or try also. Once we see its code, in the code we have been given a string and we have been given a dictionary. First of all, what we had to do is we have to create our dictionary. If we had to push the word into a data structure, then we have done it here. We have put a loop and pushed all our words into the dictionary. Whenever we have to search a word, we will directly look inside it to see whether it is present in it or not. What we had to do was to zero out and store all the strings that would come in our answer. What type of answer did we want? We would store all the solutions that would come in a vector. So we created an answer variable of this type - vector of drink. answer variable of this type - vector of drink. answer variable of this type - vector of drink. Then we reduced our recension function to zero, our index became zero, our dictionary became our mapped answer, we will store our answer in this and in the beginning we will pass an empty string that till now we have not found any valid word in the previous. It is not found because we are starting from 0 right now, this will reduce our kid off, after attraction, all our strings will be taxed in the function, then we will return it. Now let us see this research function of ours. This question is also what is ours ? What happens is that first of all we have our base condition ? What happens is that first of all we have our base condition ? What happens is that first of all we have our base condition which is to terminate our recession and after that what we do is explore all the possibilities. What was our base condition whenever our index is but before that what do we do? If we had to remove the extra space that we had added in the last space, then first we will remove the space, then we will push it in our answer and return from here. If it is not our case that we are out of account now. If you don't go then what does it mean, now we are processing this train, so what we had to do was to try all the possibilities, so for that we took casting which is there now, in this we are going to take everything from the index till the last one. To try out all the possibilities, we will push one by one our current Krish ring into it. Basically, we will make a current ring. We will check whether it is present in my dictionary or not, if not. So again I went to the people, if you push another tractor and check whether you are present or not, when I get the present, then what I had to do was to store it, open the space in it and then next. Index Best Time Passed Mine Passed to me Answer I will do something That I will have to pass How will I get this string which I was making I will candidate these two ears plus this side if I want to do it then I will add space after this and pass So in this way, our entire recession structure means that overall our and factorial can run so many tanks look, then this will be the time waste of our problem and the factorial has given us the value of N, 20, so if we look like this, 25, see our 18 something comes. That means it will be very big and will hit time out, but we have a problem that our answer will be given a constant, it will be up to power five, it will be so big, we will be given input in such a way that how will be our worst ever, that is, every time and N - 1. N / 2 In this way we have to put loops, N - 1. N / 2 In this way we have to put loops, N - 1. N / 2 In this way we have to put loops, such input will not be given. Now this type of input can be in which case when it is from all your connectors like Ma Lo A. This type is a 20 letter string and is in your dictionary. Also, there are corresponding words like A is, then it is, like this, all these words are there in your dictionary too, every one is matching is for four, further here too, imaging is for one, amazing is for three. Matching is for four. In this type of situation, you will look for 1 and -1 and -2 and look for 1 and -1 and -2 and look for 1 and -1 and -2 and your time will be wasted and in factorial but the input will be given to us in such a way that even our first attempt will not be hit. This will be general. We have recursive approach. Discuss the problem. This will be done easily. No, what will be our space complexity? Firstly, it is our request, its space will be taken up. Apart from this, we have stored our dictionary in the unload, this will also be special. We will generally count the space of the answer. Do not make jokes please, we need to store the answer, if we do not count, then for this problem we will count extra, one is our express in our order and one is our which we are making every time, so if If we talk about this, our space will take up problem has been discussed in which our general structure is almost of size. Do you know whether you have learned how to store this type of problem in general or not? You can do a practice problem which is a practice problem. I would suggest you this is a lead code contract problem, the name of the problem is extra tractor image, it is like your previous two problems, only in this, what you have to return is that you are given some string which you are not able to break completely. What do you have to return in this, such extra crackers which you are not breaking up with? Now take the customer and your dictionary is the lead code delete code, then you look in it, the lead is your present and this is present in your list, story to you. If you are not including this character even in the story, then how many extras have you got? One of them is that if you are not including this character in the story, then in this way, all the characters who are not being included, breaking their string, their account. You have to return, if you are making a full break then you have to return zero. If you want to return their account then in this problem also the same structure will be followed. Just ask us to maintain some extra variables, then I will message that you yourself. Try to do it to check whether you have understood the concept or not. If you are not able to do it with them, then we have made a video of it on this channel, I will put the link of it in the description, you can refer to it from there. can thank you
|
Word Break II
|
word-break-ii
|
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\]
**Output:** \[ "cats and dog ", "cat sand dog "\]
**Example 2:**
**Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\]
**Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\]
**Explanation:** Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** \[\]
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 10`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
* Input is generated in a way that the length of the answer doesn't exceed 105.
| null |
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
|
Hard
|
139,472
|
523 |
welcome to lead code JavaScript a channel where we solve every single little question using JavaScript today we have 533 contiguous Savory sum this is a medium question however it has a shortly low acceptance rate of below 30 percent and the reason for this is that this question might be a bit more mathematical than algorithmic so there's a good reason most lead recorded don't get it right but it isn't super hard to implement so I'll explain so given an integer array nums and integer K written true with nums has a configured survey or size of at least two whose the elements on up to a multiple K or false otherwise and just give us the definition that X is a multiple of K if X is equal to n times K and the remainder of that zero there's a few examples for that and here we have this following array and we have k equal to six essentially we want any sub array that has like at least two that is a multiple of six another way you can realize here two and four is six so feels relatively easy and now your first instinct maybe just take a look at every single sub array and then calculate the remainder for each of array and if you find one with remainder zero then you got your answer and that could work that's absolutely fine however that's not super efficient because it will require you at least o of N squared to do such an operation and there's a better way to do that right now so the first thing you're going to need is a map um you can use a object or you can use the map object in JavaScript I like to use the map object recently and the first thing that we're gonna do I'll explain this later is we're gonna initialize or rather set our map with the value to zero to negative one so the key is going to be the remainder and the value is going to be the index and the reason that we initialize the first one uh to zero negative one is to prevent us from having errors where sub arrays of length one would be considered that's true when we have the condition that the size has to be at least two okay so we need to give a sum or we need to keep track of the sum so let's use the sum variable and finally we just need to look through the nums array I plus just a regular for Loop to the three and so we're going to keep a sum as we go through the array we're just going to keep some in num's eye but whenever we look through a new element and we need to check the following we need to check whether the reminder that we look that we're looking for what we access and what is the reminder that we're looking for you may ask so here's where the intuition represent the hash map or hashtag works and it goes something like this you had an array and a k um you will like to know what's the remainder of the array but we already discussed that they can look at every single sub array we take probably way too long but something that we can do is keep track of a sum and let's keep track of the sum here we start one then we start three then becomes six final becomes ten and we can take the remainder in every single step and it's gonna be something like this and that sorry so it's gonna be something like this and here's what we're interested in if the remainder repeats itself that has to mean that we added a value or we have a sum rather that's has a remainder of zero because the remainder is the same and it does have to be contiguous let's just imagine an example where there's a remember there are five I remember six between those two ones we still know that since this domain has been repeated we can know for sure that they this sum as it is has a remainder of zero now we need to look for every for this remainder every single time um but this relatively simple we simply let the remainder to be called the sum module okay and then oh right about that then we check whether the map has a reminder remainder there you go if it does not have the remainder then we add the remainder to the map and as you remember the key is going to be the index I sorry the key is going to be the remainder itself and the value is going to be index I and even else if I minus whatever map that gets remainder and in this case we are guaranteed to have the remainder because this part would only run if it doesn't remember so this one will run it does have the remainder so if I manage map.get remainder is so if I manage map.get remainder is so if I manage map.get remainder is greater than equal to 2 and what greater or equal to two because we need to make sure the length of the subarray is at least two so therefore greater or equal to two and we simply take the current index and the previous index such that we know that whatever that length has to be at least to and if that's the case we simply return true and if we went through the whole array and we didn't find anything that satisfies this condition we can return false and the timing space complexity of this is quite good the time complexity is actually uh open when Aaron is the length of numbers and as this complexity is also going to be oven because in the worst case we're gonna look through every single number in nums and then we're going to draw false and also in the worst case we're gonna store every single index and remainder that the nums and we're going to return it finally let's run this code see if it works and it works let's submit this and there you go it works really well as in the faster half of JavaScript and line submissions and thank you so much for watching don't forget to like And subscribe
|
Continuous Subarray Sum
|
continuous-subarray-sum
|
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1`
| null |
Array,Hash Table,Math,Prefix Sum
|
Medium
|
560,2119,2240
|
294 |
let's continue to solve lead code problem Flip Game 2 294 yeah so it's the same like before but this time the current state is going to be the plus and minus sign yeah and it can be any lens so the length can be 1 to 60 and the current state I should be plus or minus sign yeah and we also need to calculate the wrun time complexity yeah because this kind of algorithm actually it is used similar like backtracking so the runtime complexity we need to analyze a little bit and let me first explain this problem in the white board after that I'll go to the code Editor to finish the coding and for this problem I going to use bit mask to solve the problem because this number is just 60 and for each time we can do two operations it means for a continuous plus sign we can turn it to the negative sign yeah this is just for each of the operation but for Al and Bob there are still two people can play optimally so finally we're going to just return a true or false it always depended yeah on the question let's go back to the question yeah so the condition is return true if the starting player if the Alice is starting player Alice can guarantee a win yeah so the game ends one person can no longer make a move so for example for this one yeah if Alice take the two plus sign in the middle and Bob cannot take the operation so this means at Le will win yeah because Bob cannot do the operation so yeah it's like the game theory in the real games yeah now let me analyze how to solve the problem for me first of all I'm thinking about this problem as a DFS problem basically it is backtracking but this problem as we are giving a 60 and for each operation we can do yeah a continuous plus sign and them to negative sign so this means 2 to the power of 30 is enough for the calculation so I going to use bit mask for the DFS so basically yeah for rhm uh sign it can be plus uh it can be plus minus but it will be some sign like this yeah and for me I will make a record as my state so the state will be the bit mask the binary calculation of this number yeah so for this number if it is a minus sign I going to call it a bit one if it is a plus sign I call it as a um yeah if yeah I think U it going to be the same but uh for the calculation for the current initial State I going to use the negative sign as B one and the plus sign as zero so this is uh z this is one and zero so this is my current state and what I going to do I going to use the DFS go from the current state to tack for the next yeah so if we are having a string like this so for each time I going to check if there are two continuous plus sign but how can I check Yeah so basically I need to use the bit mask to check if this is a plus sign and if this is also uh plus sign yeah if they are both plus sign what I going to do so I can turn it to the minus sign and go to the next DFS yeah but if this is related if this plus sign and this plus sign has already related so I can just use a continue go to the next DFS and if uh Alice and Bob if this Bob lose so definitely Alice will win the game yeah I think it's difficult to explain but just let me go to the code Editor to explain the code yeah so I'm going to prepare a DFS inside of the DFS I going to prepare a state currently I will give a pass now I need to put the prepare the state value so what is my current state yeah because this current state cannot be zero because they are not always plus sign it can be negative sign so I need to prepare the C state so for I in r l of the current state I need to check if this current state I equal to uh minus sign this means I need to use the BET manipulation to get my result so my result should plus equal to this I should be shifted uh one should be shifted to the left side and how many PR it should be shifted to I pris so this means yeah if the first character is a minus sign it going to be zero plus one because this I is zero so it going to be a one yeah so finally I going to calculate what is the result basically I going to count how many minus sign and this is for me this is the low bait and to the right side this is the highest bait so this is why I going to calculate my current state yeah now I can put the state inside and get the result I just need to put the result inside and return this DFS so this is for propeper reasons basically if there are always positive sign or plus sign yeah my current state is just zero if there is a negative sign like this yeah so basically I need to prepare so this is a two and this is a four 2 + 4 is a six so basically I need four 2 + 4 is a six so basically I need four 2 + 4 is a six so basically I need to put six inside yeah so this is my current state now I need to write the DFS so for the DFS basically I need to check this function if I can find two continuous plus sign yeah so for I in range L of the current State minus one yeah because I just needed to go to the second last because basically for each operation I needed to check two continuous sign yes so this is why it is a lens of current State minus one now I need to check a continue station if it is inside basically I need to continue yeah so if this state let me yeah if the state shed to the uh left side to I plac and one yeah so if this state shifted to I bait yeah it means basically in the ice bait if there is a one if this bit is a one it means it is a plus sign Yeah so basically it means it is uh a negative sign because I going to use one to represent the negative sign so if I find a negative sign but I need to check two continuous negative sign yeah so I need to check the next bait so it let me copy this one yeah so basically this is the state sifted to here is I but this time it going to be I Plus one yeah because I needed to check two bait if this two continues B will be always be a minus sign so I just need to continue this is also one yeah so if it is add one and yeah basically I just check the two continuous sign if they are both minus sign so I let it continue so I will jump to this step and go to the next step so for the next step if Alis and Bob if this Bob lose the game so if yeah so this is basically the template for the same uh Game Theory so yeah so my current state is Alice I want to check if Alice can win the game so if Bob loses the game it means Alice must win the game yeah so I going to return a true finally if Alis cannot win the game so the Bob must win the game so Bob will return a foral yeah so let's put the Bob state so it means yeah if it is a minus sign it is it will continue if it is not it means for this uh character it must be a plus sign and continuous one it going to be a plus sign it means I find two continuous plus sign yeah so what I needed to do I need to Tex the um Bob state so add and Bob I will check the Bob's State I need to update the Bob State basically it is or uh with this I uh with this one yeah because I need to put it inside I need to put this bait inside my state so I need to use R so this one should be shed to the left to ice positions yeah so this is just one oper reason and I now I need to check the next one so the next one is let me copy yeah so the next one going to be the one Saed two going to be the same I + one Saed two going to be the same I + one Saed two going to be the same I + one yeah I also noticed I made a mistake here this end yeah so this is basically this should be yeah should be R uh yeah this is all this is means I need to put two if I find yeah if I find two minus sign yeah this means if I find two minus sign yeah or I find one plus sign and one minus sign I still let it continue because for 1 plus one minus we cannot do the operation or if I find a minus and plus I will we still let it continue so this is for the continue actually there are three combinations so this is why I need all here yeah basically this is the entire code now let me run it to check if it works yeah as you can see it works now let me submit it to check if it can pass all the testing cases yeah as you can see the pastor all the testing cases now as this is a bit mask and this DFS will just return a true or false for the state we can add a cast to speed up a little bit let me just add a cast and submit again to check if it works yeah as you can see it is much faster than before this is a why because we used the bit mask and we also used the cast so the time complexity now becomes two to the power of 30 yeah we are giving a 60 but 60 divid by two it is 2 to the^ of 30 but also by two it is 2 to the^ of 30 but also by two it is 2 to the^ of 30 but also inside it always dependent on the result and this state yeah this is like the triming and this state is also like the triming so it may be less than 2 to the power of 30 yeah if I yeah I think basically that's all for the question see you next
|
Flip Game II
|
flip-game-ii
|
You are playing a Flip Game with your friend.
You are given a string `currentState` that contains only `'+'` and `'-'`. You and your friend take turns to flip **two consecutive** `"++ "` into `"-- "`. The game ends when a person can no longer make a move, and therefore the other person will be the winner.
Return `true` _if the starting player can **guarantee a win**_, and `false` otherwise.
**Example 1:**
**Input:** currentState = "++++ "
**Output:** true
**Explanation:** The starting player can guarantee a win by flipping the middle "++ " to become "+--+ ".
**Example 2:**
**Input:** currentState = "+ "
**Output:** false
**Constraints:**
* `1 <= currentState.length <= 60`
* `currentState[i]` is either `'+'` or `'-'`.
**Follow up:** Derive your algorithm's runtime complexity.
| null |
Math,Dynamic Programming,Backtracking,Memoization,Game Theory
|
Medium
|
292,293,375,464
|
1,340 |
hello and welcome back to the cracking Thing YouTube channel today we're solving lead code problem 1340 Jump game five I have not made one of these videos in a long time so hopefully I'm not too rusty anyway let's read the question prompt given an array of integers and an integer D in one step you can jump from index I to index I plus X or a or I plus X is less than the length of the array and 0 less than x is less than or equal to D so basically we have up to D jumps that we can make or we can go in the opposite direction up to D jumps in addition you can only jump from index I to index J if array of I is greater than array of J an array of I is greater than an array of K for all indices K between I and J formally blah so essentially that when you're jumping between indices your current position needs to be greater than all of the indices that you're jumping over so essentially you can only jump down uh you can choose any index of the array and start jumping and then return the maximum number of indices that you can visit and then you may not also jump outside of the array at any time okay so this question is really horrible to read uh because of like the less than or equal to stuff but um the gist of what we want to do is basically you just want to find out the maximum number of hops we can make uh within the constraints so let's look at an example M for this one D is actually two so if we start here at 12 what are all the places we can jump well we are constrained at a maximum jump length of two so we can jump to the 10 or we can jump to the six and remember that we have to jump to a place where our starting position is greater than the end position and it's also greater than all of the elements um in between it right if we had D equals like 10 or something we couldn't jump to six because we can't get over the 14 so we have to basically our starting position needs to be higher than all of the places we're either going to jump to or we're jumping over so from 12 obviously we can go to 10 or we can go to 6. so if we go to 6 we can't really do anything because we can't go back to 12 uh because we you know index I has to be greater than index J so we can only jump um you know in this direction uh so essentially what we want to do is right we can't go out of that right because we can't go up after that um so we have to jump to the 10. so that's one hop we can make so from the 10 we can now jump to the six which would be a total trip length of two or we can go to the nine which would again give us a trip length of two or we could go to the seven which would give us a trip length of two um obviously from the nine we have a choice of going to the 7 or the 13 we can't because it's higher than us so we can't make that jump uh so we go down to the seven which gives us you know a path from 12 to 10 to 9 to 7. so that's just like a basic example um and the way that we're going to solve this is if you look at the solutions you're actually going to see a lot of dynamic programming ones but you guys know that we don't do that on this channel and we're actually just going to solve it using a graph so I'm going to wipe away some of this text and basically just go over the basic intuition of the graph and then we'll code it up this question is a hard question so I'm not going to go too into depth and like walking you through line by line if you're solving a hard level question you should probably be able to follow my logic if not go try some of the mediums and then come back to this one anyway let's now wipe away all of this text here and then just go over the basic intuition here so we went over the basic example and I told you that to solve this question we're going to use a graph and the way that we're going to do that is obviously we're looking for the longest path that we can take um but to find the longest path obviously that's going to be the you know we're going to have to try all the possible paths that we can take but we can actually be smart about this so the first thing that we want to do is actually build a graph right and what the graph is going to tell us is that from every position so every index we're going to have a mapping to all the valid uh positions that we can jump to so we for each index we have jump uh positions and what we're going to do is we're going to build that graph for basically all of the indexes um in our array here so now that we have the graph we can now basically figure out our path between places right and whatever is in um for a given index here uh we'll know basically how many places we can jump to that are valid so we'll basically build our graph with the constraints of the problem which is remember we can only jump up to D um you know steps at a time and then we also have the constraints on where we can jump to once we build the graph with those constraints what we're then going to do is we're basically just going to kick off a DFS from every single point here and then just try to find a global uh maximum right so DFS now obviously we may visit a certain starting position um you know while dfsing from another one so for that reason we're gonna use some memoization here and we're just gonna have a you know memorization dictionary to basically store intermediate results that we've seen so we're kind of doing some dynamic programming but we're not doing that weird one with like the arrays like 2D arrays and try and do all that wild like it's just a simple dictionary to look up your values I think everyone can kind of wrap their head around that one so that's really the intuition here we just want to build a graph for each index all of the valid places that we can go and then for each index we're just going to run a DFS to see what the global longest path we can get is and like I said we'll use some memoization along the way to save us from recomputing things because as you can see from 12 when we get to 10 you know we'll have stored the result for 10 and then when eventually when we process 10 on its own we can just reuse that result there's no reason for us to then run the DFS from 10 again so that's essentially what we want to do pretty straightforward build the graph DFS over it return whatever that maximum result is and there you go this question is more of a medium but for some reason their marketing is a hard so let's now go to the code editor type this up and you'll see that it's really not that bad especially for a hard question so I will see you guys in the code editor momentarily we are in the code editor let's code this up now we need to Define some variables here so the first one oops the first one is going to be our graph and this is going to be collections dot default dict uh we want to use a set here because we want all the unique points we can jump to we don't want to accidentally double count something remember that we're using DFS plus memoization so let's define that memosization dict and just for some utility let's define this variable n which is going to be the length of our array now what we need to do is basically build all of the points from a given index that we can jump to so basically we can go to the left or to the right a maximum of D times assuming that we actually stay within the bounds of our problem here and remember that if we're within D bounds we need our starting point value to be greater than the um the value of the index that we're jumping to cool so what we want to do is we want to say 4i in range of n we want to go both to the right and to the left so let's do to the right first so we're going to say 4J in range from I plus 1 to n and we're going to say if the array of J is less than the array of I so basically where we're jumping to is lower than where we started from and the absolute value between the distance of those two indexes is less than or equal to D which is our allowed jump with then we can say that there is a path from I whoops to J so we're going to add that to our graph and if either of these two conditions are not met we want to break because we don't want to go further to the right because then that means that we will not be following our bounds here so either we're past our D or remember that this is either invalid or that array of I is greater than array of K so this will actually check for us both those conditions are actually three of those conditions to make sure that we're okay now what we want to do is we want to do the opposite uh now we want to go to the left right this was going to the right until the end of the array now we want to go to the left until the start of the array so we're going to say 4J in range I minus 1 down to the minus 1 index and we're going to decrement by -1 index and we're going to decrement by -1 index and we're going to decrement by -1 and again we're going to say if array oops array of J and sorry is less than array of I and the absolute value between I and J is less than or equal to D then we can have basically a edge in our graph from I to J otherwise we are breaking our conditions here and we need to break out of our loops so this will run and build a sar graph now what we need to do is we need to for each index run the DFS and see what the maximum result we can get is so we're going to say res equals zero because we haven't found any path yet and we're going to say 4i so we're going to try all of the indexes in range n what we're going to do is we're going to say the result is going to be the maximum whatever the current result is and we're going to call our DFS function to find that path length starting from index I and then obviously n we're just going to be using that as the length of the array here and you'll see what we're going to do in a second and what we want to do then is just return our result and we're done so that is the main function but obviously we still need to implement the DFS function so let's do that now so we're going to say def DFS and we're going to take in whatever the current index is and the length of our array because we need to know when to stop obviously if we've gone outside of the bounds of our array then we can't actually go any further right so we're going to check that boundary so we're going to say current index equals n um we're basically going to return zero because obviously we can't find a path if we're outside of our array all right now what we want to do is we want to say if the current index is in self.memo so if we've already seen this self.memo so if we've already seen this self.memo so if we've already seen this index we can reuse the result so we can return self dot memo of whatever the Cur index is and then what we're going to do now is we're going to say what so for the next top in the graph so basically we want to go through all the points in our graph we're going to say for the next hop in self.graph self.graph self.graph of whatever the current index is so remember the graph contains for our current index all the possible places we can go uh we want to now try all those hops so we're going to say that oops sorry I forgot to create a variable here uh and then we need a variable to basically keep track of our path length so obviously path length is going to be one in the case that we can't actually go anywhere we just stay where we are and that's considered a path of one so the path that we've seen jumping between all the indexes here is going to be the maximum of whatever the current path is and then one plus jumping to the next hop right so DFS the next hop and we're gonna have to pass in N again so essentially what we do is we basically just try to find the longest path from our current um you know index and we just keep running the DFS recursively and we're going to store the results so we need to Now update our memo addict so we're going to say self.memo for whatever the going to say self.memo for whatever the going to say self.memo for whatever the current index is going to equal path and then path and all we need to do is simply return the path so that way our DFS can terminate and then we can bubble it up and eventually continue forward so let me just run this make sure I didn't make any silly syntax mistakes looks fine let me submit this and uh okay I think the screen yeah okay accept it perfect so we see that the code is accepted uh now what we want to do is essentially just talk about the time and space complexity here so for the time complexity we basically have to build this graph so for each of the N indices we can go you know D hops right we can go whatever D is to the right or to the left so that means that to build the graph it's going to be Big O of n times you know 2D and the reason it's 2D is because we can go to the left and to the right but we don't actually care about the two because it's a constant and we don't care about that asymptotically so D is just the width that we can go in either direction so we need to multiply n times D to actually build the graph and then from here it's going to be the same process in the worst case our entire um I guess the Hops would be starting from the highest point on the right and everything to the left of you know the end of the array is actually smaller so we can actually visit every single one so in this case we again need to just actually we would visit all the points so it should be Big O event um yeah so just ignore that part so the overall time complexity is n times D or n obviously is the length of the array and D is this D that was given to us earlier and for the space complexity it's going to be the same thing we basically just need to store the graph so that's going to be a big O of n times D so like I said not the most complex question um you know it's just one where you build a graph and then Traverse over it is a little bit tricky to see how to set it up but once you've seen this is relatively straightforward this Loop you know a first grader could write this and this DFS is a pretty standard DFS with memoization there's nothing really crazy here um so why this question is a hard question I don't know maybe just setting it up like a graph problem and then traversing is the hard part but who cares uh it's an easy win and yeah if you get this in an interview should be smooth sailing alrighty so that is how you solve Jump game five hopefully you enjoyed the video this was my first one in a while so hopefully I'm not too rusty um we will hopefully see uh if people like this one uh anyway I'm rambling so I'm just gonna leave it here thank you so much for watching leave a like and a comment to help me out with the YouTube algorithm subscribe for more content like this and I will catch you in the next one bye
|
Jump Game V
|
the-dining-philosophers
|
Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).
You can choose any index of the array and start jumping. Return _the maximum number of indices_ you can visit.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[6,4,14,6,8,13,9,7,10,6,12\], d = 2
**Output:** 4
**Explanation:** You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
**Example 2:**
**Input:** arr = \[3,3,3,3,3\], d = 3
**Output:** 1
**Explanation:** You can start at any index. You always cannot jump to any index.
**Example 3:**
**Input:** arr = \[7,6,5,4,3,2,1\], d = 1
**Output:** 7
**Explanation:** Start at index 0. You can visit all the indicies.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 105`
* `1 <= d <= arr.length`
| null |
Concurrency
|
Medium
| null |
88 |
hello everyone welcome back and today we are looking at question 88 which is merge sorted array so we are given two integer arrays nums one unknowns two both of which are sorted in an non-decreasing fashion sorted in an non-decreasing fashion sorted in an non-decreasing fashion which means both of which are sorted in an increasing fashion as we can see numbers one we have one two three and mums two we have two five six the numbers are getting larger as we go to the right and they are telling us that we are given two integers m and n these represent the number of elements in each array more specifically m will represent the number of elements in mums1 as we can see m equals three which mean nums one will contain three elements and now n will be the number of elements in numbers two as we can see n equals three and nums two contains three elements the question wants us to merge nums one and nums do and we want to store the result in nums one fortunately they have given a space to store the numbers of numbers due inside of nums one or in other words if numbers one contains m elements unknown still contains n elements the length of nums one is m plus n which means that num1 can hold its values and the values from num2 okay so the output is one since it's the smallest element then we can see we have a two then we can see we have another two then we have three and final we have five and six okay so now let's go to the blackboard and explain how can we do this okay so here we are and as you can see i have nums one and numbers two already made and nums one contains three elements which are one two three unknowns two contains also three elements which are two five and six and i also have put the indices of each element on top of the um array okay so now as we can see they have given a space extra space in nums one to hold the values in lines two so we need to use this and we need to be clever about this so now if we want to merge these two arrays together and the output should be stored in nums one we don't want to start from this side and move this way we don't want to override values they have given us empty space without anything here so we need we can use that right i want to use three pointers and i will tell you why i want one pointer to start here at the empty space of course these are zeros indicating that we have empty space we can just delete them so we have empty space here so we have one pointer start at index five and we have one pointer that will be at index two which means it will be at the last element in nums one and we will have another pointer that will be at index 2 for norms 2 which means at the last element of num2 so the idea is that we want to compare the values that the blue and red pointer are pointing to and the larger value will be stored at the index that this pink pointer is pointing at okay since the array is sorted in an increasing order the largest element would be at index five so let's see how this goes okay before i continue i have created three variables which are insert p which is this pink arrow and int pointer one which corresponds to numbers one and into pointer two which corresponds to numbers two um i don't like the name of insert b it's quite long so i will just say int p now we said that this pink pointer will be at the end of nums one which will point an empty space we said that nums one will hold the values of itself and numbs two and the length of nums one is n plus m so this pink pointer will be at index five or in other words n plus m minus one m is three n is three plus three is six minus one is five so we have this pointer at index five initially and pointer one which is the blue pointer will be at index two or in other words m minus one we can see that m equals three so three minus one is two and now the pointer two will be at index two which is n minus one and so we here we have n minus one so initially we will have three pointers at these positions okay so now let's start we will compare three with six which is greater six is greater so we will put six here's six and now we will decrement this pink pointer to here and now we will decrement the red pointer to index one since we already finished with six and we store it no need to keep i'm looking at six we just decrement the pointer to look at form now we keep the blue pointer at three because we still need to compare it with other values now which is a greater three or five is greater so we will store five here and now it's time to decrement the pink and the red pointer so the red pointer will be here and the pink pointer will go here now again which is greater three or two now three is pointer in this case so three will be stored here and now we need to decrement the blue and the pink so the blue will go from index two to index one and now the pink will go from index three to index two okay again compare the blue with the red which is greater two or two it doesn't matter i will pick this slower one so we can um delete this three replace it with a two and now it's time to decrement both pointers the red pointer will point to nothing negative one basically and now the pink pointer will be um at index one so remove it from here and it will be here as we can see we successfully merged these two arrays in nums one and we have one two three five and six so this is the idea now before i go and code the solution out i want you to see something important that i have to draw attention to so let's replace um mums2 with another thing and i will show you okay so i have recreated numbs1 unknowns 2. num1 will contain 1011.12 and numbers two will contain one 1011.12 and numbers two will contain one 1011.12 and numbers two will contain one two three we can see that all of the elements and ones one are greater than the elements of nums two okay so let's do what just we did a minute ago but with these values now we will compare 12 with three 12 is greater so we will put 12 here and now it's time to decrement the blue pointer to here and now the pink pointer from here to here now 11 with three 11 is greater put 11 here the blue pointer will go here and the pink pointer in this position now let's compare 10 with 3 10 is also greater so 10 will be stored here and now we need to decrement the blue and go to nowhere or at index negative one and now the pink will be decremented to here as we can see the blue pointer has reached the end and the word pointer did not move from its place and the two arrays are not merged successfully so we need to make sure that pointer two which is the pointer associated with nums2 reaches the end this pointer must reach the end when this pointer reaches the end we know for sure that the two arrays are merged successfully okay so now let's go to its code and call the solution out okay so we said we need three pointers we said that the ping pointer is called pointer p and this pointer will be reset at the end of norms1 and since num1 will contain the elements of nums1 and the elements of num2 the length of it is m plus n but since arrays are 0 in there np will point to m plus n minus one okay now we said we need another pointer that will point to the last element of norms one and this will be at m minus one and we need another pointer which called p2 which will point to the last element of num z2 array and it will be at n minus one okay once we have these three pointers we will have a while loop so while pointer one is greater than or equal to zero basically we reached the end of nums one and pointer two is greater than or equal to zero and now we need to ask one question if nums one of pointer one is greater than nums two of pointer two basically the number that we are pointing to in numbers 1 is greater so we need to store that number in the empty space so num 1 p equals num 1 of one okay and after we do that we need to decrement pointer one and we need to decrement vp which is pointing to the empty space now else we will do the exact opposite so else let me copy this and paste okay else the element in nums 2 is greater so we need to store that into the index that this pointer is pointing to and again the increment pointer to undecrement p now let's go one more time to the on drawing we need to make sure that pointer two has reached the end okay so when this pointer reaches the end we know for sure that we finished merging everything so let's take care of that okay so while um pointer two is greater than or equal to zero we need to keep looping and basically nums one of p will equals two um num two of p two and now it's time to decrement both so p two minus and p minus once pointer two reaches zero we know for sure that everything has merged successfully so let's run the code and let's submit as we can see faster than 100 okay so let's look at the time and space complexity let's start with the space complexity we did not use any extra space we did everything in place and we store the result in numbers one so the space complexity is constant big o of one now let's look at the times complexity we said that nums one contains m element numbers two contains n element and we want to merge these two together so the times complexity is big o of m plus n where m is the elements in lines one and n is the number of elements in mums two thank you guys for watching i hope you enjoyed the video best of luck to you and see you in the next one
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
934 |
hi everyone let's start solving today's lead code daily challenge question which is 934 shortest page so as part of this question we are given an encross and binary Matrix where one represent length and 0 represent water and there are exactly two islands in a grid and we need to return the smallest number of zeros we need to flip to connect two islands so let's try to understand this particular question with an example so this is our example and as per this example an island is a four directional connected group of ones and not connected to any another ones so as well as part of this question there are exactly two islands is present in a grid so as we can see in this example so here we can see this is our one Island and this hole is our one Island where 0 represent water so this is water it is surrounded by water and this hole is also Island so we need to connect this particular Islands this island and this island we need to cut we need to make a bridge between these two Islands so what we can do we can by flipping 0 into 1 by making water to land we can connect these two islands so how we can Intuit to the approach to solve this particular question how we can get the intuition so first thing to make a bridge between two islands first we need to create a differentiator between two different islands so what I am trying to say by this how we can create a differentiator so by flipping or by creating a visited array or either changing the first island values to some another value so we got a differentiator between two islands and so we can say there it will be a first Island and it will be our second island so we need to create a differentiator first after that we can create a bridge between these two islands so how we can find out where is the first island present and where is the second Island located if we are able to find this particular differentiator then this particular question will be very easy to us so how I am saying with the help of any as part of this question what is given to us in the question an island is a four directionally connected group so once and not connected to any another ones so with uh with what kind of traversal we can find out the whole connected Island in one go so we are getting an intuition by choosing the DFS traversal we are able to reach the all the ones of the first Island and after that we need to stop our DFS traversal so there will be a differentiator between the first island and the second Island so let me show you an animation how I am trying to see how DFS traversal will work as part of this question so as soon we find first find out the first I and jth row and column where we found our first one Square so we'll start our DFS reversal and after that we will convert all the ones to twos so in this way by performing DFS traversal of the first island once will be converted to two and after that our final grade will be something looking like that so here we can see we are easily able to find out the differentiator between the first island and the second Island using the DFS traversal now we need to find out the smallest distance between the first island and the second Island so which traversal we can use so as We Know by using BFS traversal what is BFS is breadth first search by using breadth first search reversal we can easily able to find out the smallest distance between first island and the second Island now why we are choosing BFS reversal because BFS traversal has an property the BFS reversal in one go reach all of its neighbors and after that the second neighbor visits all of its neighbors so in the smallest distance we are easily able to find out with uh with using BFS traversal only so the whole question is divided into two parts first we are first we will be differentiating both the islands using DFS traversal and after we Traverse the first island we will stop our DFS traversal and the all the inj row and columns we will push into a queue to perform BFS traversal on that squares so let me give you a code work through of that the same algorithm which we discussed about so I created a global variable queue okay I am using the queue data structure in this and I created the directions array where these four other directions which is nothing this is X Plus 1 comma y this is x minus 1 comma y this is X comma y plus 1 and this is X comma y minus 1. so these are the four directions which we can Traverse to visit all the islands connectivity okay after that I created a Boolean value where I am storing is my first Island founded or not so I am written two Loops for I and J as well as it is mentioned in the question it is a n cross n grid so both I and J will be running till n and if grid of I comma J is equal to 1 what it means I found it I my first island so I will do the traversal DFS traversal to convert all the one of the first island to two so here is the DFS method what I am doing grid of X comma Y which I got in the parameter where the value of grid of X comma Y is equal to 1. and I am changing it to 2 now for those first island X and Y parameters I need to do BFS traversal so for that BFS reversal I am pushing this X and Y parameters into my Cube and after that I need to perform whole DFS traversal on all the neighbors or all the connected squares of that first Island so this whole thing is doing that part only so I am running a loop over the directions array where I founded X1 and y1 my new Direction left right up and down and if the grid of X the new X1 and y1 parameter is equal to 1 I am performing again DFS traversal on it so DFS traversal is a recursive function so after it completed I changed my Boolean value of first island found is equal to true because I need to stop the DFS traversal here so my second island value did not get changed so here I am using this Boolean function to break the loop and after that I am applying BFS on those all points of the first island so from because from first island I need to find the smallest distance between first island and the second Island so I initialize distance variable to 0 and I started BFS traversal so this hole is BFS traversal so I've first I will run over a loop to the whole parameters which is present in the queue because after one iteration as you can see in the above layer or the above example so by do performing the BFS reversal on this particular zeros I need to increase the Distance by one so let's Suppose there is one more layer of zero is present here so in this case the BFS reversal to this particular 0 and the distance will increment by again one more so that's why we need a for Loop which will run over Q dot size and after got the parameters from the queue I need to visit the whole all four directions so I got my new directions which is time 0 temp is nothing but the array which I got from q and directions I am using the same which I initialize globally above this one and if my grid of X1 or y1 is equal to 1 What does it means I found the second Island and I can return the distance else if grid of x 1 y 1 is equal to 0 what does it means it is water and I need to maintain so I does not do the BFS traversal on the same square again and again I am changing into minus 1 else what you can do you can create a visited array but visited array will store visited arrival store like this particular square of water is visited or not so I will not perform BFS on it again and again so that's why for easiness I am converting into -1 because I return two conditions into -1 because I return two conditions into -1 because I return two conditions only one is for one which is for the second island and one is for zero if it is a zero I am changing it to minus 1 and I am adding those parameters into my queue again to reach to do the BFS traversal again on its non-visited neighbors non-visited neighbors non-visited neighbors after one whole traversal or whole iteration I am incrementing my distance because one layer is completed I need to iterate over another layer and at a final when I am able to reach the second Island I am returning the distance so at here at the end after if I found at the last iteration I am returning in the last distance else at this point only I am returning the distance so that's it from this question if this particular intuition helped you to solve this particular question like my video And subscribe to my channel thank you
|
Shortest Bridge
|
bitwise-ors-of-subarrays
|
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water.
An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`.
You may change `0`'s to `1`'s to connect the two islands to form **one island**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`.
| null |
Array,Dynamic Programming,Bit Manipulation
|
Medium
| null |
863 |
Hello everyone welcome to me channel we are going to do video number 29 question is quite popular today number 1863 medium but it is going to be very easy because in a very simple way we will make it very basic from what we know we will make this To the question and this video is on approach one, a separate video will be coming but we will make it from the second one as well. Okay, the name of the question is these binary trees of notes distance. Okay, you must know that the court is on Facebook and Instagram in the name of Sorry with Mike. Our page is available and it is available on Twitter by the name of Key with Mike. Let's solve it today from Flipkart. Approach one. Okay, the question must have given vanity. D value of target note. One must have given you target note also. Okay and teacher, what happened? On the target note, all the people who are at a distance of 2, that will be my answer, like look here, if this is my target , it is ok and who is this, he is at a distance of one haj, ca n't take him If yes, then what is the answer? 147 is clear till now, so if you look in this approach, I see only one problem that like mother, this is our target mode, right here, there was a note here. There was a note, here is a mode and here is my mother's let's go, this is my target mode, that means mother, first take who are the people at the distance, then this will be the first level, then these three will be in front, then this is on the second level. No, then you must have got a hint that if I reach this note, will it be given in the input? What do I have to do with this note? I have to find the notes up to K = 2 levels. Okay, so the first level. find the notes up to K = 2 levels. Okay, so the first level. find the notes up to K = 2 levels. Okay, so the first level. Look here, one, two, three, these people are the people of the first level, are n't they? Okay, so in the first level, these three will be finished, after that when the second level will start, one, two, three, they will fall, if they catch, then their Meaning, do you know now if you do a simple BFS from this 5 which is my target mode, you do a simple BF here and in BFS we travel level by level, you will know that in BF we are level one, if we do this then Then after that, I traveled to the second level and made notes of all the levels one by one, so it's okay when I reach the first level, what will I do, whatever level I have in my notes, why will I give them my answer? Okay, so first there will be 5, so what will I do? With this five, I can only catch it and hold it. I cannot catch the note behind the top because there is no path to life above. What happens in binary tree actually? It is a directed graph. Every time from any note you can go to its left child or its right child. Okay, you will be able to go below five, not 7 and 4, so you can find people but this is the one. This will be missed right because for this you have to go back, you have to go from here to here, okay, so the only way I can see is that why not, he became a director, what does it mean now that he has taken the left and right side. Now we cannot go up from any note, now we can only go down from it, on the left and right side, so what will I do, who is the parent of each one, if there are three, then I made one in front, so actually we know what I am doing, this is a directed graph. I have made it undirected, so what will be the benefit from it? Please note that with five you can go to his left side, with five you can also go to his right side, that is already life, the question is, go left, go right. But now when I have added this painter also, now from five you can go to its parents also, what is the parent is this one, you can also go to the wife's parents, so if I show how many parents this is? Isn't it, if I become a dun, this information came to me that who is the wife's parent, a painter. Okay, after that, there is no problem, isn't it? After that, I can travel completely. I went from five to three, then From three I can easily go down because it is already available with me, isn't it clear till now, you must have understood it, okay so let's move ahead now, you get the information, it will keep on increasing and fill that too. It is very easy, see how I am standing here on the route, okay now look, pay attention, as soon as I look at the lift of the route, I will do a simple inverter reversal. Okay, first of all what I wanted to write was that if the route is equal to my tap then return. Okay, what did you do? What did you do? You used to go left on the inorder route and after that what did you do? You used to go right on the inverter route. Okay, okay, this is what used to happen. Okay, if this note is equal, you tap on it, then I will go there. Okay, but darling. What will I do before knowing the left side of the inverter route? This is my map, which is the parent map. In it, I will write that I am the parent of the route where I am going to the left, which is the route. Similarly, here I will do the same route. Before knowing the right of the note, I will check equal tu null and will store here that where I am going to the right of the parents of the root, if I am going to the right of the root, then I am its parent. If the root is fine then that information is here. I will show like 3 is the parent of 5, okay then I came to 5, then from 5 I can go to six and you can also go, okay then when you go from 5, I will write that you are yours before my life. The parent is 5, it is clear till now, so we will get this information easily, I will simply travel again by level, how will that help because we have got the parent painter that from three I can go to five and from five I can also go to three. I can go similarly from 5 to 6 to 5, I can do this, I can also do this, okay, so we have got this, we have also got the information about the parent painter, let me draw, which is how we used to do the parent portal, that is, BFS. How will we do why and how will it help? I had told you a little while ago that I will travel level by picturing it, meaning I will put five in the first note. I did this, I popped it and five is okay, now why what was the size of one, right, when earlier there was five, the size of was one, that is, there is only one element in the current level, this is the first level, this is right, so in this only If I have to process an entire level at a time, then remember the same one from BFS, we will put the code in it, note off k dot in, I had told you yesterday in a question that whenever there is a question in BFS question, level is related. For some help, this method is to be written, remember what I told you that first we will find out what is the size of the current level and we will process all the elements of the level. It was told in some video that when to write which approach of BF, right? So even today we will write the same one, so now see what is the size of K, that is, if N = 1, then N = 1, then N = 1, then our Wiley loop will run only once. Okay, so what will I do with it in one go, I will do it in a big one, brother five. Is it the left hand of 5, is it the left child of 5, so given this pulse for the next level, is the right side of 65, is the right side of s5, is it the parent of 5, is 3 and all three are also non-vegetative, is 3 and all three are also non-vegetative, is 3 and all three are also non-vegetative, right now All three are non-visited. Now right now All three are non-visited. Now right now All three are non-visited. Now why am I talking about non-visited? why am I talking about non-visited? why am I talking about non-visited? You will come to know after some time. Okay, now at this level, this is the first level. My right is how many elements are there at this level. There are three elements, N = 3, so three times I You will have to process three times, do you N = 3, so three times I You will have to process three times, do you need people of second level, otherwise these are people of first distance 623 This six is at a distance from five, you three are okay, This six is at a distance from five, you three are okay, This six is at a distance from five, you three are okay, then the first six sinned Who is the left side of sex, there is no six There is no one on the right side, it is the parent of six, but if there is five, then what if we post five back, then we have to push the pipe a little bit, that is why I am saying that if we mark the visit, then there will be a vector named visited, this will take the data. Structure five has already been visited, so I marked it, so the parent of six is there on the left side and the right parent of six is there on the left side and the right parent of six is there on the left side and the right side, but it is the parent of six but it is wasted, that is why I will not put it, now the next helmet has come and popped it. I am on your left side, I have given it to him, he is going to come to the next level, is n't he is going to come to the next level number 2, that guy is also on your right side, I have given him a lesson, he is the guy of level number 2, okay Yes, your parent is also 5 but it is widgetized so I will not put it. Okay, now in the current level one, there is another mother and child. Three is the left hand side of three, so I will not write it. It is the right side of 3. There is no one here. Okay, one, I have added it for the next level. Okay, now this level number one of mine is over. Okay, now look, I have come to G level, the value of level is equal to K, the value of K is you, that is. I have gone to the second level A, which means all the elements present in this second level will be my answer, so what will I do, I will remove them from BF and all the elements seen in K will be my answer, so why should I remove them from all K? I will return my answer. Ok BFS is very simple but before that we had to find out the parent who was a painter and that actually came to my mind because it is obvious that I am limited because I am not going back. But if it was a normal graph, an undirected graph, then I could have traversed it because the number of five is three, the number of five is six, the number of five, but why was I not able to do it because from five to three there is a lot of life. There was no way, so what I did was to add one point from five to three, it could have gone from 3 to 1, but I also added three from one and so on, okay, so this became my approach and this approach In this video, we solve it, so the one who has just heard the story, we just have to convert it from the story to the court, now let's quickly start its code, so let's finish the code quickly. First of all, I told that we will tell the parent. To store it, we will take a map, in which we will store it, we will write in it who is the parent of each note, okay, and to store the parents, I had said that I will simply write in this order, okay, in this I will write three note stresses. I will send the route and from there I will write the same old in order code, if the route is null then I will return it and if the left side of the route is available then what I said is that I keep the parent name instead of MP here, it will look more clear and you are the parent of the four. Handsome is fine, till now it must be clearly visible, do n't you think that if you are looking here, pay attention here, this one comma can be zero but in the question it has been given that there are distinct values. Look here, the values are noted well. values. Look here, the values are noted well. values. Look here, the values are noted well. Unique, there will never be duplicate values, so here the parent of four, if you are there, then it will always be you, it will not be updated, it is clear till here, okay, so we have done this, we have written this function, this is my parent painter, this is my most Big one, less, it did it, okay, now I come to the function, I will do a vector of inter results, okay, train load, the target is clear till now the same old code as usual which we used to write our VFS. Okay, first of all, why did I push? Whose target has to be started from this and as soon as I have pushed, then we will have to forgive it is widgetized, okay, so we have taken a set and name it as widgetized, okay and all. Notes will be of unique values, that's why I can do that in that order set, so what I did was wild and management, this is the BF we had to write, okay but before that I will check here beforehand if my current level is Intel. At the beginning of the level, if my current level becomes equal to this level, then I will break. This is what I said, there is no need to take a separate level, we will keep mining the level. If it becomes zero, it means that we have crossed two levels. If I do it, I will break it from here, okay, after this, the code of normal BF is the same, tell Karan of the temple, it is also known from the note of account whether it is visited or not, then the value of the left side of the current, if it is my wasted. If it is not in the set, that means it must not have been in the state, then we also do the push current in the visited dot and search for the left value of the current. This has already been visited. Similarly, we will see the right side of the current and we will see the parent of the current. Otherwise, first of all, this It's done for my right child, so here I write right everywhere, right here too, right here, this was what I will have for my left child, okay, the value of parents' tax is okay. If the value of parents' tax is okay. If the value of parents' tax is okay. If the parent is off account tax, what does it mean that the value of this tax is present in the parent map, that means its parent will be available. What is its value? Look, I write here that the parent off tax bill will be equal, what will happen to you is the parents off tax. Neither will it be the parent of this current one, nor will it be whatever it is, so it should be present in the map and its value should be parented off, the value should not be visited by parenting, nor should it be wasted, so let's give it a pulse. First of all, this is this. Let's give pulses, I have turned off the parent in my K and to forgive its value, I have given pulses in the set here, Mines, I will say that one level is over, now there is nothing to be done in the last, as soon as I come out, my last level. The head will be present in element K. Okay, so what I will do is take it out of K and pop it and put its value in my result. Actually, where N is the number of notes in D tree, so this is a linear solution but two. Bar we have trigger travels submit let's see let cipher able tu pass which is solved in de best good solution any doubt is reason in de common area video thank you
|
All Nodes Distance K in Binary Tree
|
sum-of-distances-in-tree
|
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._
You can return the answer in **any order**.
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2
**Output:** \[7,4,1\]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
**Example 2:**
**Input:** root = \[1\], target = 1, k = 3
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 500]`.
* `0 <= Node.val <= 500`
* All the values `Node.val` are **unique**.
* `target` is the value of one of the nodes in the tree.
* `0 <= k <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Graph
|
Hard
|
1021,2175
|
947 |
Try to make a connection, how will the connection be made, like zero is zero, okay, now whoever is coming, in whose settings there is zero, you will get the connection with him, okay and you will get the zero, okay, now the connection is made, now the connection with whom. Build them and see which connection is next. Okay, just build the connection like this and at the end you will get some number of different pairs whose connections will be analyzed. Okay, first of all, it is very easy to get it by saying this question. What do you want? Okay, after that we will try to approach it for the final implementation So first of all, tell me this one was okay, apart from this there is no other one, so there is a connection between this and this, you are absolutely right. Now let's see what connection they have, so indirectly this will also be connected to this. Han, look, you have seen Zero, then this one came to you, now let's see from the first column which one is which from the first column. He said first. He was saying only and only from the column, he said, okay, so indirectly, these two, three, four, these four have indirect connection or direct connection, now see which one is starting from the first row, the answer will also be connected if seen from the first O. This one was starting and said, okay, now the two of them will have direct connection with them and the one with whom they will also have direct connection. Okay, so see, I have seen it from the van before. I saw it from the van only then, now let's see that you. Which column is starting from, then I told you, these were starting from different ones, okay, so indirectly, the whole of it, the error was that it was connected in itself, okay, it is not directly connected, but indirectly from somewhere. If it was connected, then you have to look at yourself and tell that in the end, remove all the connected ones, like this connector, all the connections are there, okay, first see how many are connected and in the last, all of them. If you remove the connections, then you have to return them last. Here, make connections with each pair, whether it is from row or column. Okay, so what do you do? Let's create a container type. Okay, what do you do? Yes, this is zero earning, zero, right here, show the note and say, okay, you know, now tell me, zero earning means its connection is done, 0 okay, somewhere here, its connection is done, separate connection is okay ] One more thing happens, 3 connections are made, okay, now why did I do this, it is a simple matter, the prerakat inside the graph also gets widgetized, why because if you start coming back to the same, I suggested but see its connection with this. It is absolutely correct and it is also absolutely correct along with the current one, there was a connection with both of them, now when their connections are going to roam, then this one will also be found, otherwise when he is getting this one on time, then he will say that No, you have already made this connection. You have already made this connection with someone else, so you do not need it. Now you understand what you have done. Let's do a simple one. First of all, let's take this one and check it. Let's do it, was it a visitor, if it is initial, then the first thing is that there was no circuit, okay, so if it is not visited, then one of its own has been made, then one of its graph has been made, okay, now let's see whose it is. If there is a connection then let's see the connection time, what do you have to do, you just have to check that you will have to run the look of four inside the whole and keep the four color while going, that means this whole will work from here otherwise. Okay, it has a connection, there was a connection with it, so you marked it, okay do it again, otherwise don't do it, and if as soon as you get calls, what do you say, I increase this van, okay then. Along with this, it has a connection with anywhere, I have opened the graph, I have done it many times, okay, so I did not understand the graph very deeply, I directly asked the concept about what seemed to be your concept and looked at the concept. What was the concept trying to say here? Okay, so this function, sorry, comes in this function, after that, what have you done, you have created a widget named global, which is called global. What's the matter again and again Apne Na Ye Hey pass this vector, I did n't have to pass it, so Apne Kya Hai I made it global and now what did I make its size, I made an entry and how did I initialize it with zero, okay now What is this word of recise? What is the word of recise? What did you do after creating your vector? Now after creating the vector, it becomes impossible to size it. So what to do is to name it a recise and say that now we will resize it. If you can, you do racing. He said make it M size and race everyone below zero. Okay, it's very good, you have understood yourself well, after that what is your next plan? There is a variable named value, it was told that there should be no problem in the total number of, after that then we made a loop of 4, okay, in the look of 4, where to track our account, in the look of four, we made our Puri. Clicking on the stores, okay, if I look at it a little here, then see the number of stones, that is, six times, we will trade, okay, very good, after that, what did we say that if this widget is Tell the name if you did it with zero then zero tips you false means if there is zero inside a condition inside this condition then it is not ahead that condition is correct Han so if there is zero then it is ok then it will go inside it and if When the van comes, what will happen, it will continue, leave it back, it will start setting for the next one, leave that value, okay, so what happened now, this is not true, it is absolutely correct, so now it has gone ahead. First of all, value plus will be created, okay, very good, after that, we will have a function call in DFS, okay, leave it, once again understand this, what will be happening here, our connections will be happening right. The thing is that after that, the second value will be ours, there you add the values plus, will be ours, there you add the values plus, will be ours, there you add the values plus, this much I understood and in the last I am returning that whatever the total values were, it is ours, how many values were, it is ours, how many values were, it is ours, how many numbers of grass are formed out of them, by subtracting them. Give whatever return act, whatever answer you get, it will be the same, okay, very good, now let us understand what he was doing, okay, what are you doing, we will create the keyword, whatever is the index, first of all, mark it and say, okay, very good. Okay, after that I have four colors with you. First of all, tell me whether its disease is equal to its form or its column is equal to it. Okay, so first of all this value will be vane. If that is correct, then it should also be widgetized. First of all, you are getting connections from them. If you are fine, then all the connections are fine from there. All the indirect connections are fine. From the direct connections, I have marked van on all of them, so go back to the video again and if He was a rogue, I hope you have understood it well, still if you have any doubt then you will find your comment box.
|
Most Stones Removed with Same Row or Column
|
online-election
|
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed.
Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_.
**Example 1:**
**Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 5
**Explanation:** One way to remove 5 stones is as follows:
1. Remove stone \[2,2\] because it shares the same row as \[2,1\].
2. Remove stone \[2,1\] because it shares the same column as \[0,1\].
3. Remove stone \[1,2\] because it shares the same row as \[1,0\].
4. Remove stone \[1,0\] because it shares the same column as \[0,0\].
5. Remove stone \[0,1\] because it shares the same row as \[0,0\].
Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane.
**Example 2:**
**Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\]
**Output:** 3
**Explanation:** One way to make 3 moves is as follows:
1. Remove stone \[2,2\] because it shares the same row as \[2,0\].
2. Remove stone \[2,0\] because it shares the same column as \[0,0\].
3. Remove stone \[0,2\] because it shares the same row as \[0,0\].
Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane.
**Example 3:**
**Input:** stones = \[\[0,0\]\]
**Output:** 0
**Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it.
**Constraints:**
* `1 <= stones.length <= 1000`
* `0 <= xi, yi <= 104`
* No two stones are at the same coordinate point.
| null |
Array,Hash Table,Binary Search,Design
|
Medium
|
1483
|
310 |
hi everyone there let's sological question called minimum height tree well the higher the tree is defined as numbers edges on the longest downward pass between the root and the in other words the number stages are the distance between the root and leave and we want to list our own minimum time trees root labels in other words central points in any order well the question looks very wrong so let's check example here two are the ones that so you see the example one who have four nodes zero one two three and we see the edge node tell us okay y connected to zero while connected to two and one class three so you see it's obviously the root or the centroid is one and after this let's check example two has six nodes uh all the way from zero to five and the edge dot is three connected to zero one two four and four is additionally connected uh to five so central point can be both uh three and four because they are uh both this is one from the leave node okay so for this kind of graph problem we can actually use a json release to record the connection information are you dangerous so let me use the graph joining here to show how to solve this kind of problem okay so i'll use a green color here and write it on the right side so we'll build as a json uh list we json this with a key of a post node so let me write it out here a sixth node right the first will be zero and one we have two whereas three we have four and we have five okay so this is the keys and write the key here and we also want to add mouse right and you see a zero here connected to three so the value is three one connected to three so there are also three it was two also we have three and after that posture u has slightly longer values uh to have uh both zero and one we have two and we have four since we have three four here and four we have two uh notes one is three and one five since we have four five here and four five will have only uh default okay now i have finished the mapping position or adjacent this uh between the keyboard and valves now the next step is to determine which one the deep nodes which will remove in the next step okay you see all the live nodes have uh only one valve in the json list so this one zero is the leave node let me use different collection so red one indicates when this is aluminum and y is believed note 2 is the lymph node three has four so are non-living nodes non-living nodes non-living nodes or it has twos on non-level nodes by far or it has twos on non-level nodes by far or it has twos on non-level nodes by far and five have only one so this is limitless so next step of determining the leave node we have to uh remove the leave node from uh from our graph list so we can further determine the central points uh in the next step okay so let's use different colors here let's use blue color which in the case of the luminol we will remove this node because it's leave and we'll remove these three nodes this node will remove this node will visual mode and this node will be removed right okay once we remove this node we have to update our json list so let's check which one to update well after the first step uh for remove zero is no longer this so we'll clean this out y is also not exist so bring this up and also true does not exist so clean this up and we also need to check the three right because after that 3 has only the 4 as its element okay now we only need 4 and for four now only three oh sorry i did not only have three and four five you know five doesn't exist so clean this out okay and in this step you want to see okay three has uh only one length or less one for the valve and four only have uh less one for the belt in this case i would have found the central point and we have to turn accurate into 4. okay so let me repeat again if we clean out the lymph nodes and found okay both nodes are has length 1 for the bell these means are both not a central point and we just return that in the result array so let me use a different color here we want to return the result array by continuing this two node three and four and we are done okay now for this information let's dive into the coding part so this code is uh slightly long so i will write this video i write the code before recording this video so the first case we have to consider always uh for this ground node is the corner cases so far looking the numbers nodes is smaller than two so maybe the numbers nodes is zero or one if that case now zero will be always including the central node so we just return zero and after that we want to build the graph of adjacent list so let me scroll it down you see we will use this function python so you it will build uh a number of sets with the lasso end right so there are total answers in this array and after this we want to build uh the json list using the edges that will point both source to a destination and destination to source so in this way for example uh here's a one zero will be 36 or with zero one uh for sequence and after that we want to build a crew with all the first level nodes in other words the leaves so we just call this python function we found okay if the length of json node is equal to 1 to this step this means this will be the leave node and we want to include it and after that we want to keep removing the first level or in other words the current leaves until there are only one or two remains this means we have only the central point remains in that case uh we first will pop all the neighbor nodes that removes the edges we see here we'll deduct the m by the lancer leaves which is the current leave node and we want to go through all the lymph nodes in the current level and we'll use this function so first we'll pop the neighbors and funds are all neighbors first level nodes and remove it so we remove the both the edges and the first level node you found okay at this time the lens adjacent list of this neighbor is equal to one this means okay this uh neighbor exactly the center point and we want to append this uh to our result array and we call it the leaves on next right because maybe we are updating it uh in the next duration and after that we'll assign leaves on next to use so in the next introduction uh we'll use uh we'll use uh we'll use uh in the current uh iteration and finally we will turn the leaf if this entire while loop is finished and we get all the central point the result array okay now let's submit the result to see it works okay you see the time capacity memory usage all these questions are not so bad and overall the coding part is long and explanation takes sometimes uh i think it's relatively easy to understand okay you like this video please subscribe to my channel and i'll see you next time thank you
|
Minimum Height Trees
|
minimum-height-trees
|
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs).
Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**.
The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
**Example 1:**
**Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\]
**Output:** \[1\]
**Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
**Example 2:**
**Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\]
**Output:** \[3,4\]
**Constraints:**
* `1 <= n <= 2 * 104`
* `edges.length == n - 1`
* `0 <= ai, bi < n`
* `ai != bi`
* All the pairs `(ai, bi)` are distinct.
* The given input is **guaranteed** to be a tree and there will be **no repeated** edges.
|
How many MHTs can a graph have at most?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
207,210
|
148 |
hello everyone welcome to our channel code with sunny and in this video we will be talking about the problem medium problem called sort list its index is 148 and it is the daily problem of the lead code for the month of february day 24 okay so yeah this problem is totally related to the concepts of linked list and like sorting algorithms like if you are aware about the merge sort technique then you can solve this problem efficiently yeah you can also use other sorting algorithms called quick sort or yeah maybe insertion shot also but yeah for this problem the best way to do that is you're going to use merge sort technique it would help us to do this problem in o of n log n time complexity and in the best case you can have a of one space complexity okay so i will deal all those in this video so let's begin so given the head of a linked list and return the list after sorting it in ascending order okay so we need to use some sorting algorithms to perform this operation so we would be using merge sort okay so merge sort on an array is quite simple so yeah but here we are going to use a linked list and that would also help us to like you can have open space complexity if you use the pointers of linked list carefully to adjust the nodes so that the nodes values are in ascending order okay so i will deal all those now so let's head over to the constraints first so the number of nodes in the list is in the range you can see at max is 5 into 10 raised to the power 4 it also suggests that we are going to use the o of n log n time complexity to do this problem yeah and also there is a follow up can we do it in one memory constant space here we can do that so let's discuss this problem with this example okay so let's begin so suppose we have the nodes like this one for this two and this and then we have one and then we have three okay so uh and this is the like unsorted linked list let me write down over here and sorted linked list and we need to sort this link list according to their values so you can see the sorted link list would be like that 1 2 followed by 3 and then followed by four okay so one thing also you're not going to swap the values of the notes you're going to swap the notes address and their positions okay so that is one will come we will become the head the notes address will become the head followed by like its next pointer will be pointing to the node with value two okay so this will come over here and again three will come over here and four will come to this position so how we are going to do that efficiently so uh in the in an array when we are using a merge sort so what will happen is like we will divide the address repeatedly in two parts so let me write down over here we are going to use the concept of merge sort so what merge sort says is like suppose we have this linked list so we will divide this linked list into two parts like over this position so yeah and again when this list is divided into two parts we are going to perform the merge sort operation again over these uh divided parts okay and when we are done with this one like suppose after some repetitive repetition call of this merge sort function we have the linked list as a sorted over here is like 2 4 and for this right part we have a sorted linked list as 1 3 okay now we need to merge this link list into a single linked list okay note that we are here calling a function called merge so what it will do is like it will merge these two sorted linked list into a single linked list it is quite similar to the concept of arrays we have two sorted arrays and we need to merge them into a single sorted array containing the same values as in the both of the arrays right so we need to merge this linked list so it will become one followed by two followed by three and followed by four okay so yeah so uh in that case what you are going to do is you need to find out the middle node right middle node in the con like when we divide this an array or a linked list into two parts the very key point is like we need to know the middle index in an array or the middle node in a linked list okay so how to find that middle node so when you are traversing this linked list note that when we traverse the linked list we are always traversing from the head of the linked list so in the worst case when we i trade in a brute force manner like in a linear time complexity to find out the middle node you can see it will take a of and time complexity to find out the middle node okay so we can also improve that of n time complexity to o of log n time complexity to find out the middle node let me write down o of login complexity to find middle node okay so first let's understand how we are going to find out this middle node efficiently okay so it is quite simple we need to use the concept of slow pointer and fast pointer suppose we have this linked list let's say containing four nodes okay so what we are going to do is we are going to place a slow pointer over here and a fast pointer also over here and each time slow pointer moves by one position and first pointer moves by two positions okay so in the next case slow pointer will come over here but first point i would come over here so in the next step slow pointer would be over here and first point of view over here so let me denote it by slow one and fast one okay now again slow pointer will move by one position and first pointer will move by two position so you can see the next position of the slope pointer and first point would be slow two and first would be out of this linkage denoting the null point the soviet we are going to stop it over here because we cannot move further we cannot step both slow point and fast pointer by the next positions okay so this will be a middle of this linked list that here it is the length of the linked list is even so we not we are not having a uniform number of nodes to the left and to the right of it okay so we can have this middle of the node so what about when the linked list is odd containing the number of notes as an odd number you can see uh initially slow pointer will be over here and first pointer will be over here and in the next step slow pointer will come out to be over here and first pointer will be over here and the next step slow pointed will be over here and first pointer will be over here and we are done we cannot move fast pointed by the two steps to the next overhead so we are done so this is the middle node so finding a middle node with this concept will take a of log n time complexity because you know first pointer will always move by two step forwards and yeah in the worst case it will take a logarithmic time complexity okay so yeah so this is the idea to find out the middle node and when we have done with the middle node then we can divide this linked list into two parts so what i am going to do is like suppose this mid is going to denote the middle node okay so this mid is the middle node so we will again call this merge sort function word sort what is the left uh left bound of this linked list so the left bound of this linked list would be uh like left part of this linked list is the head one so i will denote it by head and again the right part of this linked list would be the right part that would be made next so when we call this merge sort function for the left part and the right part you would be having this yeah and one more thing i could add is like i could add the merge function over this left part and over this right part when we add this merge function it will actually merge the two sorted arrays merge to sortedder if you are able to merge these two sorted arrays then we are done then we finally will be having some link list in a sorted form so okay so let's look out for the code how we can implement this in efficiently so yeah it would in the best case it could have a time complexity of n log n and we are having the space complexity as o of 1 okay so yeah so we can start over this given inbuilt function sort list and we are going to call this merge sort function or passing the parameter as the head okay so obviously we'll be having two functions called merge and this called merge sort right okay so let's first write down the base case let me first zoom it out yeah so we are having this base case add if head is a null pointer or heads next is the null pointer so basically if it's next to the null pointer it will denote the size of this linked list as one and if head is a null pointer the size of the linked list is uh like we are having an empty linked list okay so let's write down a base case for the length two we can we are going to have this suppose if heads next is and yeah so if the length of the linked list is two we are going to write down heads next and next will be a null pointer okay so in that case we are having uh we would be swapping the values of this uh two size linked list if you are able to make them in ascending order then we are done so this if part of your uh we are doing the same thing you can observe it over here if it's next its value is going to be strictly less than the first nodes value then we are going to swap this one okay now the rest of the criteria is quite simple so we will assign a slow pointer as well as the first pointer to the beginning of the linked list okay so if fast pointer is a null pointer and past next point is also a null pointer then we will increment this low pointer by one step and first pointer by two steps okay so yeah and when we are done this with this one we are going to have this middle of the node is stored in this slow pointer so what we are going to do in the next part is like we will call the merge sort function for the rest of the linked list so yeah you can see i am passing the parameter as slows next and we will assign the slows next as null pointer when we are done with this calling part of the second merge sort function and again when we are done with this one we will assign slows next has null pointer because the we need to call for the left part also so now we are calling for the left part you can see i will just pass the pointer as head right and now we are we need to focus it upon how we can merge these two sorted linked lists okay so let's look out for the merge function so if l is a null pointer and r is the null pointer we will just check out their values at the corresponding nodes else value and rs value so else next is going to call this merge function you can see suppose we are having the values let's say two let me just change out the color two then one let's say two and four and another linked list is going to have the values called one and two so it will first compare this value two with the value 1 so you can see value 1 is going to be smaller than the value 2 so yeah it would merge the next pointer you can see else next with this r and this merge function will return a node's address and it will be stored in else next and then we'll return this l pointer and if this will not happen then we can have uh ours next pointing to this merge part of this l and r next that is it will be moving to the next node's address of this r okay and suppose in if that exists a case if both l point and r pointer is both null then we will return uh like any one of the l or r is the null pointer then return will check it out this condition if l is null pointer then we'll return our otherwise return so this will give you all test cases passed right so if you guys have still any doubts you can reach out to us in the comment section of the video and thank you for watching this video
|
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,743 |
Hello everyone welcome to my channel code share with me so today I am going to do video number 8 of my hash map hashset playlist lead code number 1743 is marked medium but its solution is quite easy but I liked this question very much ok I Made this question for the first time, the name of the question is Restore the Are from Adjacent Pairs. Okay and before starting, let me tell you about the video I had made yesterday, Maximum Balance Sub Sequence, So the third optimal approach of it, I have used that video. It was written in the comment section of the video that whoever solved AIS with the help of that third approach, because there was a variant of AIS, then AIS can also be solved. In yesterday's video, we had to find the sum, in AIS we have to find the length. So, using the third approach, two people had created LIS and they had also posted it in the comment, their name is Devkumar 9889, one is this profile and one is this profile, okay you both get it, please share it with me in the comment. In your code itself, in the code comment itself, I have replied to you guys. Okay, I will share the Ajna Voucher with you guys via email. Thank you so much and I will keep making more announcements like this. Okay, let's start. Look, the question says. That is an integer that contains n elements is ok but you have forgotten it is ok How ever you remember every pair of adjacent elements in names but you remember which pairs were adjacently present ok you are given a 2d integer where there are adjacent pairs of size n -1 Where adjacent pairs of size n -1 Where adjacent pairs of size n -1 Where each adjacent pairs aa u aavi indicates that the elements u aa and v are adjacent in numbers What does it mean that if let's say here it is written 23 It means let's say 2 6 is written It means that na in the numbers Both of them will definitely be nearby, either 26 or 62, anything can happen but both will be adjacent to each other, okay, so it is guaranteed that every adjacent pair of elements, numbers a and numbers i + 1, will exist in adjacent pairs, that numbers i + 1, will exist in adjacent pairs, that numbers i + 1, will exist in adjacent pairs, that is, right. A valid example would be that all those pairs would be present in the adjacent pair. Okay, here and there, numbers i and numbers i + 1 and numbers i Okay, here and there, numbers i and numbers i + 1 and numbers i Okay, here and there, numbers i and numbers i + 1 and numbers i + 1, numbers i. I mean, I had said that either 26 + 1, numbers i. I mean, I had said that either 26 + 1, numbers i. I mean, I had said that either 26 or 62 would be present like this, but it would definitely be present in the adjacency. The pairs can appear in any order OK Return the original Are the names if there are multiple Solution Return any of them OK The original You have to return For example Look at this example 21 34 32 What I am trying to say is that your original There were no names, two and one were nearby and three and four were also nearby, but three and two were also nearby, so look here, this will be the answer to 3, 4. Look, this is what I am saying that this Your valid answer is Look in this T and One are nearby Yes and Four are also adjacent Yes 3 and Two are also adjacent Is yes Look Th and Two are also adjacent There can be another answer to this Look Pay attention 4 321 Look what again Let's check whether all the valid adjacency pairs are 2 and yes. 21 see there is 3 in the adjacency. 4 is yes. 34 is also adjunct. Even though 4 and th are there but there is no difference. Both should be adjuncts. 32 is yes. Look. 32 is adjunct. Okay, so a very good example. This is also a very good question. Let's build our solution. We will not directly come to the solution. We will build the intuition. How should such problems be approached? So let's come to its intuition. You will remember its output. I had written about it, what was its output. Here I write both the outputs Possible Output 1 2 3 4 Either 4321 Both are correct answers OK send any one the answer will be accepted because all the adjacent pairs are correct 2 1 See it is seen together 3 4 It is seen together 32 is also visible along with it. Okay, so let's see how I thought. Look at this, first of all, I did not understand that I should first make n, the size is ok. 0 1 2 3. So now let's look at all the elements one by one. What is the first element? So what did I do? Randomly put 1 here. I put 1 here because that is the first element I saw. Okay, now it is 3 4. So first let's see what it is trying to say. That three and four should appear together. Okay, so first of all let's check whether the pairing of three is already done. Is the adjacency list with anyone, that is, adjacent to anyone? If we look at it, then I have not yet entered three. Hey, for that, how will I know, I will keep keeping in the map which element I have put in which index, I have put two in zero, I have put one in one, now when 3 and 4 came, I saw three. I have not yet put it in the map, right three has not been put in the map, so it means that I am not worried, I can put three comfortably now, so I put three here and then changed the index of three to two and I haven't even put four in the map yet, so what did I do, I put four as it is okay, now I came here at 32, okay now look, I came at 3 2, let's see what is the index of three, I put three. The index number is two but here four is placed on three. Three is placed on index number two and on which index have I placed two. Look, both are adjacent. Obviously both are not adjacent. The distance of the middle index is not one, isn't it? Look, two, like here there is three and here there are two distances, they have no adjacency, a little, adjacency, not both, so friend, for this you are again the same now. How to shuffle this, I do n't see the solution from here, how would you think for yourself, coming here, I am stuck, let's assume th is two, so what I did is that the index just next to two is three. I brought it ok and I brought 1 here ok so see 2 3 is done right and 2 and now are separated see 21 should also have been together so this is the only possible solution that cannot be found in this way. I was trying to adopt random, I should try to swap any index, look at any, when 2 and 3 are adjacent, because I had to fix it, okay, then look, 2 1 is gone, 21 should also be adjacent. So such a solution will not come out, you understand the limitation of this approach that if you put random 21, put 34, put 32, it will not work, that is, the root force which you wanted to fill line by line, put 21 first and 34 first. If it doesn't work, then brute force has failed here, okay, then I thought that means this straight forward solution will not come from here, okay then what did I do, remember what I said before that already Hey, I took 01 23 of four sizes, I won't do that, forget it now because I couldn't understand which one I should put where, I used to fix one pair and the other pair got damaged, isn't the other adjacent pair damaged? If it used to be done, then let's do one thing. Let's think a little differently. Look here, there is two here, meaning what it is trying to say is that two and one should come next or either 2 1 comes first or 1 comes first. Okay, that means either two comes first or one comes, meaning you can write 2nd or you can write ntu, it is the same thing, so I write that two and one will come together, then after this comes 3f, so it is ok. 3 and 4 will also come together, till now it is clear, after that there is 2, look and 2 should come together, but here 3 and 2 are not together, so let's do one thing, I will now add to these people that brother, both of you are together, do not stay away. Stand up, okay, and I will add these people also. Two and one, seven are adjacent and which are the adjacent ones, three and four are adjacent, so see, this means that I started getting a hint from here that friend, we will have to make it by connecting. This means that you will have to think in a graphical way, you are looking at two, because look, then I would have made the same mistake as I did here, when th and two are not shown together, then I would have removed the three from here and made it equal, but then four. It gets separated here, even with three and four, it is okay to stay here, so I say let everyone stay where they are, two is one, three is four, you connect them, two and one are connected, three and one are connected. What is the problem? What am I saying? Tell me actually what is this? This is actually an adjacency list and nothing else. We used to make adjacency list in the map. Remember, I always keep saying ADJ. This is the same and nothing else. Look at the adjacency list. See how many neighbors of two are connected to one. Are connected to two. The adjacent neighbor of two is one and the adjacent neighbor of one is two. I have made an undirected graph. Why am I making an undirected graph because two are One can go from one and one can go from one to two. It is given in the question, write either 2 and or write two, it is the same thing, both should be adjacent. Okay, look at which other graphs are visible and the edge is visible. From two to th is one edge and from three to th is one, neither is se than put here nor here is the neighbors, I am writing two from and th from also becomes two, so I made th from two and look, this is also four from th. So here I made it from 0 to 4, so you can understand from here how I reached there. It's okay in making the adjacency list. Blind, I took one hey size and was putting 21, 34 and 32 in it. So see, I was stuck. That's why I thought that we can't make blind connections like this, so my mind ran towards the adjacency list. Okay, let's take the ads, so it's made, now what's okay, now the important question is what should be done now, so look at this thing, I How did it break? To understand my entire thought process, pay attention to this diagram. Okay, look, know who is the most tension free, one and four. I will tell you the reason. What does tension free mean because look, one has no tension that his Who else is going to come on the other side because there is only one person in the forest, assuming that I write one here, then there is only one tension of the forest that two should come just next to the forest, there is no other tension in the forest. That there should be someone else to come next to the forest, is n't it the same for the forest? The forest is the least tension free. Pay attention to the four too. The four also have no tension. The four knows that there is only one edge which is mine. That it is being made of three and there is no edge, mine is fine, four is also tension free but look at two is under great tension because what does two have to take care of, one of my edges should be connected to one and there should be three on the other side. Should means Two will always have to stay next to Th because Two's adjacent one is also Two's adjacent three. Okay, so this is tension for Two, so let's do one thing, those who do not have tension, first start from there with one. Let's start with One. There is only one Adjacent of One. So close your eyes and enter 'One' because there close your eyes and enter 'One' because there close your eyes and enter 'One' because there is no one else around, so there is no tension. Okay, now see who is the Adjacent of Two. The Adjacent of Two is One. So I have already written, so one tension of two is over, already who is the next adjacent neighbor of two, three, just written three, the work is over, okay now who is the next adjacent neighbor of three, look, who is the next adjacent neighbor of three, from here you can see two and Four is both but two but why would you go back to two? It is just previous, isn't it? You can go back to two also from three. You can go to four, but why would you go to two again? That is wise, D is fine, so there is only one neighbor left, four. So there were two tensions of three, one was two and four was two, it was already printed, only four remained, we reached four, just look, pay attention, our answer has actually come and we started with which one was tension free because I knew it. There is only one judge, here is the answer even if you had started from four, see how you started from four, why because four has no tension, he has only one judge, he has to make a connection with three, four should not take tension. That someone else should have come before me, okay then you can say that why are you able to start from one and four because look here, I have not written about four, what is of four, what is the edge, what is that. There is three, right? I didn't write that, so why are one and four tension free? Because look, one has only one neighbor. Four also has only one neighbor, right? Three and two have tension, because look. They have to maintain a relationship with both the two people, there is no tension between one and four, they have to have a relationship with only one person, that's fine, then it came first, it is written with four has only one neighbor, and with three, it is written with three. If there are two neighbours, one is four and one is two, four is already there. If the previous one of three has visited, then he will go next. Who is next to three? Who is two? Two has gone to two. Look, here two are near two. There were two tensions, look here, one was but three was already printed, which was its previous one, okay so who is next to two, one is one, so one has been printed, look, these two were your answers, what does this mean? What happened is that the adjacency list that we have created, the map that we have created, what is this map, it is a kind of adjacency, so we just had to do a simple traversal in it, but where to start the traversal, which is tension free from one. Either from Four, who is more tension free, who has only one relation to keep, One has only one relation, Four also has only one relation, you will start your traversal from either of the two, see, you are doing traversal only. Went from one to two, came from two to two, went from two to three, came from three, went from three to four, you are doing traversal only, either do DFS traversal, either do BFS traversal, I will solve it with DFS, okay then do traversal. But what was the tension, where to start, then start with the one who is tension free, brother, the person with only one neighbor, because if he is the one, then we accept that one is tension free, why is he tension free? Because he is not worried about whether someone else should come on the left side or not, he just knows that it is okay, I have only one neighbor, whoever is there after one will come, after one, sorry if there was two, then two will come, that's it. That's why we either started our DF traversal from one or started from four. Both of them will give us the correct answer. So see, this is how we build the solution. First, I showed you what approach I tried to take. I got stuck, then why did I try to make an arrow like this, why did I try to make an adjacency like this, and even after making an S, how did I think that the approach is fine, so it is quite simple, what will we do first of all, we will make the adjacency list, the first point, so I am writing the story points. First of all we will make ADJ, after that we will find from whom to start, this is our DFS, who will be the starting point for him, who will be the starting point, who has only one neighbor, pick any person with one neighbor there. From there you will hit DFS, from there you will automatically get the answer. Okay and pay attention to you, I will repeat it here again, let's assume you started from one. Okay, now from one, when you went to two, because of one. There is only one neighbor, there is only one neighbor, so now we have gone to two, now look at two, there are two neighbors, here one and three are both, one, three has become this and one has become that, you will go to one again in a bicycle. If you get stuck then it is an obvious thing that you do not have to go to your previous node. Okay, if you do not want to go to the previous node then you can go to Visitech, it is one Visitech, but you do not need Vid, is Visitech, it is one Visitech, but you do not need Vid, you can do this as soon as you go to two. But do n't you come and tell me, brother, if your previous one is one, then what will two do? Will he check his neighbor? What is the neighbor of two ? Is it equal to the previous one? Yes, then ? Is it equal to the previous one? Yes, then ? Is it equal to the previous one? Yes, then he should not go there. Three, this is previous. Otherwise, it will go to three. It will go to three. For three, remember who was the previous one. For three, the previous one was two. Because where I have come from three, if I have come from two, then who are the neighbors of three? Three's neighbors are two and If there is four, then first look near two, then two is its predecessor, yes, then we will not go there, if four is not its predecessor, then we will go to four, then we have gone near four, right? You have done this previous method many times, already I told you. Okay, in one or two questions, I mean, why am I using previous so that I don't have to use Visitec array, otherwise you can make it from wasted array also, there is no problem, in normal DFS we use wasted array, that too. It will be done, there is no problem, okay, so these were the three points to solve this question, and this is a very lovely question, okay, and what will be the time complexity, if you notice, we are visiting all the numbers only once. If tooth is 4, then how many total numbers were there. If there were n numbers, then it will be off. Time complex is visiting the bars only once. Let's do space complexity. So let's start. What was our first step? Make an adjacency list. Okay. Now look, pay attention, we have created the adjacency list, so we have to fill the adjacency list, so first of all we iterate this pair of our vector of int and vac adjacency pairs. Okay, let's traverse it by putting a for loop. Now look, pay attention, int. y e wake off 0 int v e wake offv Okay, Adjacent p has the same two elements in every index so y and taken out and ad j of yd push under back v Similarly u savvy means u and v are adjacent and v From U because I and U are adjacent, okay, we have populated our map, we have made the adjacency list, after that I had said that you will have to find the start point, let us assume -1 in starting, then we will pick you will have to find the start point, let us assume -1 in starting, then we will pick you will have to find the start point, let us assume -1 in starting, then we will pick it in the map, who will be starting. Point which has only one neighbor, we will pick any one starting point, which has only one neighbor, then I am traversing the auto and IT in ADJ Adsense list, okay, look, whose IT dot second, remember, there used to be a neighbor, right here. From int to vector int, this was the neighbor. The second element was the neighbor. If its size is equal to one, it means that it has only one tension, it has only one relation, then the starting point will be IT. First, okay, let's break here. We have found the starting point ok now simple what to do is to call DFS from where to start DFS from the start point ok and we do not know the previous of the start point so who is there so take anything in the previous i.e. who is there so take anything in the previous i.e. who is there so take anything in the previous i.e. any yard number I take int mind, okay, why are we taking previus because visit, I don't want to use it, okay, we will have to send ADJ and let's take a global vector in which we will store our result, vector of int result, okay, as we will do traversal in DFS. We will keep storing the answer in the result. Void DFS int current node is this, its previous is this and what else were you sending ADJ, then ADJ is this, mine is fine now I don't pay attention as soon as I came to this current node is this then Yes, let's put it in the result, push underscore back u ok now see pay attention int and v eddy j of y are going to neighbor of u ok but will not go back to previous only if this v is not equal to previous. If we go ahead of him to hit DFS then let's hit DFS, on whom to hit Hadi, now we have to hit v, who was the previous element of v, where we have come from, but v is the previous element of y, and sending ADJ has to be sent, it is okay, let's see by submitting directly. Hope fully we should be able to pass all the dis cases here sorry we did not return the result ok let's see the java code you will find it in my git hub ok I hope I was able to help you build intuition Any doubt always raise in comment section. Will try to help or see you again next video.
|
Restore the Array From Adjacent Pairs
|
count-substrings-that-differ-by-one-character
|
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`.
You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`.
It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**.
Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_.
**Example 1:**
**Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\]
**Output:** \[1,2,3,4\]
**Explanation:** This array has all its adjacent pairs in adjacentPairs.
Notice that adjacentPairs\[i\] may not be in left-to-right order.
**Example 2:**
**Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\]
**Output:** \[-2,4,1,-3\]
**Explanation:** There can be negative numbers.
Another solution is \[-3,1,4,-2\], which would also be accepted.
**Example 3:**
**Input:** adjacentPairs = \[\[100000,-100000\]\]
**Output:** \[100000,-100000\]
**Constraints:**
* `nums.length == n`
* `adjacentPairs.length == n - 1`
* `adjacentPairs[i].length == 2`
* `2 <= n <= 105`
* `-105 <= nums[i], ui, vi <= 105`
* There exists some `nums` that has `adjacentPairs` as its pairs.
|
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
|
Hash Table,String,Dynamic Programming
|
Medium
|
2256
|
218 |
hey everybody oh this is Larry this is day 30 up it's his last day it is the last day yay congratulate yourself a little bit especially if you finish it hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Forum oh what I thought we could already do this okay apparently there's a new question page you could do a problem this I don't care oh there's a timer people been requesting for a timer for a while huh so this is today apparently it's a reaction video on me reading these things debug writer debuggers premium I know it's been there for a while though but at the time I don't really care about I mean uh you could watch this is my time as um it's a little bit uh lying on that way discussion don't care share your Solutions also don't care what does that mean actually is it just like is this the same idea of kind of ripping off how is this different than discussion hmm it seems like um like a little bit of a whip off of bsio or something like this binary search this is a little bit awkward huh test cases is interesting Maybe how does this work sorry friends I'm a little bit just trying to figure out a system and how to what the hmm okay so I actually did like the old one too can we go back to the old one I should I mean actually I did like I do like this uh going left and right for more uh coverage but I'm curious like I did like the multi inputting thing so I don't know is this premium I think it's premium right okay so I'm just testing a little bit Auto seems a little bit awkward but I do miss the framework I mean I don't use it that much on stream but I think it's just very easy because um because it allows me to input cases without using the mouse which is you know but they do have the default test cases which is good um so you don't have to click on like whatever it is to get the game thing so yeah that's good anyway sorry friends uh I'm still discovering a little bit about the UI what does this do oh that's premium anyway all right fine that's a little bit weird hmm or maybe not I don't know that just seems a little bit like um I guess maybe it's supposed to be a little bit like an IDE but I also feel like that um foreign because like if you're um if you're practicing for your interview like you probably should I mean either it matters or it doesn't matter right um when on your interviews so it shouldn't come up by the way like if it matters then let me say you should already know it and if it doesn't matter then it doesn't matter right so um okay anyway let's actually read the problem sorry if I had to spend a couple of minutes on the reaction time hmm I haven't added notes on some I don't even know what all this stuff is but huh sorry friends I'm still like discovering some of these UI things okay anyway let's get started today um well last day of September welcome uh what I was also going to say was that I was going to do a bonus question today I don't I know that before I went on my month-long trip I before I went on my month-long trip I before I went on my month-long trip I actually was doing a daily extra bonus question I might or may not get back to that um I have a very busy uh cup of scheduling if you will but I will you know I still do my daily one so don't worry about that for at least for a little bit but yeah let's see that means I can make this smaller maybe that's that part is good can I minimize this all together I guess I could click on this right so okay maybe that's not bad okay well one thing I do want to see is if they tell you I guess it only matters for uh whoops I guess it only matters for um for contest right for me like they're here the comparison things I just want to see what it looks like wrong answer like it doesn't matter right and obviously on a contest you don't get a free you know check but for examples you should is why I'm saying that because for an example I would like they give you the example answer anyway right so just compare it for me in that case um I don't know that I think this is a little bit too like I said I have to look at maybe different things that we'll see how that kind of excuse me no excuse me um what I mean is that um I don't know if this is oh I guess maybe the Red Dot that's what that means let's put I'm playing around the UI more than I'm playing around the question sorry friends I'm sure uh yeah this is just this is my reaction video maybe on the UI okay so then here it gives you a Green Dot okay that's actually not bad okay that's pretty cool okay we'll see what happens but let's actually look at the problem what problem are we doing now so a city skylining is the owl Contour geometric left sub I is the left edge of the building right is the right edge of the building h is the height okay so we did it and it always goes from zero to the height right okay is there any inherent ordering I mean obviously lap is equal to right buildings are sorted by left sub I uh and each of them could go to 2 to the 31 so definitely need some um yeah the way that I usually do these things and depending on the context not gonna lie is not always um oh it's optimal but we'll see but the way that I do it is with a sweep line right what is a sweep line or line sweep I always forget which ones which because everyone uses interchangeably but basically you're given a graph and you have a vertical line and you go from left to right or right to left depending how you want to do it but from you know zero to Infinity X on x-axis right and then as you kind X on x-axis right and then as you kind X on x-axis right and then as you kind of do that sweep you basically draw that outline every step so that's basically what I'm gonna do so let's do it so basically we have a left right height in buildings oh I see that this Auto coming I don't know how you feel about that to be honest like I said I um like I think I did okay without it but we'll see maybe I mean I'll definitely get used to it also the other thing is that I don't know how much of this stuff is into the contest UI because the contest is a different UI right which is always I like this UI better just because I can see the problem a lot of solving at the same time I don't need the whole like whatever for editing and you in the contest you'll see me scroll up a lot right so I don't know anyway I haven't still haven't really started the problem so let's see okay so the way that I do it is by you friend sorting um and how do I do it right you friends is you go to do basically I mean I don't have a full idea on how to do this yet but the idea is that okay you know we Define the left Edge what is the output again so two oh two it goes to 10 3 goes to 15 and then so forth okay um but yeah we append the x-axis of it is one thing and then the x-axis of it is one thing and then the x-axis of it is one thing and then the height is the other right and then maybe we could do something like at the end of at the right we do negative height or something like this maybe you could also use a flag right so maybe you could do something like one and then negative one height so this is like to add or remove and yeah and then now we saw it so that it goes from left to right and yeah so then here now we're trying to keep um yeah I'm trying to think whether I need a sorted list is what I'm thinking in my mind um yeah let's just use a solder list so uh right and then it's getting from left to right but for x uh t for type and then height in defense what do we do um we also have an answer thing I suppose just to keep track and maybe the last height is you go to zero or something like this so that we can use it to gauge the changes so then now we have this event if T is equal to one that means that we're adding a height then the assorted list we want to add uh the height right else so that we move height I think that students index is either Discord or remove I always forget these things and at every time uh this is over we go um at eight at spot X we check to see what is the highest right so yeah so then now the current highest is you go to a current let's just say current height it's a good SL of the negative one and then if current height is not equal to last height then we increase or we just change the height at this angle so we append the X and then the current height and then last height is equal to current height it's roughly it the autocomplete is actually bothering me a bit to be honest I'd rather do it without it because it just keeps popping up everywhere can I turn it off I mean I get that uh can I change it without uh I get that you could add or complete without it but I think they just turn it on for everybody and then uh like this is actually like worse than not having it for Me Maybe getting used to it oh yeah um oh yeah I guess at the right end oh okay I see so maybe there are two ways you can do it but I guess I would just do it as ADD zero and that should handle the case because basically it's just that there's no items inside that's what I'm handling I think uh okay let's see maybe I must also misunderstood this to be honest um because now it goes to zero maybe I misunderstood just hang on 0 to 2 to 4. um okay I think I have to handle the these things all in order I don't yeah I don't think I'm done yet hang on though it's always a little bit tricky to figure out how to handle the tie breaking cases this one seems good actually there's a Green Dot so but because this one what happens is that it goes from two zero and three at the same time um but I guess we want to do the ones first so let's actually make that even though it's a little bit awkward but okay so we want to add all the numbers first before removing it and I think that should solve our issue so let's give it a quick Summit actually don't I like it when the submit was in the submit thing the submission thing it's a little bit I miss it though at least it doesn't give me a spoiler but once again we have made an issue with uh there is an issue with this I guess we can also sort by High okay let's just say key is equal to Lambda X um yeah maybe I should have tested this actually but so X Sub 0 uh except one and then negative height so that we get the highest height first um I don't know how to add that huh oh okay that's actually pretty cool uh still one though oh huh funny too serious the last question we do the negative height okay hmm I mean I know how to handle it in another way but I thought that I could do something like this I mean I guess the easy way is just to not um the easy way is just to not handle it like this I feel like the other way of doing is way not clean if you ask me but I could do it that way so another way of doing this is by how come my I can't type anymore what the heck I could alt tap this is just a this is a UI thing can I don't know if you could hear it but uh that would I press something by accident I can't edit it oh wait what oh now it what I don't know what happened here but uh Let me refresh the page okay can I now edit it okay bye this the uh apparently some bugs and now I lost my test case but that's okay and I knew what the issue was anyway I thought I could do it without it but I apparently it was a little bit sloppy today how do I just get rid of this oh there we go um I'm trying to talk about it but yeah we can rewrite this as something like so basically we want to pass everything at the same time at the same x value um I wasn't doing it I mean you can actually do the tie breaking in a good way um like something like this times X1 or something like this but that's like really unnecessary or like it just makes it very unreadable so the way we're going to do it is doing something like this instead and then we don't have to worry about um oops I don't like all the auto highlighting all the eye highlighting is making me I can't tell my cursor is half the time that's why I keep on making a lot of mistakes now we don't start anymore by that um yeah and then here what we want is um yes we just rewrite most of this anyway we don't need the last because we still need the last time so then now we do four X in sorted events.keys X in sorted events.keys X in sorted events.keys right and then for th in defense sub X then now we have this thing uh to do and then we add and remove it and then after that we do all this uh I wish I could uh can I take from the past submissions and then like how do I oh there's no whatever button okay fine uh how do I go back to my other thing then this is way uh not gonna lie a little bit confusing to use how to add a case a test case I thought I had another test case was it the same one and it just works for this one though but then I had another case that I had was the wrong answer though this is very weird the UI is really just confusing a little bit I don't know if it's new or like I don't know how much of it is because it's new or whatever but yeah uh okay I mean and as soon as it gets accepted this turns into some crazy monster thing um like I mean the pop-up is fine you like I mean the pop-up is fine you like I mean the pop-up is fine you know so yay congratulations September streakers um if we did this with me but like this turned it like this Ridiculousness which like I don't need to know this per se I guess this is a little bit better maybe I'm just like being that old guy screaming at Clouds but what is this detailed here see detail is exactly just this page but so like the detail does nothing what is a solution like added to the solution list or something no don't care uh okay I mean I like what they're trying to do I'm not gonna lie like I know that I'm the thing is that it's easy to pick up or pick up on stuff that's different and you know and make fun of it or whatever but uh but I'm not like I see what they're going for and I appreciate it I wish they allowed me to turn off autocomplete I think that's mostly the big one the other things I don't you know um yeah uh by the way this is fine I suppose I think there's some like weirdness that I've you know they um they spend enough effort to come out this Improvement I'm sure they'll fix some of these weirdness um and bugs and stuff like this I'm not that worried about it yeah don't need the timer yeah um how much I have so let me know what you think stay good stay healthy oh I didn't go over the complexity did I just kind of went over but yeah this is so I get I got so distracted by the UI today sorry friends but yeah um but this is basically like I said script line basically we sweep all of the X's together and then it just becomes for every event we do all the events together um and then just sort it at the end meaning that um you know we add and we remove and then we get the biggest element I think you can actually put in the set maybe I don't know if that's true um and then if the height changes you put it as part of the answer and that's it um yeah so let's see right so this is going to be end again so that's going to be the lower Bell um at least that's you know the minimum I mean of course everything is going to be sort of as such um and for each of these X which is already X logged then so that and again when it's not again I don't know and again and for each element we will add and remove from this sorted list once so that means that in aggregate that's also going to be n log n so everything is just going to be n log n um of course you require at least additional linear space for the answer or I'll put sensitive if you will um and that's pretty much it uh let me know what you think uh maybe I just set up my screen a little bit because I think it cuts off um on the bottom so you actually don't see my console button and stuff like this it's a little bit awkward but yeah let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
|
The Skyline Problem
|
the-skyline-problem
|
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_.
The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:
* `lefti` is the x coordinate of the left edge of the `ith` building.
* `righti` is the x coordinate of the right edge of the `ith` building.
* `heighti` is the height of the `ith` building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.
The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
**Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`
**Example 1:**
**Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\]
**Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\]
**Explanation:**
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.
**Example 2:**
**Input:** buildings = \[\[0,2,3\],\[2,5,3\]\]
**Output:** \[\[0,3\],\[5,0\]\]
**Constraints:**
* `1 <= buildings.length <= 104`
* `0 <= lefti < righti <= 231 - 1`
* `1 <= heighti <= 231 - 1`
* `buildings` is sorted by `lefti` in non-decreasing order.
| null |
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
|
Hard
|
699
|
922 |
yeahyeah Hi everyone, I'm a programmer. Today I'm going to introduce to you a mathematical problem with pronouns like this: you a mathematical problem with pronouns like this: you a mathematical problem with pronouns like this: arrange a piece by grouping. This is problem number 2 in the series. The article series We Go into the details of the problem as follows, giving us a version A consisting of non-negative integers. Half is half of the numbers non-negative integers. Half is half of the numbers non-negative integers. Half is half of the numbers in a are odd numbers and half of the numbers in a will be is an even number task We need to arrange this table so that the value of A at the final position y is small, then the number is odd, then yy is small is also an odd number A and vice versa if a Because the value of A at the final position small y is an even number then small y is also an even number which means we can return any answer an answer piece that has a requirement and meets this requirement here is us There are many permutations allowed in example one. We have the input piece which is a piece consisting of four non-negative integers 4 2 5 and 7 then we see non-negative integers 4 2 5 and 7 then we see non-negative integers 4 2 5 and 7 then we see we need to arrange these copies to does not require the problem because in position is equal to one. We see that in position Y = 1, y = one. We see that in position Y = 1, y = one. We see that in position Y = 1, y = 1 is an odd number so we need to have an odd number in this position, however in position The current understanding we have is that two has been pointed out as equal to 1 as an even number, similar to what we see, but equal to two is a number y equal to two is an em number and zero however the value At position A, y is the number five, which is an odd number, so the simplest way is to transpose 2 and 5. Let's swap 2 and 5, then we see that we will get the result. The appropriate return result is 452 and 7 y = 0 is an even number 4Y = 1 452 and 7 y = 0 is an even number 4Y = 1 452 and 7 y = 0 is an even number 4Y = 1 is an odd number five y = 2 is an odd number five y = 2 is an odd number five y = 2 is an even number or and y = 3 is an odd number 7 even number or and y = 3 is an odd number 7 even number or and y = 3 is an odd number 7 Next to the conclusion If this return is accepted, we still have three. Another permutation is accepted, we will consider 472 and five also meet the arrangement requirements of problem 25. 4 and 7 are similarly difficult to require arrangement. The question and 2745 are also a guarantee from the question's requirements and are accepted, then after having an example, we understand that once we have grasped the requirements of the question, we will now move on. To solve this problem, I will introduce to you an algorithm that uses two pointers in the filter color. I will have one pointer as the approval pointer. through even indices and a pointer that only browses through odd index periods, these two pointers will each increase by two units. Because the even indices are 2 units apart, each time we work If the pointer is at a zero position, it will look for a zero position that has a number of A at that position, which is a number. Then it stops and the pointer follows the This index looks for values at the This index looks for values at the This index looks for values at the odd position and if there is a standard value, it stops. After those two pointers find two suitable values, it will proceed too together again it swaps the position of A formula y and the bank's own thing I call i and j or I call it the even odd number I ask the place together then I do that until If there's an even number and an odd number, then we'll get to the point. As for the last word of full, I'm confused, this is a pretty simple idea, so I think we'll go into the installation right away. Because it's not It's too complicated for us to take more time to explain. Now I will proceed to install this solver using Vu Lan programming language, first I will declare an even index as y and Z and an odd number Jar Index and then we will assign that starting value to the yellow y until we attach it to otherwise bring ourselves to round one and then we will both have one The for loop says that this pho will approve, wear, and run until economic Y Van is smaller than A is smaller than your length. a Then after that we will start to deal with the part when luck comes first rather than an even number first, then for those with even numbers we will find a value A at position y and the Index that it is It's an odd number, so if at the Y Van Index position it's divisible by two, it makes me infer that I don't need the and black. At this point, I'll give the I love you to this land a new value + 2 and become a new value + 2 and become a new value + 2 and become love I guess I'll run until it finds an odd number then it will go down Let me do it alone I'll change places And if it's an even number then I'll keep going Give it two similar word units for the Open test when they are on the internet if they divide the percentage by two and get the remainder equal to one, meaning for that group, on the contrary it will look for a large even number. But right now it's an odd number because it's divided by grains, so we 'll give it to you. 'll give it to you. 'll give it to you. This Intex is equal to studying Economics I plus two a, then we'll continue until lesson 2 has the value y and That electricity and that stone go down these steps means it has satisfied our requirements that if the number is even then we are keeping the odd number and for the odd number the time is keeping the even number then take the test below. We will do it later We will swap these two places together, then to swap places in golang, we simply need to go this one line and it will swap places. When and neither and either then we will swap it If I see it like that first, then I'll turn it off first and then it'll be a waste of money. Well, let's create a programming language that will help us as it assigns values to both at the same time. This one line will be valid at the same time for the same two for two. Come on, we don't need Wifi to temporarily turn off when we want to change places, then after we finish this loop, our friends. We are one of the permutations that will be accepted, so we will return and then we try to run this girl for example 1. As you say, I have successfully solved the example, a return result is 4527 equivalent to Is it equivalent to the returned result of the problem ? Now we will create an account to solve ? Now we will create an account to solve ? Now we will create an account to solve other examples. Okay. So I have successfully solved all the other examples of the algorithm to understand the complexity of the algorithm. I also see in this problem that we use a filter. If we call N the number of elements of array a from the iterations, we only go N - 2 times. However, we only go N - 2 times. However, we only go N - 2 times. However, we have to shorten n - 2. It's guy n. Well, it turns out that the we have to shorten n - 2. It's guy n. Well, it turns out that the we have to shorten n - 2. It's guy n. Well, it turns out that the complexity of the accounting entries is a complex graph. The storage space is divided somewhere. Because we don't use any more complex data structures to store only the declarations. add a number to a variable number that is a constant ? ? ? A Call the ring by those of you who have watched the video. If you find it interesting, please give me a like, sub, like and share the experience. If you contribute If you have any questions or have a better solution, please write them down in the comments section below the video. Thank you for stopping by and see you again.
|
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 |
1,590 |
with this problem make some divisible by V so you haven't given the array and its sum can be anything can be used by P or cannot be divisible by B but you want to make this array into something uh which have a sum divisible by P so let's say if the array is 3 1 4 2 and P is equal to 6 right and uh currently the sum you can see sum is equal to you can say sum is equal to 10 which is not equal by P why it's not equal p because sum is in the form of 6 K plus 4 10 is 6 K plus 4 now you want to make this divisible by 6 how will you do that one thing is that you know what you need to do you know that you need to remove something like 6K plus 4 from this array uh basically you need to remove a sub array or also like uh and then the sum up that's a variable get removed but how much a very uh how much sum you need to remove in form of sub array 6K plus 4 because if you remove 6 K plus 4 from 6K plus 4 which is current sum will it becomes 0 always like if the K is same then it will be 0 but let's say this is k1 this is K2 so the difference it will get is equal to 6 of K 1 minus K2 which is equal to again 6K so then you know what I'm saying are you getting it so to make this divisible by 6 you need to remove something having a sum of 6 K plus 4. 6 K can be anything K1 K2 uh if this is uh original sum is 6 K 1 plus 4 you need to remove 6 k 2 plus 4 such that the total sum becomes you know what you have to remove in simple terms you have to remove either four removed then it will become 6K you can but it's not like we have to remove only four we can remove 10 also we can remove 16 also which is the total uh you know 10 is the current sum total sum okay and the other case for this problem would have been key total sum under 16. and the 4 is not written Four Keys again 10 is written then you need to return 10 but how will you return because fourth Auto you can directly remove this 4 and then you can say haha in just one uh in just one operation I'll just remove this four and I will have six three one two which is sum equal to six okay good but now you don't have something number like 4 which you can remove you don't have 10 you have 10 in the form of five so you need to remove this sub array now how will you do this uh basically you need to see that okay you got some numbers like this can be anything up till uh for plus 6K and the number can Max be up to let's say 10K power 9 they are saying so it can go up to 10 K power nine one E9 so there are so many range of number which you can delete but obviously not because based on that sum also so you can say like the sum is 16 so you have to go till upper range of that also only so you can remove either four you can remove either 10 you can remove either 16 if the sum was 36 then you can remove something like this plus 4 which is 20 plus 4 which is 24 you know these things you can remove plus 28 plus uh 32 this is what you can or you can remove your complete 36 trigger so these are the possibilities which you can remove from this array correctly the sum is not 36 so let's keep our talks to 16. now what you need to do uh so what I told you that key there can be many possibilities so you cannot check for every possibility then it will take so much time but uh then how would you and how to check the every possibility like how uh we do normal Subaru type of question you can see the sub array every sub array we can see the sum can be seen as like okay is it a basically uh 10 or 16 or something like that you know but then it's not possible to go on every sub array you will take n Square time and to calculate that sum you will take n Cube time and after that checking is not uh much uh and checking is also of end time in this because there you have to check for 10 16 also uh so now how to do this in just one operation you know you have to reduce time complexity but how will you do that so is the logic is you know the logic which he used in the last question is the base for this question to get three one and five and two so if you want to see then you can see the previous question which we did was something like uh let me see in similar question yeah perfectly this was that question I think yeah this was this question sub similar uh Subaru divisible by k um okay so the logic behind this is key when we write a suffix summary you have to create a suffix summary like how we create key some till this point is three some till this point is force until this point is uh and you have to suffix some array but suffix summary also cannot help you because you know some till this point is four and this is nine four plus five is nine plus four is 14 and now you can see this 14 and 4 there's a difference is 10 which means this difference is 10 and you have to remove this you know this pair is such a good appear like 4 and 14 is a good pair because their difference is 10 which you need to remove that can make this Paragon now complete sum is 16 but you know this can't even help you because whatever is good for you like a 14 minus 4 which is 10 is also good for you something somewhere like four is also good for you four minus because zero is also there when there is nothing you know initially there is zero also so this 4 minus 0 is also good for you because this is for this is 10 also word 16 minus 0 is also good for you can remove complete array but then how do you know you cannot even like uh do this again and again so you should have something like the whatever is list written like 16 uh and zero so whatever is written over here should we you know uh like the difference is 16 okay that's good but you know uh if you have to check by calculating basically uh you have to check for every such pair like 14 and 4K and then 16 and 0 K layer and four and zero so let me create a another array which is this if this is a sum array there would be some so that is the okay let me create some space p is basically 60 so 0 minus six nothing three remains four this will become three okay now you get something like okay three but what the suggest key when some model of P array contains the same element this means that this sum is basically a multiple of six which we the logic we used in the last question but now we have to go one step forward so 14 uh divided by 6 is 2 or maybe like this is also useful in this question like the basic thinking as you can see uh you will see uh later so this is 14 and 16 modulus is for as we know that six K plus four so our answer has to be four because this is the X star four which you are having now you need to remove this four ticket how you can remove this uh basically this four you have to remove but now what to look out for in this array you know that 14 and 4 was a good thing for you but for you 14 but the difference is 10 you know difference is 10 was good for you and over here you will see in terms of pair K2 is basically corresponding to four so if you are seeing 2 over here you will check whether 4 is present or not if 4 is at present that means you know it will say that this sum is divisible by you know uh it the sum between this would be 6 K plus 4. so there uh now you just need to look out for six such pair there will be six pairs now you don't need to look out for every possible you know difference like 10 4 16 20 24 this is not you have to just look for the pairs like because 4 and 0 is a good pair right four and zero is a good pair because you can see this 4 over here and the zero over here so the 4 minus 0 was 4 16 minus 0 was 16 which was both the word good but over here we will just look in terms of four basically four minus 0 and so basically we are just reducing us the space from you know uh from checking the so many infinite numbers to taking just six numbers four is paired with zero together it's not like Z 2 is paired with 4 so 4 should be paired with two no 4 will pair out as 0 why this pairing works that you know this two what is this two suggest key the sum up till this point is equal to 6 K plus 2. and what this 4 suggests sum up till this point is equal to 6 of K 1 plus 4 something like that and yeah so the good thing about this now okay when you see this pair suggest you keep the difference between you know these two point will be 6K plus 4 that is the thing foreign is minus two the storm up till here or which is true because 4 is actually kind of a minus two uh four minus two is you know a four sorry six minus two is four so basically minus with respect to modular six okay minus two model six oh that's about it and uh so that's why like this two and four is a good pair because so six K one plus four this is a good fair for this is 2 is good pair with four obviously cancel out okay plus zero so that's why this is a good pair so pairing I got formulas what is given in the question so you don't know that is again like uh I think yeah what is a good pair four plus six minus four which is equal to six model six is equal to zero so four kilograms so in this way we will create uh you know pairing basically we'll check the for good pairs key like uh currently I'm seeing this too okay whether I have seen four in previous or not if I've seen four in previous it means difference SM is equal to accumulate numps dot begin select a nums dot end comma 0 which means the total sum if the sum is division by 6 voltage is equal to 0 then we'll return 0 no need to or sorry I'm doing six we have been given speed okay zero no need to remove anything right now the thing starts now the basic thing starts key and R the total remainder is like this is 4 in this case is equal to S7 modulo P right that's about it and S is equal to zero initial sum I'm starting from 0 if mapping which I need for you know storing this uh this thing's key this things I'm storing in map and like M of 0 is present in minus one position so basically zero Arc has that is also needed because 4K I need okay zero is a good pair for you so you have zero okay so you can remove something but difference minus this equal to Yeah so basically that's what you need to tell the length of the sub array which you need to uh tell so basically 0 present time minus one pay four percent one pay so total difference I is equal to 0 I less than n i plus total sum S Plus equal to hampering in nums of i modulo p now this is the good thing we are not creating s array we are creating a smart P array so this one area we are creating this masary number six is 14 we obviously X model of P or is equal to P minus r modulo is m dot count this exists in the array then what you have to do result M of something like this let's copy this from here I'm off something like the sphere and then we will return result and ncq because if res is equal to not prefer but you can just write a return Aries otherwise we'll return minus one because it means this is impossible you will return minus one like in this case but uh yeah if uh all right so in this case you have to return minus one yeah that's about it anything else you need as you have or yes you have yeah I think that's it is you have now yeah n is not defined encode baby and N is equal to now dot size because the sum can go up till oh wait oh what is the issue now that's model B oh you have not stored M of s is equal to IP we have to store this also that is a obviously very good important thing you are creating this array and then you are checking for previous elements let's start submitting this okay and d0 overflow like at which point exactly or zero LL you have to write this thing now UC result because you know you are accumulating into long dog so this long you have to create okay submit it okay guys that's about it a pretty simple question you should look out in the previous question which you solved that was the basic for this you know some array type of questions casual then like generally yeah in this way we can solve okay guys bye
|
Make Sum Divisible by P
|
make-sum-divisible-by-p
|
Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A **subarray** is defined as a contiguous block of elements in the array.
**Example 1:**
**Input:** nums = \[3,1,4,2\], p = 6
**Output:** 1
**Explanation:** The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray \[4\], and the sum of the remaining elements is 6, which is divisible by 6.
**Example 2:**
**Input:** nums = \[6,3,5,2\], p = 9
**Output:** 2
**Explanation:** We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray \[5,2\], leaving us with \[6,3\] with sum 9.
**Example 3:**
**Input:** nums = \[1,2,3\], p = 3
**Output:** 0
**Explanation:** Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= p <= 109`
| null | null |
Medium
| null |
1,415 |
hello Fenster emigrant talk part the record 14:15 the case is talk part the record 14:15 the case is talk part the record 14:15 the case is like a graphic stream all have strings of length and here her happy string is defined as computer contains only a pc suite nettles and easy torjussen network is not current adjacent so here we have this dream first travel strings this adjacent nettles are a lot of same and yeah only a lot be fetched from ABC so they are happy stream and other cases another hard screen given to individuals and K we need to consider of all the harvesting and find out the case to in well there's a graphic autos so here using example here and you go to work every suite we have and you go wah so we have only three petals there are o had strings so the Swiss mm screen is easy to see for 7.1 examples we cannot get to see for 7.1 examples we cannot get to see for 7.1 examples we cannot get more than three hydrants so we return empathy for sort of a return the see a B because we can get a spell and not in the ninth in C ad and intersexual so seems this problem is that the first idea is that we can to generate her all the hype strings for the names and after that to awaken gathered occasions fresh forms and this is a more direct and straightforward solution because the end is innate constraint you know teaching one to ten which is the very small and K is also 100 and small so this a steel pipe should be able to pass the time should be able the pass the solution it should be the solution pasta without time limiter we can actually secondary we can also optimize this region a little bit hotter altameyer that way - no need to generate altameyer that way - no need to generate altameyer that way - no need to generate also having strings for the legs and we only need to find out the others - in only need to find out the others - in only need to find out the others - in the final orders sliding from Oh close closest point position and we have found that for example here and if I had numbers number equal 1 we can generate too much spin now it is a pp3 right gives you food and you were to can't generate oh maybe you see this C and this JCB if six netters so we have a container weighs 2 times 2 and force never any was three we can generate all these travel letters right so for this formulas we can find that every how oh and that was we can generate a sweetheart through pod and malathion it was and as long as this literally is big and you go to n we can return or valid I've experienced this is the total number of the hemisphere and this is the case room that we need to return and so we assume that for example for N equals week hey when I and I here where we know that they are shelves Vince actually we don't know it was to generate hotels win from the ABC to the end the CPC we only need to start for Ohio causes the previous things we already know it's need is death then k were nice so we do not need to generated since this is pitch start with a and T so we only needed to learn from the sea so this is a way we can optimize the solution appeal so we need to own in your finder the rank of the position that we need was to start so here we have the Bianca warehouse - Annette has have the Bianca warehouse - Annette has have the Bianca warehouse - Annette has ABC we only need to start from this pharmacy over here so we can use a little very cute way to solve this problem in a little bit you know where we need the fan of the rank and this is a partition numbers the part number is over to 2 power n minus 1 there here is if n equals 3 he was she the bit of she's beautiful because we know Karen number is 4 over here and there we found the Bianca is we can use it no okay minus 1 divided by the partition number and infinity to vision and then we could for the decid Owen we need to update his own rank and also the average ok right so when we need to a little care and when encoding resolution Bianca will be updated violently okay so it's creepy carefully updated padam module that is so Vesta the Western Cape and West case spins and my man is a previous release all this six rim so you divide the party and bipartisan number here and then we decrease the em - wah and to him by one he also just go - wah and to him by one he also just go - wah and to him by one he also just go to their situation in this way we can continue to weaken and you to betray the funds of your position as the network we get into the oil without so this regard the core over here and the foster which HECO have the cotton case you for the sweet house 2002 house and man as well Nelson K maybe turn empathy and what you find some the map over here how do we have the if for the initial rectified and empathy you have these three networks for venko and for a that I was awakened only fancy the pianist a for the last little iteration Yenisei and 40 you will have her home and gonna have a see for the city we can only have a pea and way to find a kinder and Cha Neto that is where you said it's kind of a start from empathy and again answer experience for in the photo in two months and we can put it into an mr. foster because it will save a space for this operation to add in tatters and then we can transfer to the final screen uses a chore and join operations for the screen because if we your screen Pasi ho every time we do we create a new space it is time consuming and also spaceless cousin consuming so again check you need you to give it away Kuwait Little Italy's and firstly we get the perigee number you see party number we have this number and we can the counterion coming we need to fetch the number here face your character unless the character should be families and we get oh this is bianca is cynical for the first time before the K equals 3 and equals 3 k equal 9 we have this Bianca equal to and ways so I can lounge highs empathy and we angry to so we can let us see here we put it into the answer list and then we update the current networks with this kind of the C networks because of all the time we see we can only need 2 a and B and of this 2n and also updated ok Sims is a since to finish it our way also to update the final if the energy for the nu hotel today do we still have the last stone the last one is not at an editor so you have two editor over here and we returned their answer oh I didn't define the renkel here so it's not really encourage these are all it should be Peter the K is already a reality so they should be the last one K minus one over here okay this is your north flow way to not help flow here what is flow 29 and oh this should be single tell Susan over here no sing stream synthesis snores the flow oh yeah this is something is wrong here oh this will be our flow is young with flow hood / the Gestapo flow hood / the Gestapo flow hood / the Gestapo but catalyst to make it eats and indeed you okay mr. books okay we made it
|
The k-th Lexicographical String of All Happy Strings of Length n
|
students-and-examinations
|
A **happy string** is a string that:
* consists only of letters of the set `['a', 'b', 'c']`.
* `s[i] != s[i + 1]` for all values of `i` from `1` to `s.length - 1` (string is 1-indexed).
For example, strings **"abc ", "ac ", "b "** and **"abcbabcbcb "** are all happy strings and strings **"aa ", "baa "** and **"ababbc "** are not happy strings.
Given two integers `n` and `k`, consider a list of all happy strings of length `n` sorted in lexicographical order.
Return _the kth string_ of this list or return an **empty string** if there are less than `k` happy strings of length `n`.
**Example 1:**
**Input:** n = 1, k = 3
**Output:** "c "
**Explanation:** The list \[ "a ", "b ", "c "\] contains all happy strings of length 1. The third string is "c ".
**Example 2:**
**Input:** n = 1, k = 4
**Output:** " "
**Explanation:** There are only 3 happy strings of length 1.
**Example 3:**
**Input:** n = 3, k = 9
**Output:** "cab "
**Explanation:** There are 12 different happy string of length 3 \[ "aba ", "abc ", "aca ", "acb ", "bab ", "bac ", "bca ", "bcb ", "cab ", "cac ", "cba ", "cbc "\]. You will find the 9th string = "cab "
**Constraints:**
* `1 <= n <= 10`
* `1 <= k <= 100`
| null |
Database
|
Easy
| null |
961 |
hey what's going on guys it's ilya bella here i recording stuff on youtube share the description for all my information i do all little problems uh make sure you subscribe to the channel give me a big thumbs up to support it and this is called and repeated element in size 2 n array an array uh a of size 2n draw n plus 1 unique elements and exactly one of these elements is repeated n times return the element repeated n times for example we got this input right here and we return three to n is equal to four n is two uh here to n is equal to six and this three we return to uh the length that array is greater than or equal to four and is less than or equal to ten thousands um the value at i into that a is greater than or equal to zero and is less than ten thousands uh the length of that array is even and go ahead all you need is uh find the first repeating volume first repeating digits to do that you create a an array of the type integer which has the length of ten thousand you could notice from the description of this problem right here um next you create for loop and you're looking through this a at each iteration you check in the case when uh the value at a is equal to one then you return a uh also you need uh increment uh the value at this position into that count every time you see a right so at this position at the position of a you increment the value by one and return this a otherwise return to minus one that's pretty much it let's run this code accept it good let's submit success well um so you know just uh for example got this uh array right here right so um we got count a bunch of zeros uh up to ten thousand then uh indices like zero one two three four five and so on uh we are looking through this a through this array and increment at i into that count by one we got one right here then we are at two um we increment by one again right uh is not equal to one then we are here at three we increment by one as well and the time when we are here we can see that at three we got already one so we return this three that's it thank you guys for watching leave your comments below everyone know what you think follow me on social medias on instagram add me on snapchat um give me big thumbs up to support my channel and i'll see you next time have a good day bye
|
N-Repeated Element in Size 2N Array
|
long-pressed-name
|
You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times.
| null |
Two Pointers,String
|
Easy
| null |
1,026 |
Hello hello everyone welcome to my channel it's all the problem maximum difference between noida and sister for giving the root of binary tree for india maximum very form which day and different note se ease with difference between noida and noida sector 9 we no differences of mother and Child of child in the system will clean this is not hidden in the air subscribe Video then subscribe to the Page Computer Processing 2009 What is the left minimum and maximum do quartz beating a different well known will take water maximum from minimum to maximum so let's find out Minimum Left Value for Money Not Benefit and Left for Similarly in Right Way According to Light of the Summary of This Electrolyte Most Loud Values Which Can Electrolyte Most Loud Values Which Can Electrolyte Most Loud Values Which Can Compute The Idea Maximum Bill Increase Letter Value Synod Value - Terminal Letter Value Synod Value - Terminal Letter Value Synod Value - Terminal Minimum of the Referee Jeff Sid Stop This and Maximum Vishal for Players Like Value - Maximum of Life Immediate Repair from Right Some - Maximum of Life Immediate Repair from Right Some - Maximum of Life Immediate Repair from Right Some Value - Minar Value - Minar Value - Minar Ki Andy Similarly Value - Ill 600 for Ki Andy Similarly Value - Ill 600 for Ki Andy Similarly Value - Ill 600 for Fears and need to get the maximum of all the For everyone keeping noble maximum be revalued and they will update with this value and Will keep updating it for starting from root note to all the notes and give verdict throughout the festivals and tried to update so go life * Find any minimum and maximum life * Find any minimum and maximum life * Find any minimum and maximum valley of the Nodi factory sweetly process all notes in this life and similarly all days Noida Night Safari And Have To Repent For Every Nook And Every Time From Its Left And Right Factory So What Will Happen And Detend For Android Exactly Endtimes Method Both Minimum And Maximum Value Swadesh Villain Wrist Algorithm Will Go To The CEO Of Square Within Every Soul Possessions But I don't code first decide approach is a to here is the code favorite and don't show is used to help by method like maximum of the sub screen and minimum of this is pain decision like it is that has not been written in case of maximum Minimum balance in case of maximum blood minimum increase maximum value and will have three condition sweetly compare exactly maximum donkey rude value all the maximum from the left leg in android upper similarly in the case of minimum swadeshi 2328 minimum maximum this is the value result B. Sc computer this is the first value the value and subscribe president and * result nvr calling left president and * result nvr calling left president and * result nvr calling left glue factory life in the defense for left and right also with that will go to date of all the notes and tried to cover for this will give real answer But time complexity of dissolution like this will run open and have fun activities were running off and tidy this maximum and minimum balance from left to right poetry on how they can raise problem let's understand more details here in this note I know this minimum value from the System and Maximum Volume Minimum and Maximum Ilu Delivery K 9 We Will Do This Minimum The From the Meaning of Swahili of the Problem Minimum - Not Swahili of the Problem Minimum - Not Swahili of the Problem Minimum - Not Willing and the Maximum - New Delhi New Willing and the Maximum - New Delhi New Willing and the Maximum - New Delhi - To Meet a Maximum of Distic Delhi - To Meet a Maximum of Distic Delhi - To Meet a Maximum of Distic 100 Problem basically choose do similarity specifically checking validating and host Shastri and not show in but also be used in human maximum value and compare is not 12th it lies between the minimum and maximum when such same approach Idea Reviews Here initially will start from root node And Minimum Maximum Value Special No Point of Truth Know Your Soul Will Start The Daily From This Minimum And Maximum Volume Sort Value Easy Minimum And Value Time Love For Initializing Our Requirement Started Every Time They Will Update Result From Maximum Do That No One Seems To Have A will have to update dip current minimum and maximum volume between the current node and deprivation minimum balance to have been passed so current minimum will be updated s chief minimum of the current minimum itself that and current not value water lehru das vaishnav or processing this current Note Beneficial Similarly For Maximum Volume Maximum Best Value Time For Every Note Specified Comes To 800 In Hair Oil Subsidy Minimum And Maximum Many 238 383 Minimum And Maximum Exam Fear Maximum Difference Will Get You Anywhere In Right Side Minimum And Maximum 800th Urs Shy Send That minimum and maximum value from top to bottom all different and where taking maximum and Sudesh shift video and tried to dance of its very straightforward first decide this line tear use minimum and maximum balance so let's complete quotes for implementation will define the global result Will Hold Over All The Best Rudolph You Will Come To Know Why Not Tree 999 Nor Will First Touch His Student That Nal Sonveer Will Not President What Will U Will Update Result From The Current Result And Departments From Not Person Date Sheet Of Node Value - Current And Take No Of Node Value - Current And Take No Of Node Value - Current And Take No 300 Truck Drawing Copy Of Badmash From Big Max Service And Values From Both Of Max Service And Values From Both Of Max Service And Values From Both Of Value And Current Result Will Take Over All Maximum Solar Maximum Subha System Hair 9 We Need To Update Avat Current Minimum Subha Can Update Current Minimum Hairs Ko Konimese Minimum Vikram Math dot mean of do minimum itself and different not value similarly they will update current maximum value current maximum h.no they will update current maximum value current maximum h.no that and e cannot believe they updated absolutely slow left and right child in this also not left and not right a i safe this is sample Implementation of Dissolution Problems Left Side To Compile And Back Website Is Compile And Other Is The Type Of Baroda Se Jor Lighting Half Benefits Current Minimum And Maximum Thursday Subscribe To Tomorrow Morning Time Is Compile And Were Getting The Correct Answer No Way Can Submit Fancy That Ritesh Accept Subha Solution Is Like Basically Similar To Checking Mein Dharaya Everyone Nazariyaan Notification Reduce Shoulder Problem In This Problem You Can So Vishal Important Meeting Sometime To Find Solutions Private & Admin No Solutions Private & Admin No Solutions Private & Admin No Comments Section How You Feel Android Problem Is Swell Kiss Bst Soft Thank You For watching
|
Maximum Difference Between Node and Ancestor
|
string-without-aaa-or-bbb
|
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105`
| null |
String,Greedy
|
Medium
| null |
1,697 |
hey everybody this is Larry this is day 29 of the leeco daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem uh let me also check for the extra points okay no extra coins um and also uh there'll be the premium problem later so definitely hit the Subscribe button and also just click on that video I guess to watch it uh okay so today's problem is 16.97 uh okay so today's problem is 16.97 uh okay so today's problem is 16.97 checking existence of edge length limited paths I'm gonna sneeze real quick or half season so I don't know what I'm doing but uh man allergies this entire month has been kicking my butt I'm still half sneezed but uh oh you know it's the worst uh but yeah okay let's take a look what does this actually mean an undirected graph of analysis divided by edgeless okay so you have UV and distance uh and an edge between UV and distance note that there may be multiple edges between two nodes okay giving away queries where queries of J is equal to p q and limit what is p and q's whether there's a path between p and Q such that okay so it's brilliant okay I mean I think um I think I looked at uh um a similar problem the other day um but it was online right and what I mean by online is that you actually have to answer the query and the answer to solution to that one is I'm very funky and I didn't really get around implementing it because I was lazy uh because it required LCA and binary lifting and if those things don't mean anything to you that's fine because it is ridiculous to learn to be honest if you ask me for about like pretty much anybody unless you're like doing really like if you're good at everything else that we talk about on this channel then maybe you know look into it but uh by the way I was saying binary lifting and stuff like this is just a ridiculous solution or the minimum spanning tree or something like this but in any case for this one uh so that's set yeah that said that the other the actual live version of this with queries is absolutely ridiculous uh but this particular problem though is tractable but it's also a little bit weird in the sense that you have to take advantage of the fact that you have a list of queries but you don't have to answer them in real time and what I mean by that is that not only you don't have to answer them in real time you don't have to answer them in order right I mean of course maybe you have to you know for the actual answer you have to put them you know corresponding to the order of the query but you don't actually have to solve them in uh in you know uh per query itself and what I mean by that is that um you know you don't have to solve the first query and then the second queries and then the third query and so forth you could do it in reverse order if you like you could do a jumping order anytime you like um so okay so with all that said this one I would say has a prerequisite of Union fine or destroying set Union TSU yeah um so I would look up DSU Union fine and stuff like this so this is uh and maybe even um not maybe but it uh minimum spanning tree yeah minimum uh maybe minimum spending Choice family tree uh or just spending trees in general maybe um because this is a connectivity problem right so you don't really need the minimum part of it um though this may resemble the way that we're going to solve it is we are going to resemble uh Cusco I think is it I always forget oh no yeah I think it's Costco right because I always confuse or not I don't confuse but I just don't know well I guess I am confused then uh which one is Cusco and which one is poem uh almost said Prime the prim's uh spanning dragon they're both greedy in essence so uh yeah it's definitely these are things that kind of look into um there are probably and well not probably most certainly easier problems are need code to um to work on these skills so that you can get into it um I'm not gonna you know I Define these things as prerequisite because I don't want to spend that much time getting into these things at least for today um not gonna lie it is Friday here uh on the 29th uh this is day 29 but April 28th and in 2022 uh is it 22 what year is this 23 jeez oh man I lost a year apparently in front of you guys but what I mean is that there's a the Warriors game is coming on soon the NBA so uh so I gotta go watch it afterwards um definitely uh let me know if you're watching the NBA let me know in the comments which team you're rooting for uh and why is it the Warriors anyway um so yeah I'm not gonna go over DSU uh it's you know like if you take an algo course in college or whatever it's probably like um like a two-week class maybe or two or like a two-week class maybe or two or like a two-week class maybe or two not two weeks but like two lecture class or something like this depending how deeply they go into it um there's ideas that I'm gonna use but I don't want to go over like from zero to one because that's a little bit too much within the scope of this uh video um but yeah so assuming you know where it is and um and I think people or a lot of people if you know if you're into the competitive scene a lot of people do have templates for this but I am gonna do this template list and I generally do uh but maybe not I generally do things templateless because that's the point for me uh though lately I've been I have a DSU template just because I don't know people are getting way fast and I need to catch up a little bit I at least don't contest I mean uh definitely if you're doing it to practice for interviews at the end of the day you have to be able to do it right uh okay so let's set up um so the way that I think about DSU in general is basically a rooted tree right so you have these notes so in the beginning you have a forest of notes and then as you kind of combine them you could you're kind of combine the trees such that they um such that they point at each other and then the root of that tree is the representative of that tree right and then there's something like path compression and uh Union by Rank and all these things I'm not gonna get into all the proofs and stuff uh but I'm gonna just assume that they're all of one for the purpose of the huge inverse Acumen function if you really want to get into it I know that you know uh no that is fine I'm just lazy today right um so yeah so basically here the way that I'm saying is that for each forest for each tree in the forest itself is the root representative route and then I have two functions uh the union fine which is for fine um and yeah we just um yeah if parents of X is not X then parents of X is equal to you find parents of X otherwise return pounds of X right so this basically this is saying this is almost like a memorization I write it this way it's a little bit confusing we haven't seen it before but the idea is that okay so is this the representative note right meaning if you have a union find tree it's just a top note on the pass uh in the tree um if it is not then get the parent right oh actually yeah and then get the parent you cannot in Philly you would actually write something like if you really want to do it that way you do something like find a parent so that you can kind of get to the root of the tree right but the thing that I the reason why I write it like this is that it kind of is memorization in that okay we recursively find the pattern of the tree um so that you go up the tree to find the root of the tree but then we save it down so that if half compression right I mean um I if I'm doing more in depth of this maybe I'll draw a thing so that you can kind of see how it really edges but I'm not going to because like I said this is a prerequisite but this is I'm just going over why I do this right um just very briefly it is a Friday night so you don't have a little fun right so here we're trying to um merge two trees so UA as you go you know we find the root of uh a we find the root of B and then we just set parents of UA as your UB you um there is a couple of things that I do here that I'm just lazy about um and that um basically you could if you are able to visualize two independent trees in the forest you could just look at the root of one of the nodes now pointing to the root of the other node so that everything in that sub uh that is the children of that original tree uh will eventually if you fall up it will now point at UB right so that's basically the idea um you can actually the way that I actually um depending on the problem but I am often very lazy because it doesn't provide too much uh benefit is that I don't do uh merch by rank or merch by size merch by you know some function right um uh it's just not usually necessary but maybe I'm wrong and maybe one day I'm gonna like get bit by that but I just kind of you know it doesn't really matter uh given random inputs but sometimes uh if you are given specific input it uh adversarially um then perhaps you can have a degenerate case but there is this you know path compression so in theory things get compressed in a very good way okay so now all that is just to set up the union fine and then now what do we do right I didn't even go with the problem that much to be honest uh that's why I don't want to spend too much time on Union fine but the way we do it is that now let's disconnect the entire graph right it would just contact the entire gravel and nodes and then for each Edge we kind of put them back into the tree one at a time and in the order of um the distance right because then now you could kind of think about it as a graph that slowly builds itself up from small edges and at the end of constructing or a lot of things then we're able to answer queries in a very good way right meaning that for example if we have a query that has a limit of say 20 another way to phrase it is process all the edges that are less than 20 right and then after that all we have to do is sort it in order so that order um all the defense are processed and then interleaving kind of way such that the invarian um is true where when you process a query the current tree will be um good enough I guess or like it causes all the edges that are smaller uh within distance Edge or that are smaller than the limit right okay uh okay yeah okay so let's do that uh let's see right so for you we uh D in Edge list right so the way that I always do it is have an adjacency list but we in this case we actually don't want or we don't need a specific adjacency list uh what we want is actually process these edges in order so um and there are a couple of ways you can do this you can just have it put it in an array and then sort by that array with the you know sorry by distance the way that I am doing it this time is actually having a bucket and then sorting that bucket so that you can process everything at the same time and I'll show you how what I mean by us in a second right so maybe I have something like edges it's Z go to collections dot default if I just fail correctly uh of a list and then now edges of D append UV right and of course this is bi-directional so I believe so this is bi-directional so I believe so this is bi-directional so I believe so yeah it should be so yeah I could just do it this way right um and then we also want to do the same with queries um and you don't really need to do what I'm doing per se but uh that just for symmetry Reasons I'm gonna do it this way so for PQ limit in queries Qs of L um dot append PQ right oh and we also actually as we said because we're basically destroying the um uh with destroying the ordering of the queries but we have to return it in some order so we need the index here so then here it doesn't matter where we put it but now we can proceed in order and you can actually in theory merge to these two lists but I don't know it's probably fine either way uh yeah so then maybe I'm gonna do this a little bit lazily but maybe I have qs.keys plus bit lazily but maybe I have qs.keys plus bit lazily but maybe I have qs.keys plus edges dot keys and the key in this case of course is the D and the distance and the limit together right so then now let's have a sorted version of this and then now for I call it X because I don't know I always think about things as a sweep line in the sense and because there's a sweep line I just call it X because you go from left to right so you have all these events that are happening and then you have all these things right sort of so the thing that um I'm looking for now is just double checking and when I'm double checking is that it is asking for strictly less than right so um given that it is strictly less than we that means that we have to process the queries first given the same X right so then here we go if maybe if length of Qs of X is greater than zero that means that we have a query then for p q index in q s of x uh we entered or we also need an answer I think I guess uh I think it's just none times n and I like using done instead of like true or false as a standard value as I'm debugging maybe if I submit I would change this but I have it as none so that if I don't set something I don't fool myself that I set that index for you know like um yeah so here we have to process these right so then now it should be more straightforward right if you find a p is equal to U find of q that means that they have to both they have the same root and if they have the same root damage that they're in the same um Union fine tree uh and as a result that means that they're connected so that means that we can and answer of index is equal to true but of course then and if otherwise you set the force which of course is just this um uh this conditional right okay and then now we process the actual um edges as well so edges of X is greater than zero the reason why I wrote it write it like this is because um there may be a limit that doesn't exist an edge and so and vice versa um and this maybe I don't even need to write it like this but it yeah it's fine I think uh and here of course you want to oops uh you want to connect these two things and that's how you do it and that's pretty much it really and then at the end this return answer and this should be good uh okay so apparently you can do it on those things that's fine I just have to convert them to lists I think maybe that's a fair thing I don't know because I think these are like uh like you can't swap them or whatever they're called I forget what they call it uh did I mess this up oh this is an N this is Q where Q is the number of queries obviously um oh still well hmm I do them in the world I write true so zero and one is two output truth but I write Force that's weird right let me double check something real quick you should get this pretty right uh okay huh did I um limit is fine okay yeah huh let me see what's happening here just debugging not none so two so I set the same index twice why is that so two it sets it to Fours which is correct but then at four we don't have a query yet for hmm did I mess this up uh it may be that I just messed it up but that's fine like why is this twice showing up oh I see I'm being a little bit silly I think um the reason is because this is not unique yeah okay so I just have to come up with this to this set yeah I'm not gonna lie usually I don't write it this way so that's probably why because it's not unique it processed the same uh it process this thing twice and that's why right all right let's give it a summit hopefully I don't have any more silly hours and yep there we go 11 24 day streak so what's the complexity here right as I said um for the purpose of this video um let's just say that these are all of one and you know uh for the purpose of this uh for each element right um this is O of N and the number of edges of the year if you will this is of Q uh and this is all of n log n or you log in plus uh yeah you like e plus uh a q like Q just for the Sorting otherwise everything is linear so yeah so this ultimately is going to be o of uh let's say n log n plus q log Q time and O of n plus Q space right for both the thing and this is the door of Q space because that's the answer you can really avoid it um that's all I have for this one that's all I have for today let me know what you think um stay good stay healthy took a mental health I'll see y'all later and take care bye
|
Checking Existence of Edge Length Limited Paths
|
strings-differ-by-one-character
|
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes.
|
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
|
Hash Table,String,Rolling Hash,Hash Function
|
Medium
|
2256
|
127 |
hello everyone welcome to day twenty fourth of july code challenge and today's question is word lighter two and even before starting the question i would like to apologize i was a little late as i was busy with my some personal work i just reached home back in the evening and now i'm there in front of the laptop solving this question for you guys the question is a very famous interview problem word ladder 2 and we have solved a similar kind of question in the past named word ladder one consider word letter one as a prerequisite for word ladder too if you have solved that question you'll be able to come up with this approach in 70 of the cases so without much ado let's look at the presentation that i have created for this and i'll be attaching the video of that previous session that i did in january's lead code challenge going further in this video itself so don't worry you don't have to hop to that video moving on to the presentation word ladder 2 lead code 126 hard question and let's try and understand both the questions word ladder one and word ladder two and let's try and draw inferences from word ladder one to word ladder two in this question we are given a begin word an end word and list of words and what we can do we can move from one word to another and that will count as one translation only if they differ by one particular character in both these words for example hot and dog differ only by a single character so you can move from hot to dog and will count it as one transformation we need to return the number of words in the shortest transformation sequence from the begin word to the end word if no such sequence exists we need to return 0 in that case let's try and look at this particular example the shortest transformation would be from starting from hit going up till cog and how many hops will you take you will have to take minimum of five hop five hops and how that will be from hit you will move to hot one transformation from hot you'll move to dog from dog you'll move to sorry from hot you'll move to dot from dot you'll move to dog t differs and g differs in both these words it's just one single character and then from dog you can move to cog d and c differ by only a single character so this is what the transformation sequence is like this is what word ladder one states let's talk about word ladder two and since now you have calculated the minimum number of hops required to transform the input word to the end word the begin word to the end word you need to return all such possible transformation let's try and understand the possible transformations for this data set only and as we know a minimum of five hops are required from hit you move to hot from hot you move to dot from dot you move to dog from dog you move to cork again from what you move to hit you move to hot from hot you move to lot from lot to move to log from log e move to cog this also count as 5 transformation this also counts as 5 transformation so both of them are valid and we need to return all such possible transformations that are there with respect to this word list that is given to us in this question you are given a dictionary and a beginning word and the end word and some rules and the rule says that two words are related if they differ by archmax one character so what you need to do in this question you need to return the length of the shortest transformation that is possible uh starting from the begin word till end word and as in each transformation you can apply the rules that stated that two words are related if they differ by at least one character at max one character so let's walk through one of the example uh you need to start with hit and you need to check whether you need uh whether you can reach cog or not using the word list which is acting as a dictionary in this case how can you reach uh from hit till cog uh this is the explanation given here hit uh from hit to you go to hot from hot to go to dot from dot hero to dog and from dog you go to cog how many transactions did we do for reaching uh the end word five transactions one two three four five so actually we did one two three four transactions and uh we actually did four transactions but the total number of words that came in between were five so transaction plus one gives you the answer also uh if it is not possible to reach uh the terminal state uh return zero in those cases this is a negative case that is being discussed in this example without much ado let's look at the slideshow that i have created and let me just start the slideshow this is a typical graph problem uh if you are not aware of graphs don't worry i'll explain how we can do uh how can we build graphs and the second part would be how can we traverse the graphs uh in this question uh what will you build we will build an undirected unweighted graph what is an undirected graph means uh with a node points a and b nodes are connected with each other there is no specific direction for example this one is a directed one a points to b or b points to a so there's a particular direction uh in which uh the tree in which the graph flows in an undirected graph there is no particular direction you can either move from a to b or from b to a what is unweighted there is no weight a sign on this edge that means it's an unweighted graph and i have taken exactly the same uh example that was specified in the question so as to help you understand better i will also discuss why we'll go for the bfs reversal or the dfs reversal whichever is so moving to the next slide now uh and let's talk about how are we going to build graph uh we will need to define a helper method which tells us uh whether a string is related to another string or not so we'll pass a string will pass the string a and string b two strings to a helper method and it will return a boolean telling us whether these are related or not what is the relation between these two strings uh that they differ at max by one character and let's build the graph the semantics of the graph would be something like this the first one is the input string which tells us how many strings are related to this string the second value is how many strings are related uh to the string the key string and this would be the value where uh whatever the strings are listed in the value part these are related to uh the key string uh let's talk and take an example uh hit and hot uh these are related and they differ by one character oh hot dot and lot so this is again a list of strings dot and lot dot differed by dot hot dog and lot they have three words in this part and so on so let's break the problem into two parts as i told we'll build a helper method that accepts two string and checks if they if the two string differ batman's one character pretty simple and i think everyone would be able to write this code and how are we going to build the map will iterate uh over all the elements using two loops and order of n square complexity and we'll pass for each possibility we'll invoke the helper method and we'll uh will build the graph using the response of those helper meters for what for n into m string for all the strings and let's talk about the traversal part y will go for the ba first and not the dfs one so in general for undirected uh graphs uh bfs reversal in this case would give us the answer and no and dfs would be time consuming let's take an example here suppose this is the what we do in a dfs reversal we traverse over depth and if from hit you may reach cog in 10 transactions if you are the one part could be this the other part could be a smaller one which is uh which occurs at a depth of five so in dfs reversal what you will be doing is you will be reaching cog and then you will be storing that information in the variable and you'll light return through all the paths that are present in this graph in a depth dfs fashion and if you find a better value then you will replace it with the minimum value if not you will continue moving in that uh traversing the graph one issue with this would be uh since you are uh moving in depth first you will be reaching you will be going by one path instead of uh touching all the boundaries touching all the nodes that are nearest to the root uh that will that is the case with the bfs reversal because in bfs reversal we cover edges that are at the same position at the same time so we go in a breadth-wise fashion we go in a breadth-wise fashion we go in a breadth-wise fashion so think of this example the diagram as a bfs one so whatever nodes are at a distance one will we'll consider them first so you don't need to think of the minimum one part because minimum will be automatically taken care of by the bfs reversal so if length is one here or distance is one this distance is two all the nodes uh at a distance two will be traversed at the same time and for this the distance would be three at any point if you can see you can find your terminal node you break that condition that will be the minimum answer while this is not true with the dfs reversal let's move ahead uh how are we going to do the bfs reversal in this case we'll start with an initial word hit add it into the queue and we have built this graph by the algorithm that i specified before uh and let's move ahead uh we added hit and this is our end word we pull out the element from the uh queue and um since it is not equal to end word we will uh add all its children that are present in our map into the uh cube so this is what we searched for uh hort's children and we'll add it all them all of them in uh in the queue so if element is not uh not the end word which i stated push all its children in the queue if they have not been visited in the past also you need to take care what all children have been visited in the past so that you don't keep on adding elements again and again once all the elements have been pushed mark that note as visited let me just explain the visited concept here if a is connected with b and so that means there could be a case where you are adding pulling out a and adding b is children again from b still then you are adding a again so that generates a cycle kind of a thing we break the cycle using the visited concept so let's move ahead in the traversal so we pulled out hit we added hot and we marked hit as visited gets marked as this and level gets incremented to one and we pull out hot now uh since hot is not equal to cog uh what we'll do will add all its children uh into the queue so let's add all its children dot and uh lord gets added into the queue and this tells us the termination of level two and this is domination of level one so let's move ahead in the traversal what gets added into the visited array level increments by two this is the terminal state for level two and uh since dot we pull out dot and dot is not equal to uh the end word will add all its children into the queue uh only those children that are not part of the visited array since hot is part of the diary will not add that uh we'll add dog and lot so the dog and lot will go here so dog and lot gets here and we just popped out to this also let's move ahead in the next iteration we get lot so lot has hot and dot are already part of the visited array so we'll ignore them and move ahead we'll ignore them and so next we have a dog in the attic and we pull out a dog from the queue we have log and cog as his children will add them in the queue because none of them is visited and we will move ahead with the iteration the blue line signifies the end of level three so we pulled out dog and we added dog in the visited area because it has been marked let me just take a highlighter here and let's move ahead with the uh next lot iteration lot has hotend dot lot hot and dot are already part of the visited i said we'll ignore it and next we have uh this tells us the termination of level three and next in queue is log we go to log and we see that uh it's still in a dog and cog we pull out a log from it and add cog to it so let's move on to the next iteration uh level is four so far uh cog we pulled out caught and turns out to be equal to the n terminal word we found the terminal word and we return level plus one other answer because i told about transaction plus one gives us the accurate answer uh and hence a level act as the number of transactions that we have done from the root of the graph root being the start word in this case so let's quickly code this up all the elements that are given in our dictionary board so we will add set or define a new set new hash set and what we are going to do we will add all the elements in the hashtag that present in the list so for integer pl in word list we'll add it in set dot add here and now let's define the helper method that tells us whether two strings are related or not so the return type of this helper method would be boolean and let's name a strings differ by one so we have string a and we have string b and let's just check whether the length of these strings are equal or not uh if a dot length is uh not equal to b dot length if they have unequal length then return false otherwise let's continue with the a check uh let's define a boolean variable uh found one difference and initialize it to false for integer i equals to zero since both of them have the same length you can take any of the length or the that of a or b and let's pull out character of what character vertical from eighth character from a string a and similarly let's pull out the b8 character from string b is character from string b and let's check if a car equals to b if they are unequal then let's update found one difference to true also before the check uh let's we need to check whether we have found uh whether found one difference is already true or not that means it's a second difference if that is the case return false otherwise will return true so this is one of the helper method that tells us whether two string to provide at max one character and let's define the map so map is of string comma list of strings new hash map and let's build the graph let's define a helper method build a graph and what we'll pass the map into to the graph and our set data set also we need to add the begin word to the data set because from the begin word uh we need to gen we need to build that graph not the terminal word so say dot add begin word if it is there in the word list it's fine if it is not then you have to start our iteration from beginner hence we have added into our dictionary or the data set up for word list and let's build a graph so building graph is also pretty simple exercise avoid the return type is void build graph and what are the two parameters that is accepting one is a string a map another one is a set of strings sorry it has to be strings word set and let's build it for integer i equals to zero what we can do we can iterate over this the word set array word set and a string and another for loop a string let's call inert yell what's it again so we are iterating over uh the string the array twice using uh order transfer time complexity and let's check if i el dot equals inner el or not if they are equal just continue otherwise let's build the graph because that means it is the same element how are we going to build it we will check whether they differ by a string difference by one or not then we have el and in a real pass to it if that is true then let's add the elements into the graph so let's get whatever is being stored map dot get or default yield from a new adder list and this will be a list of strings that are that means connections and connections dot add in a el pretty simple and let's just put this information back in the map connections so what we have done uh we have built the graph we pulled out the information from the map what all connections already existed and added the new connection to this and put back the same information back into the map so since this means that el is connected to in a real and similarly what we need to do we need to establish the connection between inner el so i'll repeat the same process connections for inner el and this time i'll uh the key would be in a real and we'll be adding el to it the element to it and in el would be the key again and this would be connections to uh you connections what in real and this is how we have built the graph and we are successful and let's uh generally define another set which is of strings again which tells us what all elements have been visited so within it is very important hash set for strings and this is let's define the queue we have standard way of writing the vfs reversal queue new link list and q dot offer from which word are we starting begin word we are starting to pick it mode and while q is not empty let's calculate the size q dot size and while size minus is greater than zero will pull out the head element q dot pull out the hell element and if we check if head equals to uh the end word if that is the case we'll return level plus one so let's define variable level and return level plus one that's good and let's check if visited what contains head if it contains it just continue right with the iteration otherwise if it doesn't contains head so that means it is an unvisited element will add all its children into the string while it's returning all its connections let's call it connection map.get or default map.get or default map.get or default what is the key head is the key and what is the default list add a list and let's check if visited contain does not contain connection if that connection is not built in visited array we'll add it in the visited q dot offer visited and let's mark since all the chil all its connections have been added we'll mark the head as visited dot add thread and once we are done with this logic we'll check if visited dot contains end word if that contains end word we'll return level otherwise will return three simple way of checking if it has uh the end word then we return the level if it doesn't have the inward built on zero that means it's not present also i forgot to increment the level so i incremented level head fingers crossed it's kind of a verbose code compilation error again some typo sorry for that oh sorry it has to be connection instead of visited absolutely correct and let me just submit this code accepted this time the solution got accepted and uh let's talk about the time complexity of a graft reversal problem is order of n square slash order of v plus c which is number of vertices edges and uh also you are building a graph in order of n square complexity hence it is order of n the worst case would be order of n square the space complexity would be again order of v plus c are the number of vertices plus edges thanks for watching the video i hope you liked the word ladder solution and now let's talk about word number two solution we'll be using the same bfs approach and we'll exactly follow the same concept that we use there with the slight modification i'm talking about the modifications here since we need to traverse the complete path and store it somewhere so every node will store its previous node from which it is coming for example from hit you move to lit let's assume so lit will store the identity that it is coming from hit that's it so that we can create the complete path in the end as soon as we reach the terminal end node the second concept that i want to share here is let's assume we have a large list of words that matches with hit and we need to keep on iterating across these words till the time uh you don't actually reach a conclusion whether a path is possible or not what could be the other way of generating all the possibilities so one could be you replace the first character with all the characters starting from a to z and generate new words for example a i t b i t c i t d i t c i t and you check if these words are part of your input list if they are then that means one hop is possible and you need to take the updated word into consideration it's not the other way out we are not using or the complete data set to check what would be the next move rather we are using the current element at which we are presently and we are generating all possibilities from this element and then checking it whether that element the updated element is present in our data set or not this will be beneficial in optimizing time complexity for those cases where we have huge number of input data so what all permutations would be there for hit first of all you'll update h by any character starting from a to z then you'll update i with every character starting from a to z and then you will update t starting from every character from a to z so let me just write those a to z followed by i t and then h a to z followed by t and the third possibility is h i a to z so what would the time complexity for these generation 26 into length of the input word that is under consideration order of line so as you can see that we have reduced the complexity to order of length for generation of the next move rather than iterating over the complete data set just keep a note of this point and at times this approach is very beneficial let me just move on to the coding section where i'll show how i'll use these two properties to optimize the solution the first thing that i have done is to define a private class node and it has two attributes in it one is the string value that the current node holds and the other one the previous node from which we are actually coming from i have defined two constructors one with only string value the current value of the node other with the previous node passed in the constructor now let's look at the algorithm is pretty straightforward guys not much of complexity there so i've defined a list of strings that will help us store the answer the second line in the second line i have sanitized the input data set so as to remove any duplication in the input word list followed by this i have defined a queue of type node equals to new linked list pretty standard process i have added the initial word the begin word to my queue and i am iterating over the queue in a bfs fashion as i do in every bfs question i calculate the size till the time size is starting from 0 up till i less than size i could have instead of the for loop i could have written the other way out size minus as well which i usually do i don't know why i followed this going further i have pulled out the top most element on the queue i check what all possibilities are possible with respect to the current list that i have starting from the pulled out element from the key from this string what all nodes are possible uh that are there in the input list and i'll get that string value neighbor string or the name adjoining string i've defined a new node because this is a new possibility that is generated and i have passed in two parameters to the constructor the upcoming or the next uh string and head will serve as the previous link for the current node if the current neighbor value the current node value uh is equal to the end word that means i found my answer and i need to get out of this loop this for loop and check for other possibilities otherwise i keep on adding the new neighbor into my cube if my result.size has become if my result.size has become if my result.size has become greater than zero that means i need to break the process because at this particular level i have found out one possible answer and please remember that the first level at which you find out uh the possibility for the begin word till the end word after performing the transformations all such possibilities will be added in the same on the same level not at a different level so you have to come up with the solution where uh shortest transformation sequences are being counted starting from the begin word to the end word that is why as soon as the data gets filled in into my answer set i have to abort the process so that the longer ones can be ignored in the end i simply return the answer set now the question reduces to two of the helper methods that i have created one is for generating all the possible neighbors with the current data set that i have starting from a string value that i have passed here head dot value let's look at this method so this is an input data list or the data set and this is the current string which is under consideration i remove the current string from the data set since it's already under consideration i've defined a new hash set and i have converted the input data string into a character array i generate all the possibilities starting from a to z and replacing each character one by one generating new words i checked if my list contains the new word then i add it to my data set the updated data set and in the end i return this set of integers where the set of strings where all the neighbors with respect to the current string are returned which was expected from this method let's talk about the add node method what needs to be done where we have found out our answer or the terminal state in this method we need to build our answer set starting from the terminal node and going back in the reverse direction so that we can have one possibility stored in our result so how will we do that this is a terminal node which we have encountered and we'll add it till the time the speed dot p is not equal to null and with every iteration we'll go back p is equal to p dot previous the previous node that we encountered in the ladder the in the complete ladder also we will add it in the first place so we i have explicitly used linked list here so that i can use the adverse method it will add it at the first index in your answer set that as well and you simply return the result starting from the terminal load and going up the ladder i hope you enjoyed today's session if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and see you tomorrow with another fresh question from coding decoded for july elite code challenge guys congratulations we are just five days away from winning the title another batch coming your way good night
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
9 |
hello all welcome to another video solution by code runner in this video we will be looking at the palindrome number problem on lead code and this video will provide you with the c plus solution of this problem i have also made a video for the python solution of this problem and if you are more comfortable with python then you can go ahead and find that video linked in the description box also i request you to please subscribe to my channel to get the latest updates about exciting problems and their solution so without wasting any time let's proceed to this problem in the problem we are given an integer input and we have to determine whether the number is a palindrome or not the definition of palindrome is that it reads the same backwards and as it reads forwards also we are not supposed to convert the integer to a string and then check the palindrome to understand the problem better let's check out the first input example the input here is one two one if you see the reverse of this number we still get one two one therefore the output of the function is true because one two one is a palindrome in the next input example we have the input s minus one two one this is not a palindrome because minus one two one when reversed reads as one to one minus thus the output is false in this case now having understood the problem let's proceed to the c plus code to solve this problem as we just saw in the second input example a negative number can't ever be a palindrome number thus if the input is a negative integer we return false then we check the next condition if the number is non-zero and it is if the number is non-zero and it is if the number is non-zero and it is divisible by 10 then this number also can never be a palindrome consider the examples 10 20 30 to understand this better note that here we exclude the number 0 because 0 is a palindrome and it is divisible by 10 as well having checked these two conditions let's proceed to the next part where we'll reverse the second half of the original number and then check if the reverse second half is same as the first half or not if the reverse second half is same as the first half of the number then the number will be a palindrome otherwise it won't be a palindrome we start a while loop and only run it as long as the input number x remains greater than the reverse number this while loop and the two code statements inside it will help us accumulate the numbers from the end of the number x and push them to the variable reverse to understand this better consider the example commented here the input x is 5225 initially the value of reverse is zero in the first iteration of the while loop we get the value of reverse as five and x becomes five two in the next iteration we get reverse as fifty-two and x fifty-two and x fifty-two and x also becomes fifty-two there won't be also becomes fifty-two there won't be also becomes fifty-two there won't be any further iterations as the value of x and reverse are now same we come out of the while loop and check if the value of reverse is same as x or not if the value is same then the original number x was a palindrome and hence we returned true one important point to note here is that this statement will only handle the even length polynomic numbers the case for odd length palindromes would have to be handled separately and is done in the next if condition to understand this better consider the example of five two five this number is a palindrome and is also an odd length number after all the while loop iterations are done on 5 to 5 we'll get the value of reverse as 52 and x as 5. here as the length is odd the center digit of the number does not matter at all to us thus we just check the condition without taking the center number and if the condition is satisfied we return true if none of the if conditions were true we return false and declare that the input number was not a palindrome that is it great job and we are done with the solution let's try to run it and see if it works or not and there you go the solution has been accepted i hope you liked the solution if you did then please hit the like button and press the bell icon to stay updated about the latest problems and their solution on lead code bye for now happy coding and i'll see you next time with another exciting problem and it's solution
|
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,170 |
yeahyeah Hi everyone, I'm a programmer. Today I'll introduce to you a proportional problem like this: you a proportional problem like this: you a proportional problem like this: Compare strings by the number of times the smallest element appears. The detailed problem sequence is as follows. We will define a callback function called function f with input parameter s&s which is a string input parameter s&s which is a string input parameter s&s which is a string without empty spaces. We will calculate the number of occurrences of the smallest character. In the place F, let's drop the edge to have the function of calculating the number of occurrences of the smallest element in S and then give an example: if in S and then give an example: if in S and then give an example: if we have S which is a string consisting of the characters dc e then we will have the force of this s to be equal to two because its smallest letter is the smallest letter C, which means that if we arrange by alphabet in English, this letter C will stand first. Before the letter e, I consider it the smallest and the number of times it appears in this place is two times, so we return the value of F which is 2. Now the two give us a sign a piece of letter string consisting of two pieces, Array of query array and piece of keyword, then we will return a strong number of inches named answer, provided that the answer is in position intellectual y then will be the number of words that the then is the number of words that it escapes from this condition this control is many things That is the que who the query sentence is in the Yth position After Ky and Mep it has a smaller return value than the word w in the stack of keywords in the keyword tables that transmits and edges inHa when people note that w9 is one of the words of the keyword revolution, then which word If it meets these conditions, I will increase the result variable in this answer by one unit and now I will go into example one to better understand the problem for Vi Dau Mot, we have the piece The query includes an element called cbd in the keyword fragment, then we have an element called Z AF, then we see that if we calculate the compression for the first elements of the Phi query fragment, it will is one because we have the smallest element P a&b that appears once a&b that appears once a&b that appears once from similarly if we calculate the value of function f for this first query word AAA Z sandals then we will have the value is 3 because the smallest character element is A and that appears 3 times so we see that 1 will be less than 3 and here there is also only 1 word and 1 keyword and one query so Surely it's just a comparison of these two values, so we have a return result of one. Okay, let's go to the new case or here we have more suitcase queries, more children, more queries and also If there are more keywords, then our query has two queries: bb&cc, the function has two queries: bb&cc, the function has two queries: bb&cc, the function f for bb is 3 and the edge for CC is two, then the keywords we have function F are respectively a A1 and the other two words. a 3 divided by 4k is divided into two edges, respectively 1, 2, 3 and 4 bu sida tree jaw tree which word has any keyword that has the flagship f a I have someone forcing it to be bigger than three then there is only one. a is only 4 words. The function f is 40, which is greater than three. Consider the first position, we will have an answer with a keyword, then through the second positions we have the function f, then two. I have to find this side, which edge is bigger or is it allowed to be large or is there two guys and three letters ai? With 4 answers, I will return the result here and there are two rabbit keywords if they have a request then Consider that I have passed the requirements of the problem. Now I will move on to the algorithmic thinking part for this problem. First, the first task I have to do is to find out the function f. Hey, this function f is really quite simple. I will have a piece of 26 English characters, then I will browse this string from the beginning to the end of the string. Each time we browse, we will increase the counter variable. At the position of these yth characters up one unit after we have just obtained, we have the number of times the number of occurrences of all the characters is always given a piece and then the piece This is an arranged piece. Because we will save these characters in the order that starting from the smallest one, we will always be in the Yen Bai position, if not the smallest one, we will always be in the Yen Bai position. 1st favorite Ecu gradually increases, which infers that this piece has been arranged so we just need to review this piece from beginning to end and we consider which element appears first, which intek appears first and has a higher index. Otherwise, we will return those numbers to the F ships. Okay. That's it for the F ships. Now, after we have the chest, forced us to calculate the motorbike taxi in turn. What will we have to calculate in turn? We will calculate the F of this suitcase in turn. After we have the f value of the function of each Wireless, then We will apply a mathematical spinalis function so that we can search all of them. Well, if we actually calculate the query tree, we also have to calculate the compression for the keyword. This is the keyword. We have a list of a keyword, then there will be an application of an edge, then return a number, then consider that now the keyword we become is a one a piece consisting of The integers contain all the return values of the press's return. Then return values of the press's return. Then return values of the press's return. Then we sort this keyword list in ascending order. We will find the f value of these queries in The keyword table uses the polyscias algorithm, which means I do a binary search. After I find the largest elements, the first largest element, I start to get the length of this keyword. I - given this keyword. I - given this keyword. I - given those values again, I will get the result that those values again, I will get the result that those values again, I will get the result that those larger than it will definitely also radiate. So I subtract the largest value from the length of the number of molecules, then I will get the result. The results of the program are at the official position, so if I were to explain more in this fake way, it would be quite long because the installation of this program is also quite long so I will start the installation right away. It's easier for you to understand if you're a little confused, I'll take out a pen and paper so I can do it. I'll cut it down into groups and now I'll proceed with the installation using the Vu Lan programming language, so first I'll Declare a variable for my strawberry Minzy's head now it will make a piece in A and its length will be equal to the length of the suitcase, right? How many sticks do you have? I have to answer Give it how many numbers you want to touch and come back later . And now I will start first, . And now I will start first, . And now I will start first, I will install the f function first. Then I will call it and force it to look like the program requested. passing in is forcing this, it's passing in forcing is the type of string that returns a number. The number above is the number that appears on the date of the appearance of the word of the smallest character in the place s. Now I will declare a number. a Temporary glass, let's call it temporary, it will make a piece of 26 characters with the printed ratio and then I will go through the treatment of this f function by cursing using S's keyword and then Then I will try to put this radiator at the position C - then I want to at the position C - then I want to at the position C - then I want to get the index of A, I want you to have someone as small as zero, the index of B = 1, you to have someone as small as zero, the index of B = 1, you to have someone as small as zero, the index of B = 1, then I will subtract it to calculate the value. Its upper bound is the very above saying who it will be. Here I go + + then who it will be. Here I go + + then who it will be. Here I go + + then after I finish this filter line I will have this piece that stores all the number of occurrences of all All the molecules are already arranged. Now I just need to go from left to right to the number of this heart function and I'll see if there's anyone else and it's different. Yes, I'll return to the something. And if we run out and can't find anything, then we'll end up with nothing, but this case won't happen because we know what the article says is that this is never the same thing. One is an active one. Well, this morning I will realize the Ha that Bella Resort The Binary Search for a little more but just call me to use it again, the Paris product is quite popular everyone. Everyone has to know by heart the truth: know by heart the truth: know by heart the truth: first there is a string, a piece, a strong interior integer, then there is a target, the one I hate that I will return are its indices. Now I will initialize 22 variables to run as y&j, I will give it to you for free, then to run as y&j, I will give it to you for free, then to run as y&j, I will give it to you for free, then one will run from the last element, one will do y, I will take care of it, but if there is nothing left, I will send a message to the last element. Next, I will have a loop. Set it up until y is smaller or equal to whatever, then I will continue to run. First, I will attach a sticker to find the Idol insurance microphone. It will = y + J divided by 2 and then Idol insurance microphone. It will = y + J divided by 2 and then Idol insurance microphone. It will = y + J divided by 2 and then if But I'm using this microphone to say something smaller or equal to the tales. Now I figure out what I have to do. I have to reduce the gain by using mic + 1. It's gain by using mic + 1. It's gain by using mic + 1. It's the hand that I'm using. Now it has the ability. Just lie on the right side and then kill it, but in the opposite case, what should I give you? Mix - 1 means the thing you? Mix - 1 means the thing you? Mix - 1 means the thing I hate is now only capable of being located on the left side of the jackfruit. Ok, that's it. called the one Oh the Yes Then the point is in the middle and after we get the result will be j but what is this thing that I want but I don't have to pay you? For example, it's located at the position In the first position, I want to return the number 1, but I want to return the number 0, so I will return what is plus one. Then that's it, I'm done with two important rows for what to solve. This algorithm is this algorithm. Now I'm going to start by declaring one more thing. There's one more here. One more piece so I can save something to roll the Washi pants. That means the number of quality times. is the compression tunnel for all the elements of this keyword string. Okay, then I will start installing and declaring that it is a printed piece whose length is equal to the length of this fan, which is correct. Because no matter how many fans I have, I'll have to wait until the afternoon where I work and now I'll be in Hanoi approving gifts. I'm sad to overcome the piece of word. Well, when I'm approving, whatever I do, I'll just call it out. word frequency at the y position, it will be equal to the f function. Everything goes into the Word and this data. After we have this single fan, remember that this error constraint will be passed on to Nobita. Let me find out what I hate is the gap in the edge of the suitcase so we need to arrange it, but when we want to use Paris, we have to arrange it. Well then we will arrange it with the Ham Yen dot skull object. then this is a built-in function in the a built-in function in the a built-in function in the golan programming language and now we will move on to the piece we want to arrange and see when calcium is finished, we will do an important loop. The most important part of that program is the loop and we will have to go through this suitcase or we have to destroy the welle and then every time we build this suitcase, we just have to find the largest element. The first biggest market I come across, I will find by calling the fan resort function, I will pass in something that will pass it into the Word version bacteria and frequency and I will have to pass it to find what I have to find the value of Esri's f function. I'm almost done. Now I have its largest element. For example, in school, let me find the guy C. If it goes there, its pressure is two, right? In this fragment, why will the keyword fragment, it will turn into a fragment of the bacterial family 1234, then it will find the number 2 right at the position If this is the case, it will return to me a clean bibury function that returns to me the number two, then now I know that these arrays are four, then I just need to get four, I don't know, my friend, there are four elements. Is that right? Hey, the position two from the truck is ok. I will take it as four Chinese characters but there are two a. Well, now this two is the one I will put in for the strawberry. What should I give you after Monday ? will be equal to the length of ? will be equal to the length of ? will be equal to the length of the word string, it's fine to handle the plan - for fine to handle the plan - for fine to handle the plan - for the first hot bad girl like that's it. It 's a bit long because I have to 's a bit long because I have to 's a bit long because I have to install kanjis and also when typing f and Try running the program, I have an error here. I'm missing the thread A key. I hope there's nothing more to say. I say that and I've finished solving the example. My return result is One is exactly according to the requirements of the problem. I'll try it now. I'm sure there will be another example. Yes. I've successfully solved all the remaining examples. Now let's analyze a bit about the complexity of these algorithms. So for this thing, I find it quite complicated because analyzing its complexity because first we create this first color function and it runs after If I call m now I call N the length of Well I and M the length of the keyword, then this is a delay loop of all the keywords, then it has a complexity of em and this is a basket, the complexity is n m rock me and this is running out of the welle then it will be a date so and the songs ne resort blooms in half ha Paris let you be the time m not the time m but this whirlwind is very dim It's really that bad I'm afraid that according to this word, it 's correct like tornado m. Or N, first 's correct like tornado m. Or N, first 's correct like tornado m. Or N, first add me lock me and then add me furnace multiplied by Rock m, then this is the exact meaning of your complex head. Our problem now is that the storage space is quite complicated. Because in the resort we will have to use n a using welle now has the length of Carina so how complicated is it ? This keyword has a complexity ? This keyword has a complexity ? This keyword has a complexity of M times, yes, that's it. I'll just use a few more, then its complexity is me + m me + m me + m there is the complexity of the archive citizen, let me check. Check again, do you still use anything complicated? I'll sit down and that's it. Okay, I'll end it when it lasts. Thank you all for watching. If you find it interesting, please give me a like and sub. Like and share the scriptures. If you have any comments or questions, please write them in the comments below the video. Thank you all. Goodbye and see you again.
|
Compare Strings by Frequency of the Smallest Character
|
shortest-common-supersequence
|
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`.
Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\]
**Output:** \[1\]
**Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz ").
**Example 2:**
**Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** \[1,2\]
**Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc ").
**Constraints:**
* `1 <= queries.length <= 2000`
* `1 <= words.length <= 2000`
* `1 <= queries[i].length, words[i].length <= 10`
* `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
|
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
|
String,Dynamic Programming
|
Hard
|
1250
|
136 |
hi everybody welcome to my channel let's solve the lead code problem one three six single number it is a like very common problem in interviews so let's use the problem statement and under to understand the example so given a non-empty array of integers every non-empty array of integers every non-empty array of integers every element appears twice except for one find that single one so far as it is given array and every element occurs two twice while the one element is once and we have to find that element and your algorithm should be linear and time complexity and could be implement without using extra memory so we should not is extra body so in example one we have three elements where two occurs twice and one occurs once so one is the answer of this example in example two we have five elements where four is once one is twice and two is twice occurs so four is the answer so first if we think on the simple like very first brute-force approach it is sort the brute-force approach it is sort the brute-force approach it is sort the array if we sort the array using the invented sorting functions or the merge sort or quick short those are in like done in n log n time complexity without using extra space so that time complexity of that guru for solution is will be n log n so one we can do with let me write down here by sorting so this will be o of n log N and the space complexity is o of one so but we have to implement the linear solution so let's optimize the solution and in that second case let's optimize our running time complexity so if we want to achieve in oh of n time complexity what we can do we can user one storage which is let us say hash map and we will keep insert the value numbers in the hash map if it is not already exist if it is exist then we can remove that element itself so this can be achieving o of N and I space complexity but space complexity is also here o of n but we have to do in a constant space so how can we so let's think about the binary operations like bitwise operation so let me explain you few binary operation so how bitwise jawed is work so let's I have a number X which is let's say 4 and if we represent its binary representation that will be 1 0 and I have another number by which is let say 2 and if I represent it in the binary representation of 3 bit 0 1 0 if I do the X Y or by bitwise jaw then I will get so bitwise or of if it is the same bit to 0 both of the same with 0 and if it is both are opposite bits though then it will give 1 so 1 0 so we will get this 1 0 and this is a binary representation of oh 6 so we got 6 so this is a how bitwise job' work 6 so this is a how bitwise job' work 6 so this is a how bitwise job' work let's try the bitwise or of X Y or X itself and see what will get we will get if we do so every bits of the bitwise of both is same so we will always get the 0 so if we - if we do the bitwise your of so if we - if we do the bitwise your of so if we - if we do the bitwise your of the same number we will get 0 so how we will use this approach in our problem as we know every number is exist twice and the number one is at like one of the number is at this one so if we do the bitwise jaws of the twice numbers we alway catch the 0 and let's try another thing what will we get if we do bitwise jar of X bit 0 so here we are doing bitwise you're of 1 0 bitwise your bit 0 so here we will always get the same ax if we do the bitwise or of X with a 0 we will always get X so this is approach we will use to solve this problem so let's write down the code so let me take a variable jar which will we start from the 0 because if we do jar with 0 we always get the number and then we will run the integer num in numbs and simply we will do the jar of ax width bitwise jar of x width num so whatever will get in the end we will get this single number so return the jar so let me go back through this code in the example given here first example so 2 1 so the example here exam how it will work so example 1 we have our in arrayed 2 1 so if we do the bitwise jar of this sky - and this sky if we do the this sky - and this sky if we do the this sky - and this sky if we do the bitwise your then we will get 0 and after 0 we will do bitwise your with 1 so this 2 number we did the bitwise your here and then we do the bitwise your then again we will get D 1 so this is our answer so let's try to compile our code so I miss the semicolon here so it's a mistake but here we are getting correct answer let's submit our code and see it is accepted so the time complexity of this solution using the bitwise your using the third solution which is time complexity is o of N and in a row of one basically constants which as we use the drawer valuable thank you if you like my solution please hit the like button and subscribe to my channel for the feature upcoming videos
|
Single Number
|
single-number
|
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,1\]
**Output:** 1
**Example 2:**
**Input:** nums = \[4,1,2,1,2\]
**Output:** 4
**Example 3:**
**Input:** nums = \[1\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
| null |
Array,Bit Manipulation
|
Easy
|
137,260,268,287,389
|
961 |
hey everybody this is larry this is me doing the uh a bonus question for august 6 2022. um i'm trying to still complete uh oh what the why oh this is frequency i did um yeah i'm trying to do one that i haven't done before and i pick it randomly uh today's problem earlier problem was poor pigs and it was poor me it took a while i hope you did it a little bit better but uh yeah let's get uh let's take a look hopefully it's not premium okay this is a easy one so hopefully so it's a little bit better uh let's see n repeated elements in size two and array so basically what does that mean you're given an entryway numbers two times n plus one elements one element is uh repeated n times returned element okay so basically um this is phrased in a really weird way but uh but it is the election algorithm right uh what's it called void is it fight for its majority algorithm i just want to get my name right uh no that's not right who's uh something famous a boilermore okay yeah so i guess the thing that you're looking for is boiler more majority algorithm i forgot the name i mean i knew the uh the majority algorithm i forgot who did it so that's my fault but definitely read up on this that's probably the way to go um you could put it's almost like a pigeonhole type thing of principle on the proof but because you know like these problems people got you know phd and research papers and their names on these algorithms so i'm not going to be able to get this in a couple of minutes uh with all the proofs and if you are interested in that get um do that um that said i only googled the name so i actually don't remember the algorithm so that or you know it's not an algorithm that comes up that often to be honest uh maybe like once in a blue moon or in my case even less than that so let's see if i'm able to kind of derive it from first principle and the idea here is that how do i even describe or think about the idea here is that you're given you just basically keep track of the element and then you count up um you count up if you see the same thing if not you count down and if it's below i want to say if it's below zero you take the new element instead and there's some like um like we draw the trajectory of this uh the path of this it'll always be the element that is uh in the majority and some of this is just i believe i think i call it pigeonhole i don't know if it's quite the out the idea but it's just that otherwise um yeah i mean the cup i mean of course you can also sort given that n is five thousand if you sort it you know um it'll probably be you know you just need a number that's uh the same in this case and that'll be good and you could also do an n square but why would you right um yeah and you got to maybe do uh i want to say do a quick select maybe that's another way as well um because if you choose the or like i guess given two times n it can be uh because if you um because if you do a quick select and you do the median right if you do a quick select click select that's also a linear time of h f um because then the element is either the middle element or like for n where n is even is either n over two um so it's one of those two elements right so um like n over two or n over two plus one uh maybe you do it three times if you want to get n over two minus one and you know the element will be guaranteed that will show up in two of those but i'm not gonna do it that way i'm just gonna do the ball more i think this the baltimore is right though we'll see and in this case because one element is repeated n times and you know that we said you only you don't even need the majority point now that i think about it you only need an animal that's repeated twice so do i think the baltimore even lets you do that i think so yeah um is that true um maybe not maybe baltimore only goes up to n over two plus one due to picture now but i think maybe if it's um because actually in this case voldemort may not actually run properly because yeah it would just yeah i guess it does assume maybe i could think about another way though right so if it's n over two okay yeah i mean so this is something that i just derived from the majority algorithm and that the majority algorithm won't work here we'll give you a five but that means that this is the only scenario where it won't give you the five but that also means that obviously there's one case which is that if the if two adjacent numbers are the same then you could repeat or you could return it otherwise it's the number plus n over two right and because you know because of the pigeonhole principle another version of it um it has to you know um this has to happen either two numbers are next to each other are the same or two numbers skipping one number you should be the same so i think that should be good and once we have that foundation down oops it is easy to write um though this isn't quite that uh not quite this but we derive from this basically the only case where so baltimore when it when you um the observation is also that um if an if a number is repeated twice then that's good that's from one more because then now you weren't able to go you know down enough um and this is the only case where it doesn't work and in this case by doing the math it has to be n uh or i plus two so yeah so we just have to try it here um if uh num sub i is equal to numbers of i minus 1 or i plus 1 whoops i plus 1 is less than n and this return num sub i otherwise you know you do the same but for numbers over 2 number plus 2 i plus 2 yikes uh yeah and then here we maybe assert force or something wait for an exception i'm lazy so this is gonna have to do um yeah so let's give a quick submit i haven't done it before hopefully this is good and i didn't forget a case oh no i guess this is this the only case with i guess the other cases if there's two numbers but has to be more than two numbers um i guess maybe uh okay i forgot the end equals four case so i tried to be a little bit too clever here perhaps because there are also i would also say that if this was a contest definitely sorting it and then i don't even think i would make all these observations i would just sort it and then do a collections that um uh i guess i don't even need to sort it i would just put everything in a bucket uh in a collection side counter um or like a hash table and then just count it that way but here i am trying to do something clever um is this the only case where this is the because okay i mean we can obviously add a thing for this but i thought that this was true but i was wrong uh but this is the only case though because now um if you think about every two pairs of numbers this is it and now if you add like another nine for example there's just no way to you know be two away um so this is the only scenario and i messed up uh okay well i think this should do it hopefully let's give a quick summit okay yeah um wow how am i slower uh huh um not quite happy that i made this mistake i guess that's the one edge case where my thing was wrong because i was kind of visualizing bigger numbers in my head oh well anyway this is of and time or one space that's all i have for this one it is easy even though i made a easy mistake so but also like i said if i was doing it for a contest definitely would have done it another way just because you know correctness is better than these optimizations and yeah anyway that's all i have for today let me know what you think stay good stay healthy to good mental health i'll see you later then take care bye
|
N-Repeated Element in Size 2N Array
|
long-pressed-name
|
You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times.
| null |
Two Pointers,String
|
Easy
| null |
124 |
welcome back to algojs today's question is leak code 124 binary tree maximum path sum so a path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them a node can only appear in the sequence at most once note that the path does not need to pass through the root the path sum of a path is the sum of the nodes values in the path given the root of a binary tree return the maximum path sum of any non-empty the maximum path sum of any non-empty the maximum path sum of any non-empty path so in example one we have this binary tree the output is six because the maximum power of sum is one plus two plus three in example two we have this binary tree the output is 42 where we have the maximum power of sum equaling this subtree right here 15 plus 20 plus seven okay so there's a lot to consider with this question we're going to be using dfs so we need to keep track of the maximum path so we'll just call it max for now and what we're going to do is constantly update this so we're going to initially going to set our maximum to zero so let's run through this binary tree and see what we need to return so we're going to do a depth first search approach and we're going to traverse the left and the right before visiting the root so let's do that so let's go down to the left we reach this null value down here okay so nine's pointing to null when we reach an old value we can return zero we need to return an integer in this case because our actual output is going to be an integer so we have a base case and that is if the node we're on is equal to null just return zero so we're going to return zero here because we've gone down the left side the right side and then we visit the root okay so it's going to be a post order traversal we reach this nine the current max at this point is going to be the left side plus the root value plus the right side so this is the current max so zero plus nine plus zero is that greater than our max of zero yes it is so we can update that now what we need to pass up from this side is going to be the maximum between the left value and the right value plus the root value now the reason we do this is because we cannot take both of these subtrees so this left side and this right side we cannot include both of those in this path right this path here is a valid path and this path right here is developed half but including both of them is not valid so we need to return up the root value plus the maximum between left or right so in this case it's just zero so we're going to return up 9. now we need to go down the left side or the right side here but go down the left so we reach this null value again we're going to return up 0 go down the right return up to 0. now here's the sticking point we have a negative value here so our current value at this minute or our current max is zero plus minus two plus zero so that's minus two right so is that greater than this max here no so we can keep the maximum at nine now what do we return up from here because if we return up minus two whatever we add that to is going to be decreasing the overall max which is something we don't want so in this case we need to return up zero so now we're at 20 current max is well let's go down the right side this is going to be connected to a null that's going to return up zero the current max is zero plus 20 for the zero which is going to be 20 so we can update the max and then we return up 20. we go down the right side we return up zero here we have a current max of 20 plus 15 plus zero so that's 35 so we can update the maximum so we have 35 as our maximum at this moment in time now what we turn return up from here is the root value plus the maximum between left and right so that's going to be 20 plus 15 which is 35. then we traverse the right tree and then the left so we reach null here turn up zero current max is zero plus seven plus zero so that's not greater than 35 so we return up seven plus the maximum so that's going to be seven now we have a current max of 35 plus 20 plus seven which is equal to 55 plus 7 which is equal to 62. so that's greater than 35 so we can update to the max now we return up the root value plus the maximum between left and right so that's going to be 35 plus 20 so we return up 55. now at this level we have the root value of 10 plus 9 plus 55 which is equal to 74 so we can update the max again and because we've reached the root we have nowhere else to look so we return this value here so the complexity analysis for this question time is going to be on where n is the number of nodes since we visit each node no more than twice and then space is going to be of h where h is the height of the tree so let's code this out so we need the max variable which will initially set to negative infinity i said in the explanation it should be zero but actually it should be negative infinity just to account for any values less than zero okay so let's create the function we'll call it dfs i'm going to pass in root when we call it we'll pass in root and we also need to return max at the end of this so as we said in the explanation if root is undefined we can return zero so if we reach an old value we just return up an integer then we need to do the post order traversal so left right then root so let's get to the left which is equal to dfs root dot left let's do the same for right but on the right side so dfs root dot right and then we can get the current max so current max is going to be equal to left plus root.val plus right root.val plus right root.val plus right so this is where we're getting the total of the subtree now the issue is at this moment in time we haven't accounted for negative values and the way we do that is by using math.max and comparing the left side with zero and returning whichever value is greatest and we can do the same for the right zero dfsroot.right zero dfsroot.right zero dfsroot.right this way we're always going to be returning a positive value so we're never going to be decreasing the overall maximum half sum then we can update the max so i'll equal maximum between current max and finally what we need to return up the tree is root.val plus the maximum is root.val plus the maximum is root.val plus the maximum between left and right okay let's give that a go and there you have it
|
Binary Tree Maximum Path Sum
|
binary-tree-maximum-path-sum
|
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root.
The **path sum** of a path is the sum of the node's values in the path.
Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 6
**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
**Example 2:**
**Input:** root = \[-10,9,20,null,null,15,7\]
**Output:** 42
**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-1000 <= Node.val <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Hard
|
112,129,666,687,1492
|
882 |
hey everybody this is larry this is me going over day 12 of the september eco day challenge hit the like button here to subscribe for enjoyment discord smash order whatever buttons uh anyway today's problem is reach above know it's in subtitle so i usually solve these live so if it's a little bit slow you know skip ahead or watch it on more faster speed my point to these videos and i get these questions every once in a while and people are like hey you know you can make these videos better by doing this i'm like no this is the point is that i want to have a different video i don't want to make the same video that everyone else is making which is just explaining the solution there are no videos for those google those instead you know we live in 2020 what year is this 2021 uh yeah you can google you can search on youtube you can find other videos that's fine i'm not going to hold it against you but my thing is that i'm going to give you my thought process and my thought process is me you know seeing the problem the first time and kind of you know step by step even the ways that i sell the problem incorrectly or you know yeah a lot of weird things so that um yeah anyway okay i hope that made makes sense so yeah please take that end of consideration anyway tony's problem is reachable notes in subdivided graph okay let's see what does this mean you have an undirected graph okay yeah and notes okay your chain of notes with the number of new loads what does that even mean wow it's like these notes have babies or something okay the graph is given deceptive by uv replace it with count sub edges how many nodes are reachable from zero and you're given max moves okay this is very awkward hmm but let's see i mean this is a way i don't think that i mean i was gonna say i haven't i don't think i've seen this particular problem but this is just a very awkward problems right i mean it's a graph problem obviously but yeah okay so you're just going from zero to okay and in this case maximum for six so you one two three four five and then one two three by six okay hmm i mean i think it's still just going to be some sort of distress algorithm why did i say dijkstra dice true um because basically you're just doing the cost except for each of the frontier uh i don't know that's the term but the frontier edge uh notes um on the frontier notes you do like a little bit more math on how far you can go in between the edges okay so this is uh i wanted to confirm certain things so this is an undirected graph which means that yeah i mean i think there are also a couple more um scenarios meaning that for example let me pull up paint real quick but still i think it's going to be diction maybe i think dijkstra gets us a lot of the way there are more weird cases that we might have to consider and we'll cross that path when we get there i suppose let's see so let's say this is my thing and what i mean by that is that okay you have a note here and you have a note here um you know and you have the you have this thing and you have this thing right so then let's just say that we can get here and then now you have all these other smaller sub notes that are like you know uh that are here and let's just say max move cuts us off in like some you know so one is that for max moves we're good on this one and everything in between let's say we already did the math on that so then that means that we can take say i don't know some subset of this right and what i mean by that is for example this means that you know let's just say maximum can do this and then this max move can do this thing right and of course in this case you have to be careful about how you do the math um so that you don't double count you know these notes in the middle and i think that's basically the idea but behind what we have to do but otherwise i think it's just dijkstra yeah i think it's just dice shrimp we have to figure out how to be very careful and there's even more than that i think now that i think about it so maybe it's not that's true let me think about it for a second but i want to draw again the visualization i was thinking about is that you know and you know we did this and that's okay and one reason why i don't know if it's nicer now is that because you can still have extra edges and even this may be good say um and this could be good like that just say that these are also good you know these are also good um but you know let's just say you add an extra edge and it's this one to this one oops one color but same okay let's see this one for this one and you have some you know you have some notes in the middle well you have to consider some subset of these two so i think we have to be really careful i mean it might still be dijkstra but i think we have to be very careful about how we want to do it um so yeah okay let me think about it for a second okay so the number of edges is going to be uh 10 to the fourth is that a thousand no that's ten thousand so ten thousand edges so we only have ten thousand edges we have to consider we can also maybe is n is three thousand okay so three thousand ten thousand i was going to say i was thinking of um what is that uh vg algorithm we times we are i forgot the people's names but basically it's the shortest path one where you do for each vertex times for each vertex we relax order all the edges and then you do that three times um or yi times maybe and then that should be good um but yeah but that would be too slow in this case so yeah i'm writing out the name right now but leave that in the comments if you know because like i said i'm doing this live but okay um i'm still tr so dystro with a lot of if statements is going to be my guess but we have to be careful okay they're no multiple edges that's good uvn okay i mean i think we should still be okay because for each edge we're only at worst going to look at it from well i mean recharge can only be looked at from two places right from the from one endpoint and the other endpoint um so yeah maximum is 10 to the nine so here if you had any thoughts about doing dp by max moves this would be like nope you have to do it with dice driving this is just nicer of carefulness so let's think about it and then yeah i think we can do that actually so let's set up the list of stuff okay and as usual i always change this to a big end just because it's consistent with me but you know that's just me okay so for you we in edges and is there a count as well yeah uh this is the count yeah in edges we're just setting up the edge list let's call this uh let's just say z uh default date of the list yep you got this we append recount and then yeah this is just setting up the linked list with the cost and then now we start from zero from dystra yeah let's do daistra i'm thinking about something for a second no it should be okay yeah dijkstra i implemented this i think this was a contest solution like about this was a contest uh problem maybe like a month ago and i had a typo that i really debugged for a while really rusty with all these like problems that i know you know that i know i could have done better but yeah um okay anyway let's do it let's just set a heap and then we set heap dot uh he cute he push sheep and that's just called h alright um yeah and then this is node zero or zero this is just a lot of if statements i think that's the thing but yeah wow think of heap is greater than zero we okay we have to do more things here by the way of course we have to do shortest path yeah okay because that gauges how far we can reach out from here actually i think the shortest path is already good enough then we can look at each edge and then determine how far okay i think that i was going to do something way more funkier but now that i think about it i think we can just look at we can just use the distance in the dijkstra and then for each node we can look at all its neighbors and then do the math that way okay i think i'm happy with this one now uh okay so yeah let's just say we have this as you go to um i don't know what happened um infinite times okay and then now you have the distance and node equals q the hip-hop of h okay and then now we go for v in g sub node or for we count when use of node let's double check the map for a second because here if there's one count in between then it takes two to get to two right so then um yeah outside my spell heap if distance of three sorry i'm getting distracted people keep pinging me on my phone okay let's do this okay if is greater than d plus count plus one then we want to set this equally plus count plus one and then put that on the q uh let's see we push new distance and the node um yeah okay this is okay right why does this feel so too short i feel like i'm missing something really obvious but okay fine um yeah and then if d is greater than distance of node we can we skip and we continue so that we don't process the same note more than once okay and then now we should have to show this path from everywhere uh let's see let's take a look real quick to see whether this should be good he pushed got to oh yeah i always forget because the syntax is very awkward in python 10 4 and let me just copy and paste these things in okay let's run the code real quick to see if the shortest path is good uh let's see 0 is 0 it gets to 1 and 11 okay gets to 2 and 2. i guess that's right assuming that this is 10 okay um and then here is just a lot of infinities and here we have five and nine and then max is 23. okay and then now we can look at it for each node and then we can calculate it for each edge right um yeah so okay so then now we go for each edge again you we count in edges okay so how many gets used right so that's a question so total is zero for now um then that means that how many notes of this edge gets used so that is the question okay so yeah okay let's first of all okay um hmm i mean i know the math but i it's oh i know the theory i have to think about the math to be precise it's a little bit tricky so that now you have two things right and then this is basically the couple of examples one is that they don't reach each other so that means that max moves minus this distance uh so this is and i just caught from the left it's not really from the left but i mean all like you know there's no left right um but yeah so then now this is from the right and then total we just added to um min of left press right so left plus right or max or not max moves or count because that's the number of things in the middle right um and then now we can return total uh that's not we don't consider the original node so now we just do the originals so here if this step i is equal to uh infinity no it's not equal to infinity and that means that we it is reachable so then total we increment by one hopefully this is good yikes oh i guess these can be infinity as well so that's why if okay well okay fine i'll just set max of this or zero so that this basically gets at least uh is either zero or nothing okay so we're close not quite obviously but we're close i think we're on the right track um so what do we get wrong let's see and i think yeah we're just having off by once so yeah okay right now the path here i think we need to yeah this distance is one because wait is it max moves though right not let's run it real quick i don't think so though i think this is still c is it is max moves from zero so it doesn't count the node zero oh no um yeah i don't know i think this should be still be zero okay because i think that's just max move so then it takes count number of moves plus one to reach the new node yeah i think that's okay why do i have 12 so that now there is max moves let's say we're coming from max move to the left then that means that we can make that many moves hmm i'm not convinced that what i'm i mean i know that my what i'm doing is wrong but i'm not convinced that my logic is wrong i just want to have something weird maybe hmm so okay why is it let's just print it out then fine hmm okay so from the left it gets ten or six and six zero uh and we have ten in the middle so we count all 10. now we only count six so zero and six is that right i think this zero is a little bit awkward right as you go to the max smooth minus distance of three all right let's just do uv so i can kind of see maybe i'm just confusing things okay so zero and one is ten away yeah oh wait max move is six oh i was thinking about the other example i think that's why maybe oh yeah so there's six one two three four five six so that this should have a contribution of six okay um to the other node um it's six so it's one two three four uh okay so it takes two moves to go to two and then two now we look at each edge next to it um and okay so for the o2 edge we have one right o two wait what is this cow again oh no this is the cow okay yeah of course because you can't do more than discount okay yeah okay so what's wrong here let me also print out the total no i mean it's fine okay so far okay fine let's i don't have to do things in my head if i just print it out right so yeah okay so it's six plus one plus two is that right six plus one plus two okay so you could get to one what is the distance to one so there's an extra one that uh off one what is the closest distance to one it should be one two three four five so okay so let's print out distance i guess hmm okay so this is giving me 11. so that means that my dice dress wrong i think so that's why ow what am i doing here whoops what a typo okay i've been just really bad with these typos lately okay fine and then now we're gucci because the distance now is calculating correctly because yeah okay let's give it a summit um i'm so sad about it oh no okay well now i'm even more sad about it uh okay let's see i guess i should have checked the answers as well but uh but i got a little i was like oh this must be it i mean that is a big portion and we did fix it but yeah i don't know why we didn't um yeah should be okay let's see what is this one uh these crab pumps i always have to think about how to draw these out in this in these cases so that's a little bit sad i think the one thing that i didn't consider is about going for two no we did go with two notes here so okay so we're just getting off by ones i think okay let's print out the distance so then now we have zero seven nine four two is that right probably i mean that is true it should be okay right because you have zero two three is four okay uh and then zero to four is 2 also good and then now 3 to 1. okay three two one should be so now it's four plus three so seven okay and then three to two is four plus five so it's nine okay and then did we miss anything what is this four i don't know we got this is the three so i think we're good here um at least in the distance one double checking and now we have to do for you to note okay so between one and two there are five notes but one is seven and the other is nine um do i have one five one no we used up all the moves here so then the contribution is zero okay so then here we have six eight nine oh uh i know i actually was thinking about it when i was coding it but then i got distracted by the infinity so okay yeah so we have to we can we only count these notes if obviously if um if this there we can if we can get there so okay how did this work for this one oh for this one it's just that there's no it's not connected but here it's connected but it's too far away okay i um i thought i tested it that's why i didn't think about it but yeah okay cool yeah so i mean i struggled a bit with this one as well so yeah yikes but yeah but overall this is just dijkstra i think the hardest part for me is that you have to think about the cost instead of the edges and then now and then once i thought about okay i have to process all the edges independent or it doesn't have to be in the front of me but i have deposits all the edges and then now i think about okay backwards a little bit what does that mean for me right and that means that each node has you know that means that from each edge you can go from the left and the right and that's kind of basically the idea that we have um cool so yeah so dijkstra in this case is going to be let's just say you know oh of oops over read like we um technically this is already about yi the way that we implement it but as a result uh keep in mind that this is roughly reliably um roughly uh because e can be v squared and then you take out the two right so yeah and this is going to be dominating because this is just o e and this is o of um of n or v so yeah so this is this and then space is just o of e for space because we have to can reconstruct it to edge list um or you can say v plus g i suppose it's more accurate because we have all three stuff here and here is all of the um of g in general so yeah which is where you got the log e but yeah um let me know what you think uh hope y'all have a great week hit the like button to subscribe and join me on discord hope you have a great week have fun uh and yeah it's a good mental health i'll see you later bye
|
Reachable Nodes In Subdivided Graph
|
peak-index-in-a-mountain-array
|
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge.
To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`.
In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less.
Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_.
**Example 1:**
**Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3
**Output:** 13
**Explanation:** The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.
**Example 2:**
**Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4
**Output:** 23
**Example 3:**
**Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5
**Output:** 1
**Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.
**Constraints:**
* `0 <= edges.length <= min(n * (n - 1) / 2, 104)`
* `edges[i].length == 3`
* `0 <= ui < vi < n`
* There are **no multiple edges** in the graph.
* `0 <= cnti <= 104`
* `0 <= maxMoves <= 109`
* `1 <= n <= 3000`
| null |
Array,Binary Search
|
Easy
|
162,1185,1766
|
933 |
hey everybody this is larry this is the first day of october yay of the lego daily challenge uh let me know what you think about this problem uh usually i saw of this live and then i will go over to as much as i can what my thought process is how i approach it and how i attack it's not like the usual explanation video so let me know what you think uh hit the like button hit the subscribe button join me on discord and i'm gonna do this for the rest of october so hit the subscribe button yay okay let's look at today's problem number of recent cars you have a recent counter class which kind of the number of recent requests different time frame uh you have two cores recent calendar which just is a thingy it's a initializer constructor and ping had to ping a t and then just look at the last thirty thousand or three thousand millisecond okay so this seems pretty straightforward um yeah so there are a couple of ways to do this uh the way that i would think about it just using um you know the way that i think about these kind of problems is just do the stupidest thing that's easy or the simplest thing that's possible i use um i'll just use a q or you know and in python there's no q so we use a deck so that's what we're going to do and then basically you know with a queue or a deck you have two um you have the beginning and the end right well so what are we going to do well on a ping we always just insert the t and then we just keep on popping from the beginning uh while that um well the front of the queue is greater than 3000 minus the back of the queue or something like that i might have to double check on the bounce but you know but that should be okay so we have to double check that you know off by one and stuff like that it seems like it's inclusive okay but other than that it should be straightforward uh i'm gonna implement it now let me know what you think uh okay so initialize you just solve that q is you go to collections.deck as we is you go to collections.deck as we is you go to collections.deck as we talked about and then on ping we always append t and then wow i guess i mean on precondition is that they should always have at least one element by definition right because this cannot be true if there's no element so uh so we look at the top element and if that minus if t minus 3000 is greater than um this number then we just we pop left and then at the end we just return the size of the queue i think that's pretty much it uh of course we should test this is the only test okay fine uh you should have put more but i think this actually includes that edge case where it is uh off by one so i'm going to submit and then let's see how it goes cool uh so yeah a pretty straightforward problem a good way to start off the month uh so what is the complexity of this right well for each element that we hit for each ping we can at most append once and we also pop left at most ones right and because of that and each of these operations are all one we can say this is all one per ping operation amortized and also linear in the number of pings uh overall in terms of space it can be in theory of n because q can get really backed up but you know it's going to be just the size of the uh largest depth if you want to call it that number of pinks colored together um yeah uh that's all i have for this farm i don't know if there's anything interesting to go about it uh let me know what you think let me know what you find about this problem uh hit the like button the subscribe button join me on discord and i am gonna do this for the rest of the month so you know follow me along huh anyway i will see y'all tomorrow have a good night bye
|
Number of Recent Calls
|
increasing-order-search-tree
|
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`.
It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call.
**Example 1:**
**Input**
\[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\]
\[\[\], \[1\], \[100\], \[3001\], \[3002\]\]
**Output**
\[null, 1, 2, 3, 3\]
**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1
recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2
recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3
recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3
**Constraints:**
* `1 <= t <= 109`
* Each test case will call `ping` with **strictly increasing** values of `t`.
* At most `104` calls will be made to `ping`.
| null |
Stack,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
| null |
57 |
hello and welcome back to the cracking Fang YouTube channel today we are solving yet again another interval problem this time number 57 insert interval you were given an array of non-overlapping intervals non-overlapping intervals non-overlapping intervals where intervals of I equals start of I end of I representing the start of the an end of the I interval and intervals is sorted in ascending order by start of I you were also given an interval new interval which has a start and end which represents the start and the end of the new interval you want to insert new interval into intervals such that intervals is still sorted in ascending order by start of I and intervals still does not have any overlapping intervals and you are asked to merge overlapping intervals if necessary we are asked to then return intervals after the insertion so if we have um this example here and kind of let's just draw it out uh on a number line so if this is one let's just say uh this goes up to nine so 2 three four five six 7 8 nine okay that is roughly a six okay so we have our first interval from one to O that's really bad uh one to three we have the second interval from 6 to 9 and we're asked to insert the interval uh 25 so we can see that this is here oops not to there 225 Okay so how would we do this well obviously if we were to insert this interval here um it would overlap with this one and we're asked uh that there's no overlapping intervals and that they're still sorted so in this case we need to merge these two intervals and we've done this problem before um basically to merge it we take whatever the kind of leftmost starting point is and whatever the rightmost starting point is of the two intervals and then squash them so now our interval becomes 1 until 5 and then obviously there's no overlap with the next interval so we don't have to do anything there so we can just leave it as it is so six and N now this example is uh quite long um but maybe we can actually do it oh boy I have to draw out a new number line here CU this thing goes up to 16 now uh okay that should hopefully be long enough uh one two 3 4 five 6 7 8 9 10 11 oh boy 12 133 14 okay 15 and 16 so we have this example and just to do it visually um okay so we have what are the intervals uh from one to two we have 3 to 5 6 to 7 8 to 10 and 12 to 16 and we're asked to insert two to five so obviously if we were to insert two to five then this would overlap with this interval so we need to squash them which becomes the interval for 1 to 5 um which actually also encapsulates this one so we would just merge them so to get rid of this one because it's overlapping so this would just become the parent so it would still just be one to five uh so this interval would kind of just go away um oh actually no wait hold on uh oh wait we want oops I was inserting the wrong interval so oops I was looking at the previous example um so this is 8 to 10 sorry about that so this should be 12 16 and we're inserting 4 to 8 so four until 8 so with this one we merge these two and obviously this covers uh this one so it would get absorbed so this one would go away completely um so we still have the interval from 1 to two that one is fine but then we need to merge these ones so this becomes three until what so it goes all the way to this one but then they intersect so we need to merge it again so we'll merge and take the end point here so it's 3 to 10 um and then the one from 12 to 16 is on its own um so that is kind of how they got that one so this question obviously looking at it is relatively straightforward and the solution to it is pretty intuitive uh let's see if I can just remove it and there's really three cases we want to handle here and this is the uh insert at start so this is the case where our interval actually comes before the first interval um in our uh given intervals in which case we just need to put it at the front and that's all we need to do the second case is the insert at the end insert at end in which case our interval is so far to the right that it actually does not interfere with any of the other ones so we just insert it at the end and we're done the third case is where we actually need to merge some intervals so the merge can happen at the beginning um we need to merge we could potentially need to merge at the end or somewhere in the middle uh and then we need to merge and basically uh reduce the intervals to get rid of any overlaps kind of how we did in the problem merge intervals so those are the three cases you want to handle the one where you have to insert it at the very beginning the one that you have to insert at the very end or the one where you insert it at some point maybe it's at the start maybe it's at the middle or maybe it's right at the end and then you need to merge down your intervals to make sure that you follow the condition of no overlapping intervals uh and you merge where necessary so those are the three cases we want to handle and once we go to the code editor we'll see how we actually handle those three individually so let's do that now so we went over some examples we went over the solution intuition and we went over the three cases that um we basically need to solve for so let us actually solve this question the first thing that we want to do is if there's no intervals uh for us to check then we just return whatever the new interval is uh on its own because then we don't need to insert anything really so we're going to say if not intervals we're just going to return uh the new interval right so pretty simple okay now what we want to do is remember that we're going to be basically just checking uh each of the intervals and we're going to do this from left to right so we're going to say the current index is zero and we need to define a result variable to basically store our result here now what we want to do is we actually want to check the first case where do we actually want to um insert it at the beginning or maybe we want to check it at the end and here's how we're going to do that so we're going to say while the current index is less than the length of uh intervals obviously we don't want to have a out of bounds exception and um the star of our new interval is actually um too big then we want to just add the intervals um that we can right so we're going to say if the current interval that we're processing so inter intervals of whatever the current index of zero so if the start of the interval that we're processing in intervals is actually less than the start of new interval of zero so basically before the start of our new interval uh then we know that there's no overlap here so we can simply just um just add whatever the interval is to our result because that means that we don't have to insert our new interval yet um so we can just keep adding it and remember this works because we are told that the intervals are sorted in ascending order so that's why we can uh do this okay so if this is the case then we simply just append the current interval so intervals of curent index we just add it to our result and then just add uh one to the current index to move forward to the next interval so when this while loop breaks uh one of two things will have happened either we're now at the end of the array or um we actually never got to even start because actually the interval needs to be inserted at the beginning of the array so let's check those conditions so we're going to say if not re so if re at this point is empty that means we Haven an Ed anything to it and that is because this thing um didn't fire which means that we actually need to insert the new interval at the beginning so if we have a result if result is empty or um actually we just got to the end of the array and it turns out that our new interval actually doesn't even overlap with the last element then we just need to add it to the result so in either case we need to just add our value either it's going to be the very first thing that we put into res or the very last thing in either case we can just append to it um and it's fine so we're going to say or if the last element in res its end position is actually before the start of our new interval then that means that there's no overlap at all and this is the case where it's at the end that we need to insert it and this is the case where actually you need to put it in the beginning so if that's the case then all we need to do is just say res. append r new interval otherwise uh what we need to do is actually for the last element we now know that there's uh a problem here because we need to double check that where we're inserting our interval um is actually going to we need to just take sorry let me take a step back so this is the case where we insert at either the beginning or the end or that means that we now need to insert it and we need to actually check uh that we actually get the new bounds of our interval right because we're inserting them so we need to take the start in the M position accordingly so we're going to say that the last thing that was inserted we need to adjust it its n position based on the nend position of either this current interval or our new intervals n so we're going to say res minus one so it's the new end of our last thing that we added to our result is going to be the maximum of whatever the current end position is and the end position of our new interval similar to how we did in uh merge intervals problem okay now we have inserted our interval either is at the beginning of the array it was at the end of the array or at some point in the array and we've now merged uh those two intervals to make sure that um you know we have the merge thing but now that we created this new interval by merging whatever the you know some interval with our new interval we may have an overlap later on in the actual um uh problem so now we need to handle any of those uh lingering overlaps so we just need to continue through our processing uh and actually finish it so we you know we'll still have cerr index at some value now we need to just continue until the end of the array and actually process everything and add it to our results so we're going to again say while the current index is less than the length of intervals now we basically just have a merge intervals problem and we've done this before we're just going to say that the current interval is again equal to intervals of current index we're going to say if the start of our current interval is a oops interval ah sorry if the start of our current interval is actually less than or equal to the end of our last interval that means that we have an over overlap and we need to handle this so if this is less than so res minus one will give us the last um interval we have and then the First Position will actually give us the end of it so if the start of our current interval comes before the end of the other one that means we have an overlap uh so for example if this was like the interval 1 3 and then we had the interval 2 to 5 right so two its start position is before the end of the other one so that means that there's an overlap and we need to combine these two into one to five so uh that is that casee so if this happens then again the new ending position is going to be the maximum of the two ending positions so as we just saw in that example with 1 to three and 2 to five obviously it would be five uh after we merge it so we're going to say the current interval of whatever its end point is and whatever the current end um intervals end point is okay so that is that so this is the case basically when it's equal to that um we would use this one so okay so otherwise we know that there's no overlap here because we just checked whether or not there's an overlap between the start and the end uh if there's no overlap we just append um whatever the current interval is and continue so in the case that we basically inserted at the beginning um all we're going to end up doing is just um actually no sorry we can still fix overlaps but yeah there's a chance that there actually are no overlaps uh so we just basically just append the interval I'm confusing myself even so um otherwise yeah let's just increment the index at the end of all of our logic here and continue until basically um we hit the end of whatever the length of intervals is and then at the very end all we need to do is just return our result and we are done let me make sure I didn't make any little mistakes here Cur interval oh boy today Cur interval great can't type today can't spell today okay there we go at least it now should be accepted Perfect all righty so what is the time and space complexity so as you can see in the worst case we're going to basically parse through the entirety of intervals once and you know we may have to do some merging logic but all of that happens kind of in place um so our time complexity is Big O of n uh um where n is the number of intervals in intervals uh so for the space complexity we have well it's a bit complicated so technically it's Big O of n uh because we need a result uh array we can't you know use the we can't overwrite the original array um so technically it's Big O of n because we have this new um array but um some interviewers will just call this but maybe bigo of one um because we need an array for the solution so uh in this case sometimes your interviewer will let you just call it Big O of one because I mean you can't not return this list here so you're not using extra space this is just what you need for the solution but technically it's big oad because you need to store uh the result here but you could say I mean the best way to say it's Big O of n because we have the result array but since we need it for the result it's technically Big O of one because we don't actually um create any extra space other than what we need for the result anyway that is how you solve insert interval like you see all of these interval problems are very similar uh this one is basically a combination of merge intervals and whatever the other one was I don't remember in interval insert index or something like that um where we're basically just checking start and end points merging intervals and continuing forward so pretty straightforward remember that there's three cases in this problem inserting at the beginning inserting at the end or inserting somewhere in the middle and then needing to handle all of the overlapping cases because we're not allowed um mer uh non-merged arrays here allowed um mer uh non-merged arrays here allowed um mer uh non-merged arrays here so that is how you solve this problem hopefully this video helped you if it did leave it a like and a comment really helps me uh grow the channel why not subscribe as well and I will see you in the next one bye
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
1,834 |
hello guys welcome to code enzyme and in this video we are going to discuss the problem 1834 of lead code the single threaded CPU and in this playlist I discuss daily the elite code problems so let's see the problem statement you are given n task labeled from 0 to n minus 1 which are represented by a 2d integer array where task I is in queue time and process time it means that the ith task will be available at process time and queue time and it will take process time to finish the processing you have a single threaded CPU that can at most process one task at a time and it will work in the following way you can read it I think the main line is this if the CPU is ideal and there are available tasks the CPU will choose the one with the shortest processing time if there are multiple tasks with the same shortage time it will choose the task with the smallest index okay so this is the catch here and once a task is started it will process the entire task without stopping so let's see this with an example since we have at time t equal to 1 task 0 is available to process so it will take this task at and then we can either take task 2 or task 3 since task 3 has the uh we can either take tasks to this one three comma 2 or 2 comma four since this is has the smallest task uh process time so it will take this one and after this finishes we can either take this one or this one because the time overlaps is 5 so we can take time equal to 4 or 20 equal to 2 so we will take 4 comma 1 and next this is left so we are going to take this okay so we need some way to find in Big O of 1 the smallest possible time that is at hand and what kind of data section will help us do that it will be a heap right because it stores the Amin Heap will always store the shortest index at the zeroth added three head okay so let's see how we can do that so first I'm going to make a heap out of my tasks as and you can see that I have this uh I'm also storing the index so I updated my tasks and I am storing this index also in my array and when I convert it into a heap it should look something like this and I have sorted it using the zeroth index so this zeroth index are in ascending order okay now uh and I have two more heaps this weighting is also a heap and currently the time is 0 and our final answer is empty now when I choose my first task since my waiting list is empty I am going to choose from the Heap okay so this was the first task and I have chosen that task and now my time at time t equal to 1 I chose that and it took time two seconds to complete so my time is 3 right now and when I check in the Heap now I am going to search this entire Heap and I am going to check which all tasks have uh starting time less than three or less than or equal to 3 so these two tasks were in this main Heap and I'm going to transfer them to the waiting list now so my waiting list has become 3 comma 2 and 2 comma four comma one why this uh array by this order because now I am sorting them with the uh finish time the process time because I have to choose the smallest process time now and my answer will become the answer will have the zeroth index and I have removed these two tasks from the heaps so he only has this one task now okay now when I will choose the second task I can see that my waiting list is not empty so I am going to choose from it now since this was my first task in the waiting list this is my current task and my answer I'm going to append this tool in my answer array and now my time is equal to 5 because it take it took two seconds to finish it so my time has become five now I'm on now I'm also going to Traverse in my Heap and I'm going to check how many uh how many tasks have a time starting time less than or equal to five so there was one task so my Heap has become empty and this was a and this does was appended to my waiting list and finally it will be this because we have sorted it with the finish time the process time okay now and the third task will also be the same we will choose this 4 comma 1 comma three and we will append this 3 here in and last time it was five so I am going to add this one to my time so time has become six and now in my waiting array we only have uh waiting here we only have one task and like that we can choose the four task and now since waiting and he both are empty since both are empty I am going to stop here and this is my final answer okay so I hope I was able to explain you the uh at least the implementation part properly now let's see the code so this is a python code first we have a heap and now I am going to use the enumerate function in Python to get the indexes and I'm going to push them in into my Heap and I have a waiting Heap and an answer array so if I have something in a waiting in waiting I am going to choose F and I from I will I'm going to talk about why I have put this like that here and if not I am going to choose from Heap the start time the process time and the index and I will set my finish time as e okay now I'm going to add it at this finish to my finish time because it took that much time to complete and I am going to Traverse the Heap till this is less than or equal to finish time and I am pushing this F comma I to my waiting list why because in Python I did not I was not able to find the Sorting uh if it was possible to sort it using the second index I mean there were ways but not with the Heap okay not with this heat push function so I just decided to remove this first index and since uh and this will be able to sort this will sorted using the finish time okay and after that I can just return the answer and if you are running this on your computer you can just put this print statement here you will be able to see how your HEAP is changing how your answer and waiting keep an answer is changing and you should be able to get that idea okay so this was it and I hope I was able to explain it properly so if you were able to understand this question properly uh I hope you like this video subscribe to my channel so thanks for watching I will see you guys next time with another problem thank you
|
Single-Threaded CPU
|
minimum-number-of-people-to-teach
|
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109`
|
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
|
Array,Greedy
|
Medium
| null |
1,254 |
Soon dynasty or there will be children here and subscribing will give normal number of cost Ireland okay number five is silent question which we have done like this concept base system I am telling you this okay I am please request you I will make this humble request that you please attend this rider, he will board the auditor liya, okay, it seems like a little mixup of the shop set, it may be a question to my videos or not, so watch Vikas when I get the code done to do that cord. A lot of things are right from the style and it is very important or what you do, the lead to define button, when I explain the code to the people getting it done, that letter is very important friend and do you think or have understood, move ahead. What is the problem, but lately, those small things which I will intimate in the code, they will let you know, will give 10, I can do three lines in it, so these small things will not be seen in this chord, see more of it in the code. I am using it for you, Vikas, literally, he was afraid of those who will learn small things, okay, then the question is a deep problem, my friend, but before that, I am going to say that you yourself, we will be the guest, must have asked these questions because of your questioning. We will make it more important. Okay, so the question is being asked. The whole question is very simple. Friend, number follow side number follow silent. People are asking such questions very often. Okay, the number off is now in the last place. Shankar will come to the fruits that have come out, okay, the total number of sacrifices is okay, so that is all of us, you will remember how we did it, okay, you will know the body success, we will use it here from this chhutku, so I had said that every time is free. Let's change the theme that zero means line and one means water. Okay, remember that investors don't care. D grade is okay and we have been given a hang and sam's metric in which 140 feel heavy and where But that land of Zero Adams is fine, right? Our job is to find a surrounded line which is completely covered with water. So, if we talk about this screened route, it is fine, what kind of line is this which is completely covered with water? It was completely filled with water, ok sure, what kind of line is this, the problem is that it is surrounded by water, if we talk about direction, then we are talking about fold action, which was specified to you in the question, we are talking about this line and kidney cancer. To develop the whole of the whole does not fall from water this side water add water but here it is all water if this side zebra water but here there is water no here powder this is not okay so this is understood till now thought upon doing Ca n't walk in the butt boundary, okay when Pandey applied a little brain below that after doing the dates, you must be feeling that come on, this year 's answer has come, it is understood how 's answer has come, it is understood how 's answer has come, it is understood how development is 21 types of calendula which is full of Friday, let's go with water. Seeing this question one thing, you must have understood that in the question it is given surrounded by water which should be completely surrounded by water, it is not that here the base judge is not right like in this case. I think this made the picture clear that we do not want the boundary touch line, okay SDO BDO will also be the boundary test for Ireland, we will touch this land border from below, we do not want this, bond centers do not want this from this point. If there is zero here, then is this required, then this is not a border, these pimples used to be collected from the boundary, we will get this till here too, so this is also not required, okay, then this thing which will be Led Foundation Trust, okay, otherwise silencer's We can reach through the border, we do not want these attacks because for the border minutes, we terminate at the counter which is ₹3, the whole of it will be surrounded by water, which is ₹3, the whole of it will be surrounded by water, which is ₹3, the whole of it will be surrounded by water, otherwise we will not get the request and it is better. You will understand, if you don't understand then watch the starting video, you will learn stitch saw in a much better way. Okay, see how we can do it this year, there are questions like that and we will start walking in the laundry, okay. When we start doing things in the body, we should start from here, then we got 101, what we got here, what will we do with it, will we stop it, now what will we do, will we call gas, okay, then what will this forest do, ISRO is crazy, it has been turned into water, what will this day do? Who has made this gang? Next, when we make zero here, click on the date, we will make it. Okay, so the whole body has been made ours. Now what work is left for us, what to do with all the zero children, edifice self. Start, okay, what to do this time, check how many are being covered in one go, whether the whole will be covered in one go, okay, this whole will be covered in one go, so this is done with A Grant Plus One then where will the second go, this is also one, all these are made here, the person will then do Swiss roll here, then it will come here, color 102, the answer is ok, basically these two raw test calls, verification will be called twice, the first goal will be scored only. If we get zero on any boundary, we will record it, we will call the rest, we will make one and a half resolution and in the end, we will roll the desk only to keep track of how many zeros are left, lines left, send it to the Group of Scientific. That it is surrounded by water, okay turn off the flashlight, understand it as one, here we have to cut it and hit zero, here is the chart, okay this cross is difficult in youth, if you decide this then you have got the sea line, this arm clock will stop the sharp hair. Will close it will close it datesheet Now this is one day one now what will we do then we will do school for this then this wave's this human's this is completed now when we will see in the last that and all this all the money is gone Now whoever got one in the boundary is fine, what was our job to make one in the boundary, you get zero in the laundry, if you get zero in the boundary, that means you get a line, then what to do, dad, call for that and all the others from that. The connected line is convert everything into water, this is our WhatsApp, what can we do, we will convert it into water, okay, so all this has been converted into water, now in the end, this diagram became this village itself, 151 What is the half-baked work that? A call DSS then What is the half-baked work that? A call DSS then What is the half-baked work that? A call DSS then you like we land luck like this is line fault okay now this is a single line I got this trick single window elemental not at all in a group line now this yagya more added to this would have been 120 okay this is over here Zerota would have done this by converting the whole thing into a group of flying and taking the pressure, but that's why we used to add a little plus to the duty of this function call, you must be feeling what is going on, this is why you feel that we have developed. Dongri, at least watch this, I have not understood the concept of division which I have maintained in this video, so it is very problematic for you, better if you do the old question before asking this question and which I have given. You will get it in the play list of this graph, it will be very light for you, co-exist gram dhokkar will understand a lot, co-exist gram dhokkar will understand a lot, co-exist gram dhokkar will understand a lot, you will understand basically what is quora every day, so that you are getting zero in all the boundaries, okay, basically what will dowry do, finally terminate. So he will go to the boundary, so what are we doing dear, first is going on, ok first travels boundary wall jhal, I am getting zero, keep making it difficult, platforms were found here, as soon as this gang was converted into life. He will turn and do this for 15 minutes, whoever will butt, then look like a strange person, he sat inside, then from a boundary, we can have internet from here, so this will convert this into a forest, do this, look at those who take falooda and give coriander to the people with arms. So after debiting in ultimate grinder, this fire is fine with us and what am I doing all this? Simple, if like Grade of I is getting forced then what we will do is to call on gas and inside the desperation Grade of I We will kill the fun in the forest, okay, here's the marking, here, by killing the animal here, we have killed the living creature, okay, here, okay, Dada, what would have happened now, if he had come to us openly. Now this is one such group left out of line which is not converted into one, why Bigg Boss Boundaries, we are reachable on this group, what does it mean that it is completely surrounded by water, so if we could not reach you guys, then this Mute things like what will we do, then we will call DSS, not on the boundary, but have full control on the entire grid, this line will start moving, if we don't find an old man, what will we do then, I would race him, call him once for another reason. If you do, then we will roll from here, select 10 in it, what is not found in it, select it in parts, cut it in parts of the country in which it was found here, in the forest, do not take this etc., in the forest, we will in the forest, do not take this etc., in the forest, we will in the forest, do not take this etc., in the forest, we will reveal the armpits in the forest, by making a big comment, why convert to others now? Why are people converting it into what? Last time it was definitely necessary to convert it into the sea so that we can reduce where we are going to reach. We gathered here, we could have also used it, but why do it when we are zero? We can march in the forest and tied that we will use it after that otherwise why should Madrid be spoiled, it should be data quartered that it is not problematic for us, we basically have to account here, start on DJ Comment here, the pudding of defense pension is fine, whatever zero it is today will convert everyone, it is fine in the forest and if it goes out, it will not get any 108 actor, then this is what f10 has done together with the British and what is not zero. Got the phimosis closed, then we will move ahead, here also we did not get zero, again we got zero, here we will make it difficult once again, here it is ok, call us again, this one tweeted this one this body Commented in my mind, closed take, there is nothing else, let's move ahead, G0 was found here also, here and we have come to the open loop, okay, so 200 grams is the total, this is such a group of land that we are a complete. It was surrounded by water and after doing the entire process of reminding that all the zeros that were there in the boundary, we caught them and differentiated them. What was the benefit of this that till the boundary, such land got converted into water which ultimately Pandey It was doing joint, it's fine, even if you convert it into water, there was no problem, basically we killed it, firstly, its benefit is ok for you and on the other hand, Vidare is not using it, today we will be able to understand the office, use it to be joint. By doing this, Verma will do it. Okay, this is such a humble request, depression is not Vasundhara, I am not understanding anything, it will not stop starting in the play list of her Simple Sahara and you would have been associated with it, you would have understood the questions of Italy before I could speak. Let's code it and see who can support it. I would request you to please the Lord Besto with this, see, I am telling you the truth, I am installing you that you will get so much confidence in the graph that you will say that For the first time in your life, you understood such a good crust. If you are not able to believe what I say, then please check the comment section. Starting Rakhi Playlist Katha, because the better I understood what is bad about other people, my videos. Okay, now Italy will feel very confident, friend, so I would request you this question that you must stay connected because Bigg Boss is bigger than you and me, that's why Vikas seriously, when I code and explain by saying this, it hits your mind. So we think, how are we replicating this in angle, we are okay, the first task is to remove them, so what will we do, grade size will be very simple and second, what is M equal to grade of zero size, okay, so we What did you get, you got the metro site, now our work is done, it is okay to walk in the body, till now those people are assuming that you are not in this video, there are no settings, the playlist of my village has been made so that only then I have the button, my health is still beneficial. By now do you know how to do it on the border but come on that tight now let's start some new method place subscribe and i plus ok you points 100 tell me how it happened now you will know how it happened right Only my cross J is equal to zero or I is equal to and minus one or the gel is equal to - it burns. or the gel is equal to - it burns. or the gel is equal to - it burns. If this condition is there then we will say that yes, now we will cover it and we will ask the question it. Means that yes, this shell that we have caught is the text of the boundary, it is covering the Aravan tree, now people brother, if I do it then see if zero comes, I am giving the proof, then we will call the notification. Bypassing IJ and grade, let's go for sure. What will this do, this Dongri body, this dam of F1, will convert all the lines connected to it into water. What will be the benefit of this, that the land will not ultimately convert into water, the rest of it is surrounded by water, okay development mode. Start walking through the line, water, those who were not holding the metro, convert all that land into two cups of water, if that line is saved from the ultimate, then surrounded by water, Italy, I must have understood what Seema wanted to say, now tell me which one you want. I am giving it, okay, what do you have to do, whatever data is inside it is coming to me here, okay basically you will put co.in here, okay, you have to try it put co.in here, okay, you have to try it put co.in here, okay, you have to try it yourself, okay in the copy because You did not trust the depository, it is turning off the types because of this condition, it is only he has to select it that he has his trust in the laundry, he was taking it out and working in the plant, okay look, I pasted it if and five Class Seventh is okay, so ultimately Gems nourish, okay, whatever you are seeing, that means whatever you are seeing, it is more fun than water, it is looking cool, basically this whole thing is from Gura, that is Delhi's okay in the network. Convert it into three and four without husband, as much point as you will get, okay, he will get the data, he will get the boundary, okay, so this condition is doing that I have understood that if the one who is on the boundary, we will basically give him the complete boundary wall. Hatred should explain this, overall ok, we used to be the people who used to do this typing, Bible verses were in online system, this is your dry ginger found, ok, condition has been imposed on it, Income Tax Commissioner Rajesh should be 120 or equal to rent, admin, this is equal to Isn't it a little bit, please give it in five minutes, you will understand better, okay, I called for the second time, our work was done that we put face in hole grade, what was the benefit from it and what do we have to do, which ones were saved, okay? So what to do on this is zero, then pasted it, removed it completely, grade of ideal for me in fights or comes home subscribe village so that in the absence of freedom will do, see here, all these such a group of Due to hatred of water, that's why despite traveling this body, we could not convert it into that zero oven, why the monk was completely surrounded by water, so what will we do now, regarding this, all the lines at that time should be given to everyone on this lamp. Number will convert into relation Fall mark of visit is ok and absorbed Will give a big one That we got the gas cylinder Again if we get something like this Then again the MP will give a big One Our main focus is to complete across this country Okay, so that's Dad I and Jan10 Entertainment and What is a Vector Grade Uber App, I have explained a lot of things by basically doing the complete process, so I have explained a lot, so you have a little empty work that MS Word gives you to complete it. Let's kill him, okay? Intellects of I'm sorry. Come on, why not make it work in a little less space, okay then pants for end i = 0, this is my mistake, pants for end i = 0, this is my mistake, pants for end i = 0, this is my mistake, what did I do, assume that you should believe this, why should Vikas die, then the week loop is not ignored, they make mistakes. This one came and inside itself or cream, then starts doing class, then your answer is coming, the software is wrong, so that London for and K Plus, I used to do a lot of settings behind, will you get a new Okay, and intent and wife are equal to Z plus off, okay, we will check the notification light here, it is also correct that where we are, what is it, Lord, is it really a post matriculation lesson or not, okay, this is a noble understanding. I came in this month ago, I have told you to join it till the net minute, once you have searched, the hair will understand the batter, it is okay because if you meet, then it does the class, you do not get the data from this stitch. Then we create the avatar wrap, if it is like this, then the edifice of a simple Android and tagged Colgate, our work is to shift it to this side of the business which is very easy to make profit on this one, so it is taking all the parameters, okay. Not only is it greater than 60 i10 nano and examined yesterday 204 and what is the name and we are going that should be together should be okay yes so will return true and also will return this is good okay so this definition is complete Vikas has happened, he has killed his mind, this youth has worked, now what will this pandey and cheap boy do to all the Gujjars, he will masturbate him with as many points as the ringtone, and what are you doing in the second time, how much will he [ __ ] you? Sit and go for admission how much will he [ __ ] you? Sit and go for admission how much will he [ __ ] you? Sit and go for admission that it depends on if I am getting the flight, okay, submit, it is successfully submitted, then I hope, friend, you must have understood this, 40 is saying that the end solution architect was not Vikas, this is the new decency in coding this. A little driving has been given to him in his job, he has not been allowed to attend happiness. If you are not against starting then keep watching from the perspective, it is fine for you only. If you liked the video, then please let me know by commenting. Friend, I like this very much, okay no, like it, comment and subscribe, if you have not considered then you can share it and do your August, then I don't remember Vikas or anything, please share any post of the gender. I am Rafi from here, it feels good that the conference is coming, share some quality WhatsApp, in which college you study, like the side of help that I need from you guys or the burning Tubelight, Happy First Rain
|
Number of Closed Islands
|
deepest-leaves-sum
|
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1`
|
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
1,608 |
okay we're going to be doing lead code 1608 special array with x elements greater than or equal x so you are given an array called nums which consists of non-negative integers which consists of non-negative integers which consists of non-negative integers nums is considered special if there exists a number x such that they're exactly x numbers in nums that are greater than or equal to x right and notice that x does not have to be an element in nums uh what this means is for example this three and five because this was confusing me as well so three and five qualifies as a special array and this is because they are numbers two numbers greater than two greater than or equal to two right but it's not one the answer is not one right because uh yes three and five are greater than one but there's no other number here that's greater than or equal to one so if there was maybe one three five then yes but it's just three and five yes three and five these numbers are greater than three greater than or equal to three but there's already but no they're not great there's not three numbers three there's to be a minimum of three numbers which isn't the case right um let's go to the next example zero and zero can never make an array special according to these conditions because if zero exists in an array then there's already one number which is zero right so zero cannot qualify you need a number whereby there's x or more that are greater if that number exists then it is a special array and you return that number now this is difficult because it's not an algorithm that you can even you cannot think of the solution of how to identify just by looking right um okay let's look at also this example so you have 0 4 3 0 and 4 right so the answer here is 3 because there are three numbers greater than or equal to three right uh the way another the way we're going to do this there are two solutions the first one is brute force but it uses two for loops and the second one is a binary search but the for loop solution is actually in constant time it's in constant time because the num length is a hundred but also the highest possible value because our nums is between the values are between zero and one thousand inclusive so the highest possible value is x is equal to 1000 and if x if you're trying to see if x is 1000 then it can't be the solution because the length of the array is only a hundred right so you need to have at least one thousand numbers greater than or equal to one thousand so one thousand itself cannot be but in order to exhaustively search you search from zero to one thousand as our possible values of x and for each of these we check by looking through nums and seeing how many times it occurs this a number greater than or equal to x or cars and if that number of occurrences is equal to x then we have found a special character and we return that character otherwise we return negative one right here they say return x if the array is special otherwise return negative one another thing they say it can be proven that if nums is special then the value for x is unique this means that if that number exists in the array then it will be the only one right it will be the only one in the array so as you can see here right three exists i mean the there are three numbers greater than or equal to two to three so three is the answer but it exists only once so it's unique but this isn't much of something think about so let's start with the brute force solution which we've ascertained is in constant time because it's uh so we'll say brute force solution which will be um our sum our s our population cause our population size for possible values of x is 0 less than or equal to x less than or equal to 1 000 right so we iterate over the possible values of x and check for them check for the number of occurrences of x greater than of num greater than or equal to x in the nums array if this count is equal to x then we have found then we have a special array and return x or count so let's do that for what's in it we need a counter so we do that we need our counter so counter is equal to zero then four we iterate through possible values of x which will be for i for x in range 1001 right because we want to go from zero to one thousand remember x stop python stops at the second last position here so then we actually the counter needs to be for each so we need a counter for each right so iterate through possible values we need a counter for number of a of number of greater than or equal to x in nums right so we do it here we're like four num in nums right if num is greater than or equal to x right if num is greater than equal to x then we increment our counter so counter plus equals one then if our counter is equal to x we have a special array and we return x or counter so if counter is equal to x then we return x if we reach here then we loop through all possible values of x and found none we found no instances of nums of numbers in num nums array which are larger or equal to x and occur x times right so we simply return negative one this takes constant time because it's 1000 and this here is actually length 100 so this is a thousand times 100 which is constant time even if this was like n if this was like an if n was to infinity then this would have been a thousand times n so it would have been an o of n solution voila it works so we're not going to use this solution we're going to use uh because an interviewer may decide to say that no this is not optimal i don't care if it's constant i consider it i consider this n right so one that shows you that the interviewer doesn't know what they're talking about but you don't argue with the interviewer and what you do is you simply move forward with a more optimal solution so the more optimal solution is we're going to do the counter part this part but instead of looping through we can binary search and the reason we can binary search is that this is an ascending order right so since that is an ascending order let me draw it up here so we can do it in ascending order right uh from zero to one thousand inclusive we check we find a mid and then we check if we check through the nums array then if the number of occurrences is equal to mid we return mid otherwise if mid is less than the number of occurrences then we push out we want to get rid of all the values including mid right otherwise if it's greater than we want to get rid of all the values as well on the right hand side so let's do the binary search solution so the binary search solution is i is equal to zero j is equal to 1000 right so while i is less than or equal to j we get our mid which will be made is equal to i plus j divided by two but as you know some people if i try to i plus in brackets j minus one divided by two right and now we check in nums right so we have our counter is equal to zero then for num in nums if uh num is greater than or equal to mid right we could have called mid x right or possible value of x so we get our mid which is a possible value of x right then counter here counter plus equals one so now we check using binary search so if counter is equal to mid then we simply return mid or counter l if mid is less than counter then we want to get rid of all possible values of x less than or equal to mid right so i is equal to mid plus one else this means mid is greater than counter so we want to get rid of all possible values of x that are greater than uh or equal to mid so j will equal to mid minus one so once we get out of this loop and we still haven't found it we simply return negative one so let's run this and see voila it works and this is uh log of n log of size of the possible so log of 1000 uh times uh length of n right but this is essentially constant time but another thing that we can do is this works for length of nums as well this will also work what the hell happened i didn't mean to pop that up this works for length of nums as well hold on a second this works for length of nums second yeah uh what was this last time okay another option maybe if you started from one to length of minus one no okay from zero to length of noun should work and the reason this works is because um all possible values of uh of x when using the binary search they are not going to exceed uh the length of nums right because the size of the array actually constrains how many uh possible values you could have right so when we're doing the brute force we're just exhaustively searching through whatever was possible but here we know that it will never exceed the size of nums
|
Special Array With X Elements Greater Than or Equal X
|
calculate-salaries
|
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`.
Notice that `x` **does not** have to be an element in `nums`.
Return `x` _if the array is **special**, otherwise, return_ `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**.
**Example 1:**
**Input:** nums = \[3,5\]
**Output:** 2
**Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2.
**Example 2:**
**Input:** nums = \[0,0\]
**Output:** -1
**Explanation:** No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.
**Example 3:**
**Input:** nums = \[0,4,3,0,4\]
**Output:** 3
**Explanation:** There are 3 values that are greater than or equal to 3.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
| null |
Database
|
Medium
| null |
1,688 |
hey everyone today we are going to solve theal question count of matches in tournament okay so this question is very easy so let's jump into the code directly so first of all initialize result variable with zero and start iteration so each team gets paired with another team so total match should be n/ another team so total match should be n/ another team so total match should be n/ two so that's why we iter through until like a while n is greater than one so if we meet this condition we continue iteration and the matches should be nide two right so and uh we should a number of muches to variable and then so okay so total team is four and uh in that case there are two mates right so and then um so if um some team lose the matches so they have to leave so in that case two team have to leave right so total number of Team should be n minus matches right so and then uh we continue iteration and then after that just return oops return less yeah so let me submit it yeah looks good and the time complexity of this soltion should be order of log n and the space complexity is o1 and uh so actually there are another way to write your code so and that way is very easy so I'll show you how Okay so look at this example so if total team is four so there are two matches right and after that two team stay and play one match right and the total three matches and if we have seven teams so there are three matches and after that four team um stay and play two matches and after that um two team stay and they play one match and total six right and if we have 10 team so there are five matches and after that five teams stay and play two matches and then after that three teams stay and one match and then after that two teams stay and play one match and total seven8 n right so look at the relation um like between total team and the total matches so when we have four team so three matches right and when we have seven team so six matches right and when we have 10 team nine matches right so that means so the answer is actually n minus one matches so we can write like this return n minus one yeah so let me submit it yeah looks good and uh yeah time complexity and the space complexity should be all1 right yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Count of Matches in Tournament
|
the-most-recent-orders-for-each-product
|
You are given an integer `n`, the number of teams in a tournament that has strange rules:
* If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round.
* If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round.
Return _the number of matches played in the tournament until a winner is decided._
**Example 1:**
**Input:** n = 7
**Output:** 6
**Explanation:** Details of the tournament:
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.
**Example 2:**
**Input:** n = 14
**Output:** 13
**Explanation:** Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.
**Constraints:**
* `1 <= n <= 200`
| null |
Database
|
Medium
|
1671,1735
|
124 |
hey everyone welcome back and let's write some more neat code today so today let's solve binary tree maximum path sum and yes this is another problem from the blind 75 leak code list so this is a list of 75 common leak code questions and today we're going to be solving this tree question binary tree maximum pathsome the link to this spreadsheet will be in the description if you do want to take a look and i think i've almost done all the problems that i wanted to do from this list nearly all of them so far so a path is defined in a binary tree as being a sequence of nodes where each pair of adjacent nodes in the sequence has a can as a edge connecting them and a node can only appear in the sequence at most once and the path sum of that path is defined as being the sum of all the nodes values in that path so for example in this example we're given a tree and the path is basically going like this right you see how you know we have a node we go here and then we go here right it's it this is this counts as a path right even though it's even though from here we're technically splitting we're going left and right this is still a you know a sequence of nodes right it could be read like in any direction but it's still like a sequence and then when you take that path you basically get one plus two plus three so that's going to be the output now of course in this problem we can actually have negative values so for example this 2 could be negative 2. so then what would be the maximum path sum then well we don't want to add negative values that won't increase our total so in this case we're going to go from here to here right this is going to be our path 1 plus 3 and then we would return 4. now what happens if this negative 1 this value was a negative 1 instead right now we could just take 3 by itself that counts as a path or we could take 2 by itself that counts as a path or we could still take that same path which would give us 2 minus 1 plus 3 which gives us 4 and that is actually the max once again so it's possible that negative values could still be included in the output so you might think well what if we have a tree of all positive values like this one can we just take every single node like basically like this and call it a path and just add every value together well no and the reason is because some if we had this structure right this isn't really a path because how would you traverse it right we could start here then you know go this way then go down but then here we have to make a split we can't go in two directions at once that doesn't count as a path so basically what we realize is as we look at this example is that if we're starting at a node we can only split once right like if we're here we can split in two directions right we can include a path from here from the left side and then we can also go here right and if we get to this portion right we already had a split up above so we can't split twice right because then it's no longer a path so we can only choose one of these nodes we would obviously choose the bigger one that's a five right so take a look what would the sum be if we ended up splitting from here this is obviously the max we could create what is the total it's 1 plus 2 plus 3 plus 5 which is going to be 11. now we can we're going to try it multiple ways right it's possible maybe there could be a split over here of course this doesn't have any children so the most we could get doing that would just be a two but what about over here what if we ended up splitting from here so we took the left and the right from here we'd get a four and we'd get a five now if we did do that notice how this is going to be the top most node so whenever we split from a node we can't really get any of its parents or anything like that so in this case what is the sum of this path well it's going to be 4 plus 3 plus 5 which is going to give us 12 is greater than the 11 that we had previously so this is going to be the max path sum so you can tell that a brute force approach would be for every single node consider it being the topmost node and then from the left subtree basically find what's the maximum path we could create in the left subtree if we never split so we can't include both left and right and then do the same for the right side right and if we sort of do it recursively we can eliminate repeated work so suppose we're given that same tree we want to we're going to start at the root not like normal right so from here we want to know what's the max path sum we could do from here if we split from this position right going left and right now why start at the root when we could solve the sub problem first and possibly use that sub problem in the result at the root position so we're going to leverage that idea a depth first search idea just like usual with tree problems and using that we're going to end up getting a linear time solution and it's just going to depend on the return value of our recursive function so we're going to start at the root and now we're going to go left right we want to know what's the maximum path we can get from the left subtree if we never end up splitting so in this case it's pretty simple because it doesn't have a left child or a right child right so we don't even end up having to split and we get a sum of two from this spot right and even if we were splitting from here we would get a total of two so far so what we'll say is so far the max path we've gotten so far is two right now we still want to know what's the max we can get from this position so what we're gonna do is now go to the right tree so recursively now we're gonna ask the question down here what's the max path sum we can get if we ran it through this position and we ended up splitting left and right and by the way our result so far is going to be two that's the maximum path so far that we've gotten so from here we're gonna since we're trying to again find what's the max we can get splitting from here we're gonna go recursive and we're gonna do that for the left sub tree and the right subtree so we're getting that same base case here right with this left sub tree if we tried to split from here the max path we'd get is four because it doesn't even have any children right so let's keep track of that the max path we could get from here is four now if we didn't split here we'd also get that same value of four and that's what i'm marking here next to each note i'm marking what's the max we could have gotten if we did not split i know it's a little confusing and it'll make more sense when once i actually finish the rest of this example and so from over here now we do have what's the max we'd get from the left path without splitting it's four but now we just want to do that for the right side once again it's that same base case right so what's the max we could get running through here if we never split it would be five it doesn't have any children so we couldn't split even if we wanted to so now we're at this node once again we have computed the left and right sub problems now from this node we're going to be computing two different values by the way our result right now would actually be 5 because that's what we've gotten so far so from this position i'm computing two values i want to know what's the maximum sum we could get with a path running from here if we are allowed to split so we are allowed to go right and we are allowed to go left so what would the total of that be well of course we would just take okay what's the max we could get from the left subtree without splitting right because we can't split again if we already split up here we don't want to split again here so what's the max we could get from here if we never split well it would be four right and once again what's the max we would get from here if we never split it would be five so up here i'm going to take three plus four plus 5 and say this is the max path running through here if we are allowed to split now this isn't the value that i'm going to return to the parent the reason i computed this value is so i can potentially update the result right and we are going to update the result because this is 12 so far our result is five so we can say that our new result now is going to be 12. now what's the value i want to return up to my parent remember what this guy wanted to compute was what's the max it could have if it was allowed to split to the left and it was allowed to split to the right so from here on we don't want to split twice so the question of i have for this node when we're returning up to our parent is what's the max i could get running through here if we are not allowed to split so how am i going to get that well i can take this 3 and add it but then i have to look at my left subtree and my right subtree and take the max of both of these right i have to take the max of them i can't choose both so i have to choose one of them i'm going to take the maximum which is going to be 5 so i'm going to say 3 plus 8 that's going to be the value that we return so notice how for each node i'm marking what's the return value from that node going to be so it's going to be 8 in this case so then when i return back up to the root i'm going to say okay from here what's the max path we could get well i'm going to take the note itself 1 take the left which is 2 and take the right which is this path right notice how we don't split it's going to be an 8 which is going to give us 11. now that's not bigger than our result right so we actually don't update the result in this case and of course this is the root node so it's not going to end up returning to its parent but what if it did have a parent what would it return well we could only we would take one and then add it to the max of the left or the right of course the right is an eight this is the path so we'd say one plus a is going to be nine is what we would return to our parent that's the max path we can get from here without splitting what would that path look like well of course it would just be this right notice how this is a path it never splits so that is the main idea for this problem there's one last quick thing i want to go over so the return value of course is going to be for every node what's the max path without splitting and we are going to still calculate what's the max path with splitting and use that to actually update our result we're going to keep this as a global variable because it just makes the code easier but it's actually it is possible to solve this problem without using this global variable and by the way if you've been noticing we're only going to be looking at each node once so that's going to be a time complexity of big o of n the memory complexity of course is going to be the height of the tree which is usually log n if it's a balanced tree but one last case remember this tree could have negative numbers so for example let's say this was a negative four and this was a negative five so then from this left subtree we would return a negative four and from this we return a negative five so then you know when we're actually computing okay what's the max path that could run through here and let's say we're doing it for the one that we can't split right where we don't split so we either choose the left or the right and as i mentioned how we're doing it is we're just taking the max of the two right so in this case we would take the max of negative four and the max of negative five right and of course we'd say the max is negative four so then when we're up here what we would end up computing is three plus negative four which is going to give us negative one right negative one so what we would say is okay the max we could get here without splitting is going to be negative 1 but that's not actually the case right because th to get the maximum pat some from here where we're not allowed to split it doesn't necessarily mean we have to include the children right they're optional we could actually choose to not include either of these and that's what we would want to do because they're both negative anyway why would we want to include some negative numbers so when we're actually taking the max of the two we're actually going to take the max of three values we're going to take the max of the left right and potentially zero because if we just add zero to it this will stay the same so those are the key ideas i wanted to go over i think that is enough for us to dive into the code to solve this optimally so like i said we're going to have a global variable for the result and initially we're just going to set that to the val whatever value happens to be at the root so the reason i'm making it a list is because that'll make it for that'll make it so that we can modify it within the recursive function a little bit easier so we're going to have a recursive dfs we're going to pass in whatever root node we're traversing and that's really all we have to pass in so now the base case is that if we don't have a root like if the node is null in that case what we're going to return is just 0 that means we're not going to be adding anything and so we're going to be returning i just added a comment we're going to return from this function the max path sum without splitting so we want to get the max path sum so of course we have to do this recursively so let's get the left max and we can do that recursively just pass in root.left if it's in root.left if it's in root.left if it's null of course that's just going to return zero we're also going to get the right max passing in root.right so the first thing passing in root.right so the first thing passing in root.right so the first thing i'm going to do is compute the max path sum with a split from this root node so basically what i'm going to do is i'm going to take the root dot value and add it with the left max and the right max right because we are splitting from this root node now of course these left and right maxes could be negative so what i'm actually going to do before that is update them so we're going to set left max equal to the max of itself and 0 and do the exact same thing with the right max so it's going to be set to the max of itself plus 0. so here we're going to be computing the max path running through here so we're going to take the root value the left max and the right max add them together now this could potentially be our new result so let's see if it actually is so result at position 0 is going to be set to the max of itself or this value that we just computed so this is the part where we're actually computing what could actually be the updated result now what the return value remember of this function is not going to be the same as this the return value is going to be what we compute without splitting so the return value is going to be return root dot val plus whatever the max of the left max and right max is right because we can't choose both because if we choose both that means that we're splitting and so that's actually the entire function right you can see when we handle the recursive case well and we take the max of it and zero then we really just have two main computations we're doing right the max path sum with a split and the max path sum without a split of course this one is going to be the return value and after we're done with that all we do is call our dfs passing in the root and then that will update our global variable up above which is the result then we can go ahead and return that result and that is the entire function i'll run it and you can see that it does work now you might think it's a little bit cheating to even have a global variable like this and it's actually possible to solve this problem pretty easily without a global variable 2. i just didn't show it the main way you would do it is instead of you know computing this and updating a global variable what we could do is take we could basically return two values from this function so we would return the max path sum with the split and the max path sum without a split so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Binary Tree Maximum Path Sum
|
binary-tree-maximum-path-sum
|
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root.
The **path sum** of a path is the sum of the node's values in the path.
Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 6
**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
**Example 2:**
**Input:** root = \[-10,9,20,null,null,15,7\]
**Output:** 42
**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-1000 <= Node.val <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Hard
|
112,129,666,687,1492
|
35 |
okay guys now we get go to the 35th problem and he goes search insert position you're sorted Arrieta talking tell you it return the index if the target is found if not return the index where it would be if it was inserted in order so let's stop we will approach this dislike any search so H will be Nam stolen nice one while LS model equal to at children have and read equal to half plus h by 2 F nuns at MIT is equal to target done return net else if yes target is greater than or is equal to make password as I would've made thanks one and we are going to return out let's submit this and I'll put this correct right oh man yes if you like this ok that's it guys thank you
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,870 |
Hello everyone welcome, you are not my channel, okay why will it be easy because there are many similar questions, okay if you have made that then this will be made or if people have made this, then that is the similar question which I will give you now after some fear. I will give a list of similar questions, they will become and please keep in mind that such questions come in online assessment, a very similar question of this is to make cocoating, it has been asked in the online assessment of Amazon, it is okay to understand, it is not too fancy, in this you will get a floating That is, floating number has been given, inferior is fine, early access is either maximum, you can spend this much time, if it is fine for office life, then computer is fine for you to go to office, whatever other trains are available, you have to take those trains in sequential order. Ko also means first, like mother, look at the example, first take one, then take three, you have to take it, you ca n't skip anyone, okay, after that you are also okay, of length, where distance, I distance of diet train, okay. What is the meaning of what has been given? First train can do one distance. Second train can do three distances. Third train is your distance. Okay, this is what I have given. Train can only depart. Come and wait for us. So you mean it. You wait in between. Train right, understand what it means, like mother takes this is zero one, I have indexed it, if you have done the first train, this is the first train, neither is it doing one distance nor is it doing one kilometer, what is the distance? It is one kilometer, okay, the train is going at the speed of Tu, so how much time will it take to cover one distance, the time is equal to Tu distance by speed, it is 1/2, that is, it will take 0.5, by speed, it is 1/2, that is, it will take 0.5, okay, how many hours will it take, 0.5 okay, how many hours will it take, 0.5 okay, how many hours will it take, 0.5 When G is gone, you have covered this distance, now you have come here, but do you know the problem, this is 0.5, this is 0.5, this is 0.5, now you have the next interior inferior, that is, after 0.5, what integer will come, one will come, after 0.5, what integer will come, one will come, after 0.5, what integer will come, one will come, next wait inferior on it, you travel. You can do it, okay, you cannot start it in 0.5, it is can do it, okay, you cannot start it in 0.5, it is can do it, okay, you cannot start it in 0.5, it is okay to travel, what does it mean that even if you reach here in 0.5 over time, reach here in 0.5 over time, reach here in 0.5 over time, you have to start it just next, which will be the interior number, which will be the next waiting number of 0.5? It is not floating. Teacher is one. number of 0.5? It is not floating. Teacher is one. number of 0.5? It is not floating. Teacher is one. What is its C number of 0.5? If it is one, then you can start in one interior time. Right here, I have placed my zero point, I have covered this one distance and reached here in the second train. You have reached for but when can you start 1.5 over you must wait but additional 0.5 because 1.5 over you must wait but additional 0.5 because 1.5 over you must wait but additional 0.5 because who is the next waiting number of 1.5 you who is the next waiting number of 1.5 you who is the next waiting number of 1.5 you are either sell call it only 1.5 are either sell call it only 1.5 are either sell call it only 1.5 this you are fine before you can depot on the second Train is ok till now it is clear this thing was important ok now we have to say that return d minimum positive integer speed was which d train mast travel at u aate for u tu rich d office on time ok this has to be said tell us the minimum speed in which you You will travel, you will travel the whole train, you will reach the office, okay, so what speed did I take, what speed did you take, let's see, if you take speed and I go, then my answer is no, okay, what did I say, what was I thinking? I am not going to take the speed but you have given me the distance and I have given you how much distance. First you have given me the time of the train, then how much time will it take, how much will you have to wait first, that is, you are one hour later, you are lost here because what I said is zero point decimal number. You have to wait for integer next train, if you can board this then in 0.5 you have done it is then in 0.5 you have done it is then in 0.5 you have done it is good but you will have to wait for 5 more overs so that you can reach the integer number, so I took the sale of 0.5 so 1 Over means I took the sale of 0.5 so 1 Over means I took the sale of 0.5 so 1 Over means that you have already eaten one hour, okay, first distance is done, now let's come to the second distance, okay, what is the distance this time, if it is three, then how much time will it take? Time is equal to distance by speed, distance, what about me? What is the speed? So how much will it be? It will be 1.5. Okay, so what is the total time? 4 hours have gone. Okay, 4 hours have gone and it was reaching you in 6 hours, that is, good, that is, this speed is also correct. You will reach within 6 hours. Look, you reached within an hour. But in the question, it was asked that if you want to find out the minimum and minimum speed, then it is an obvious thing. Look, now a very important part is about to come. If you were at the speed of two, then your speed was two. If your train runs at the speed of 1000, then you reach in 4 hours. Any speed more than 2, why would people look at the speed more than 3 4 100 1000? I will check the speed less than 2. I want minimum speed, so I am in two speed. It was about to reach, so I was going to reach, in how many hours was it going to take, it's ok in 4 hours, I would like to check in lower speed, I want to find out the minimum speed, so I will check for one, if my speed becomes one So how much time will I take to reach, will I be able to reach below in an hour, okay, so let's see, if my speed is one, then what will happen, it is 132, what is my distance, 132 is okay and it is okay, how much time will it take, speed, distance, speed one, you are three. It will take five to six hours and now you will reach the office. How many hours did it take to get here? It was taking 6 hours. There was a limit of 6 hours so there is no problem, it means you will reach the office on time. It is fine but look at the advantage, what happened to you in Speed One only. You have look at the advantage, what happened to you in Speed One only. You have look at the advantage, what happened to you in Speed One only. You have reached the office speed, it is equal to one, you are in the office, that is, this is the minimum speed in which you can reach, that is why look at the answer, there was no one in the output, okay, I got the answer, I had reached the office but I am minimum. Due to speed, that's why I went left at 2 and why not right at 2. Why didn't I go at speed 3, speed 4? Because brother, I want max minimum speed and if I can reach at 2, then I will be able to reach at 3 as well. I will be able to reach, obviously it's okay, that's why I went to the left side, it's okay till now, it's clear, but if I go at the speed of two, it's okay and I don't know, mom, let's go, mom, let's take it took me 10 hours to reach, okay, mom, let's reach It will take me 10 hours, which means I will definitely have to increase the speed, then I will go to the right side, try 3 hours, try speed 3, if that doesn't work then I will try speed 1 and so on. If it's okay, then you will get a slight increase from here. You must have got it, you are looking at the speed, I am hitting the division in a way that if my friend could not be less than two, if my friend could not be less than the speed, then I went to the right side, okay and look here, if less than two. I had reached within 6 hours, so I went to the left side. I had understood that this is a question of binary search. You have kept the distance in the input and you have to find the speed, right? You have to find the minimum speed and so. Now we saw from one of our examples, the idea came to mind that this is giving us the instruction of binary search only, and this was our building of instruction, see, first we took two speeds, then when it became less than two speeds, then three. And why would we go towards the tax, if we want minimum speed, then it is on the left side or if the speed is not less than 2, then I go to the right side and we have to increase the speed, it is just doing a binary search, isn't it, remove it on the left side search. Given here, removed here, finished here tuition, understood, and see one more thing, because what I will do, I will say that I will start from the minimum speed and the maximum speed, how much fear kept, the power of the tank is 7 R = tanker the day after tomorrow. Okay, then 7 R = tanker the day after tomorrow. Okay, then 7 R = tanker the day after tomorrow. Okay, then I will find out the made and should I find out the L+R mines, as if I was finding out the time, no, it is at the speed of the made one, this is not only the speed, this is also the speed, this chilli too, so we have found out the speed, okay, now pay attention, what is the condition. Maybe what will I do when I reach office? I will store it in the result or maybe if I have seen a smaller answer then I will remove the right side. What have I done to the right side, made minus one equal to even clear? What is the second condition, what can happen that brother, if the speed at which I was walking is notary office, if I jump to the office, note rich office, then what will be the time for the office, then I cannot show this speed in the result. What does this mean, I will not try to travel at any lower speed because if I am not able to reach at this speed, then how will I reach at a lesser speed, if my office is fine then it means I will have to increase the speed, whatever speed will be the smaller one. If I am rejecting it, then I will increase L further, I will increase it till mid plus one, till now it is clear, okay the condition will come and till now I have not written the complete balance, the biggest confusion is this, what will I put in the wild, okay first. This is the confusion. What is the second confusion that if I do n't know what will be the return, then this is what I do every time to save myself from the return LR. I think I should have done the same in yesterday's question also, it would have been more clear. Well, in tomorrow's question also you can do the same thing by taking a result variable and storing it in it. The answer is ok, keep moving R wherever you want, ok and store the result in the last. So it is clear that I will not return the error, I will store it in the result, every time I will return the result, this problem of what to return is over, that tension is over now. This is the biggest tension. What to do here? This is the biggest tension. Look how well we will solve it. Look, I am taking this example to understand. Look, I told you this. Ville, I don't even know what I will put, okay, take out the med there, I know that we will keep L plus R mines and the power of R tank will be kept as 7. Maximum speed, this was also cleared and after that, this is what has to be checked, isn't it? If I take it in mid speed, will I be able to reach before 6 hours or else I will do it tomorrow, sorry function, I will do it tomorrow in the name of IF Possible, what will I check in it, brother, whatever distance is there, it is fine. Am I doing anything less than this speed? Is it okay now? What is my current speed? Say Made or Made, I have to write it as Mix Speed, it will be more meaningful. Made Speed. I have selected this speed now, so I will check that if If I cover the entire distance at this speed, then the total time taken will be less or equal. You are my inferior, which means it is very good, it means I have covered it in the same time or in less time, then what did I say? That I will store this mad speed in the result, but I will try to find out the minimum speed, okay, and if it is not so, if I walk with this mid speed, then I will not be within 6 hours, that is, not within the inferior hour. As far as reach is concerned in the office, now if I have to increase the speed then what will I do to increase the speed? Will I move to the right side? L = mid plus move to the right side? L = mid plus move to the right side? L = mid plus one. Okay, you have checked it here, so Meet, why are you checking again, then do plus one. No, okay, what will we have to return in the end, the result is okay and this is a possible thing, we will discuss it now after some time, but first let's focus on what will we put in the Ville condition. Okay, so let's dry and kill it. So if you hit dry then the value of L is one, the value of tank is R, the value of tanker is 7, so the day after tomorrow the tanker is very big, for now, for the sake of example, because of mother, we have reached 3, because of mother, we have reached R. If the value of key has reached 3, then it is ok, then its mid will come out. How much will the mid come out? One plus three minus one by you. Ok, so I will try two at speed. How much time will it take? Let's see the time is equal to distance in the result. Made speed in 400, what was the speed? If I am moving at your speed then I will reach within 6 hours. The office is clear till here, it is ok but what did I say that I send Made Mines One to R. Where did you send the mid-one, that is, you send the mid-one, that is, you send the mid-one, that is, you cleared it, you were there, I sent the mid-1 to R, cleared it, you were there, I sent the mid-1 to R, cleared it, you were there, I sent the mid-1 to R became one, now you are seeing that the value of R has become one, then both of them are now one, it is okay if you have seen in the result. Only two will be left, ok, do n't remember any pattern, do n't remember when to put it separately. Don't remember, friend, make a simple diagram from here itself, you have come to know that this equal is necessary, now see if it is coming, now this loop will work because Now it is equal to R, so now see what will be my mid will be one a, this time my mad will be one a, now I will see if it is possible at the speed of one, let's see the time passes, 6 hours are gone, so I have just given the result as one. Understand this thing, this time look at the result, I have updated it from one this time, but I said R and if we try to kill in low speed, then R has become made mines, so what has become of R, it has become zero. <= A raha hai one le dene equal tu zero hai <= A raha hai one le dene equal tu zero hai <= A raha hai one le dene equal tu zero hai otherwise he broke. The correct answer is stored in my result, I have returned the result in the last one, my answer is not to be done that yes, if such a condition comes, then if such a situation comes, then this condition has to be put, do not remember it anytime, it is okay, then this thing should be clear for us. Went and they talk about the function. They talk about the function. It is possible, okay, distance and medium speed, they send it. Okay, they send the distance, this is my speed right now, Maa takes it, I sent anything, then Maa takes it, send two, that's it now. We are fine, so we had to find out the time, so take the time equal to 0.0, for now it take the time equal to 0.0, for now it take the time equal to 0.0, for now it is okay, till now it is clear, now see what I have to do simply, but in this you are zero here, 0.5, 0.5, what is the distance. So, if this one takes the time of distance by speed, then 2x is fine. Pay attention, its ceiling delay is fine. The next train that you will catch is the next train, right? You can catch it only during the waiting hour, so if you take the current one then mother. Dub flat A is gone, so for that I have taken it for sale because I have to catch the next train. It is okay now mother, let's also take this flow. And if they can catch it in the interior only, then why has this also been converted into the ceiling, because the next chain has just become a child, now this train has become a child, now look, let's take the mother, if this feeling is the last one, then tell me yourself, is there any train after this? Is there any train after this, otherwise I will not convert it into ceiling, okay pay attention, I have explained it late in the example, but I have explained it to you like this, okay, the last train will be the one you have to convert into ceiling. It is not necessary because after that you do not have to catch the train, nor when do they convert it into sealing because whatever was the next train which is going to come is waiting for you, it is going to come later only, you can board it, hence feel in it. Used to give but after this, there is no train, so why do you convert it into ceiling, it is okay to leave the last train in decimal, then take it as n, here I take n - 1 and add it. I will give the n - 1 and add it. I will give the n - 1 and add it. I will give the bus last in time, which is Lesnar, which will be the last train, which will be in N-1 index, last distance, we will be in N-1 index, last distance, we will be in N-1 index, last distance, we will add it directly like this, how will we add time plus this is equal to distance by speed, which is the distance of last distance? N - 1 speed, whatever my speed was, my I had to N - 1 speed, whatever my speed was, my I had to tell a small thing, so I have explained this possible function completely. Okay, so we have learned everything that why is there a question of binary search, why is this the second question, we also understood the tuition in that because there is a question, what is the second condition, so that You should not have any trouble in the end, okay, it is very important, okay, I am just showing you similar problems and after solving this question, I want you guys to definitely make those similar questions, okay, so let's write it in the lead code. Let's code and we will also see the time complexity at this time. So let's code like this. Let's finish this question with binary. Okay and you must have found root force very simple. You see root force. I did not discuss it but it is quite simple. You have to give it in the question, right, your maximum time will be from one to power of 10, up to 7, okay, look here, answer bill note, power 7 of Exceed tank is okay, so now it's okay, now the speed. Try with one, if it is done with one, then your answer will be the same. If it is not done with one, then try with you. If you fall asleep, then the answer will be the same. If it is not done, then try with three, try with four. The tank kept going like this and 7 more. Try till if you reach the office in less than or equal to this inferior, that will be your answer because I am going from minimum to maximum, so the first one who got the minimum number got the minimum speed in which you can reach the office within inferior. This inferior variable has been given, in this it will be your answer, so now you can definitely try from root four, it is in the butt, its binary search was to be understood, I am fine and look, there are so many from similar problems, its cocoating bananas capacity, you shift package. Minimum number of days, make three buckets, magnetic force between two balls, allocate minimum number of pages, I have given the link to it here and you will get all these, you will go to my Github repo, there is a repo of binary search inside this repo. If you go to binary search, you will get this question, is n't this the minimum speed, you arrive on time question, you will get it there, I have pasted it there, it is completely fine, so I will remove it from here, you will get it there, okay? Let's start, what did I say, I have simply given, I will start from one, the minimum speed cannot be this much, okay and the maximum speed has been given, the power of the tank is 7, so 1 is e7, okay in the end, that too is clear to you. It has been done well, L+R minus speed is fine, sorry, no, brother, whatever time is taken, this can be my result, so the result is equal, mid speed is fine, but I will try to find a better answer, so R = Made. try to find a better answer, so R = Made. try to find a better answer, so R = Made. -1 See why you did not go to mid because -1 See why you did not go to mid because -1 See why you did not go to mid because I have already stored mid so there is no need to try it again in net speed and if it is not so then we will do L = mother underscore speed plus one. will do L = mother underscore speed plus one. will do L = mother underscore speed plus one. Okay why equal to mid speed? Didn't do it here because we have already checked the mix speed, it is not possible, why will you check the speed again, then we have done plus one here, okay, and in the last, what do we have to do, Ratan, return the mean speed, it is okay, now we just have to give the possible one. We have to write the function, what will it return to us, will it return the time in double, how much time is being sent here and what else are we sending, I have selected the speed is fine, now let's start, double time is equal to it, you will keep adding to it. Sir time is ok in 10 it is equal to distance till here is clear double t = time is equal to distance of I distance is by speed ok science we have sent in here so everyone will have to convert into double ok time is equal to distance By speed comes out, we have removed the time plus, we have to make it equal but we will add it every time by doing a cell. Okay, we do n't even need to check whether it is a decimal or not because what is the cell of one, it will be one. Okay, what will happen to the cell of 1.5? one. Okay, what will happen to the cell of 1.5? one. Okay, what will happen to the cell of 1.5? You will be okay, so if this is a non-decimal You will be okay, so if this is a non-decimal You will be okay, so if this is a non-decimal time, then it is one, so the number of one will remain one, so there is no tension about it, okay, we do not have to remove the cell of the last one, that is why there is a separate set here. We will write time plus this equal, here we just have to write distance, here N - 1 i.e. return for the last distance, we will write N - 1 i.e. return for the last distance, we will write N - 1 i.e. return for the last distance, we will write time here, okay and there is similar logic in cocoa eating bananas and whatever questions. Here is the complete code, it is possible that it may have been checked in some other way, in coquoting bananas and in different questions, everything else is ok. After submitting, let's see whether our answer is getting selected or not. I have made wrong spelling of scale, sale will be ok and here I mean speed by not result, our right result is not variable, it must have been clear to you to a great extent, see here, let me tell you what is time speed, time compressed, see here. But I am doing this tomorrow, okay, how many elements are there in total, there are elements between R and L, let's take the meaning of our search page which is that according to Beneshwar, people will search for you and all the time, N is going here. We are putting N * people here, the N * people here, the N * people here, the total will be N * people, it is clear till here, now total will be N * people, it is clear till here, now total will be N * people, it is clear till here, now you help me, there is any doubt, region de commerce, region tree, you help me next video, thank you.
|
Minimum Speed to Arrive on Time
|
minimum-speed-to-arrive-on-time
|
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
* For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark.
Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_.
Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**.
**Example 1:**
**Input:** dist = \[1,3,2\], hour = 6
**Output:** 1
**Explanation:** At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
**Example 2:**
**Input:** dist = \[1,3,2\], hour = 2.7
**Output:** 3
**Explanation:** At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
**Example 3:**
**Input:** dist = \[1,3,2\], hour = 1.9
**Output:** -1
**Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark.
**Constraints:**
* `n == dist.length`
* `1 <= n <= 105`
* `1 <= dist[i] <= 105`
* `1 <= hour <= 109`
* There will be at most two digits after the decimal point in `hour`.
| null | null |
Medium
| null |
1,827 |
Hello guys welcome song in two videos only according suggestion this problem dress ko minimum operation sukrauli increase the giver nitya re naam lai re naam se tire ko subscribe now to ki sadar distity increase so you can change account ok what to do is The difference between the two and the three to go to the first and not that Bigg Boss for the smaller NHPC Limited 600 What changed into two to zero difference between the two and two to two Two More Than 30 Two Convert This Point To Three Four Three Two Four 960 Subscribe Forward Screen To Take - 6 To 7 2108 Take - 6 To 7 2108 Take - 6 To 7 2108 Yo Honey 287 Calligraphy Brighter Clear All Song Sunao ₹100 Current Part Plus Song Sunao ₹100 Current Part Plus Song Sunao ₹100 Current Part Plus 7000 Subscribe Channel Subscribe To 154 Tiffin Yeh To Jai Siyaram Very Bandariya Ko International 180 To Retail Account Elections 2012 Elements To A Good Start The First President Of Units Dowry Element Don't Forget To Subscribe Problem No Problem You Love You Women To Wait For a solemn fennel i - 151 To Wait For a solemn fennel i - 151 To Wait For a solemn fennel i - 151 - numbers of units and its working o - numbers of units and its working o - numbers of units and its working o 200 ok understand example start working to give president o connected to the element in 2012
|
Minimum Operations to Make the Array Increasing
|
invalid-tweets
|
You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`.
* For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`.
Return _the **minimum** number of operations needed to make_ `nums` _**strictly** **increasing**._
An array `nums` is **strictly increasing** if `nums[i] < nums[i+1]` for all `0 <= i < nums.length - 1`. An array of length `1` is trivially strictly increasing.
**Example 1:**
**Input:** nums = \[1,1,1\]
**Output:** 3
**Explanation:** You can do the following operations:
1) Increment nums\[2\], so nums becomes \[1,1,**2**\].
2) Increment nums\[1\], so nums becomes \[1,**2**,2\].
3) Increment nums\[2\], so nums becomes \[1,2,**3**\].
**Example 2:**
**Input:** nums = \[1,5,2,4,1\]
**Output:** 14
**Example 3:**
**Input:** nums = \[8\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 5000`
* `1 <= nums[i] <= 104`
| null |
Database
|
Easy
| null |
4 |
in this video we are going to find the median of two sorted arrays this is lead code problem number four and it's a lead code hard problem and it has been asked in Google Amazon Apple Microsoft and many more interviews so let's see the problem statement so it says that you are given two arrays and these are sorted so you can see in the input 2 4 9 10 16 this is sorted similarly and nums 2 is also sorted and you have to find the median combined median of these two arrays so first of all uh let's understand what is a median so a median is number which divides a list of numbers into two equal parts so let us say we have one two three four so in this case uh if you draw a line between two and three so we can assign a value let us say the average of these two 2.5 average of these two 2.5 average of these two 2.5 so if you assume 2.5 is here then 2.5 is so if you assume 2.5 is here then 2.5 is so if you assume 2.5 is here then 2.5 is bigger than two elements and it's also smaller than two elements so uh it's dividing the array equally uh in this case there were even number of elements so the median that is 2.5 of elements so the median that is 2.5 of elements so the median that is 2.5 was not belonging to the set but let's say we have instead of a even number we have odd number of elements so let's say we have one two three four and five so now you have to find what is the number which divides this group of numbers into two separate groups so in this case three is the median because there are two numbers which are less than three two numbers which are more than three so it's dividing the uh array equally now this was the case for a single array now we have two arrays and we have to return just one median in this case it's 12. so uh what you do you would say that it's already sorted so in sorted array it's very easy if you have a sorted array you can simply go to the mid midpoint and that element will be the median if it's odd if it's even then you pick two middle elements and take the average so it's a o of one operation in case of sorted arrays if it's not sorted it will take off n time since you have to scan the whole array but in the case of two arrays you do not know you even don't know which array the median will belong to it may be in the first element first array it may be in the second array or it may not be in any of these arrays if the number of combined some of these elements is even so it's a trick a bit tricky here so first of all if you don't know the optimize solution you can always say that since these two arrays are sorted you we can use some concept similar to merge sort that is we put two pointers either you first merge them and then take the middle element or you can just keep a counter that here two is the smallest element so you know that here number of elements is one two three four five elements are here we have two four six elements so you know that there are 11 elements so five elements will be on the left of median there will be one median element in this and then five on the right of this so you have to find Which element comes sixth in this area so you can keep two pointers one here and one in the other one whichever is a smaller increment the counter one then you move this pointer here four and eight again four is smaller so you move the pointer here now eight and nine eight is smaller so you move this pointer so till now we have scanned three elements then uh 10 and 12 10 is smaller so increment this one four and then uh 10 and 12 again 10 is smaller and then 16 and 12 is smaller so you move this pointer here but in the counter you see that the value of counter is now 6 so 12 was the Sixth Element and you return the median so this approach will take o of n plus M time or divided by ah 2 because we will only scan till half and where M and N are the size of first and second arrays so m is the size of this one and N is the size of second array and we can do it without any extra space that is just two pointers so space will be of one but we can do better this is the brute first Force approach we are just scanning both the arrays so we have to use the fact that these are individually sorted and we will use that fact and try to reduce the time complexity so let's see how we can use the fact that these are sorted so uh in the case of single list what we were doing we were trying to find a partition which divided it into two halves all the elements in the left half were smaller than the median that is all the elements in the left half were smaller than all the elements in the right half in the case of two uh arrays also we have to pick all the elements of these two and move them in two separate partitions such that all the elements in the left partition is smaller than all the elements in the right partition so this is what is the goal so let's see so and also all the elements in both the partition should be same so if we have 10 elements here there should be 10 elements in the other partition also so we have to find such partition so it may not be that always possible that we find a partition in the middle of both those arrays so if you divide both there is into half and half then this array had M elements and this had n elements so the left part will have M by 2 right part will have M by two similarly here it will be n by two so combine some of this left part will be M plus n by 2 and so will be the sum of right part but this may not be the case always and we may have to shift this partition in both the uh arrays so let's see so this middle partition would be the simplest and ideal case but let us say uh these elements were a bit smaller on average than the elements in the nums too then maybe we may need to shift the partition a bit to the right so if we ship this Partition by one right then the number of elements in the left partition will increase by one so we have to move this partition one left by the same amount so if we divide in the middle exactly then clearly this is sorted in ascending order so these elements will be less than these right half elements and these elements will be less than the right elements in the first array so if we move this partition in the first array to the right we have to move the partition in the second array to the left so that number of elements in both the partition remains same so our goal is that all we keep all the elements to the left of partition in first array and left of partition in the second array in one partition and all the elements in the right partition of first array and second array in the second partition so this is the goal only thing is that we need to find the place where those errors should be partitioned so let us say we partition this array here ah let's say at 12 after 10 and in the second array we keep it after so let's see the number of elements here m is 2 4 5 n is 6. so there are 11 elements so number of elements in each partition should be 5 plus 6. by 2 that is 11 by 2 that is five elements would be in each partition so here we have already picked ah 4 and one of the partitions will have one more elements so in this case we will keep one extra partition in the left if this is odd number of elements so we will have one extra element in the left partition and the right partition will have one less in that case this element will be the median the highest value the max value in the left partition will be the median if these are even then both the partition will have equal elements and we will pick the max in the left partition and Min in the right partition and take the average so these are the only two cases so in this case it's even so we will keep one extra element in the left you can also keep the other way you can keep the extra element in the right partition in that case the final median will be the minimum of elements in the right partition so in this explanation I will be sticking to the first case that is we will keep an extra element in the left partition itself so instead of 5 we will keep six so we can add 1 here in the formula so M plus n plus 1 by 2 so this will take care of both the cases let us say we have 10 elements then we will have 10 plus 1 that is 11 by 2 that is 5 in each partition if we have 11 elements then it will be 12 by 2 11 plus 1 by 2 then 6. so this formula takes care of both the cases so in our code we will be using this formula to find the number of partition number of elements in Partition M plus n plus 1 by 2 in the left partition so we have to keep six elements in first and five in the second so if we partition it here so I am not arriving at the final solution but let us say the partition is here after 10 so we have already four elements here we need two more so in the second array the partition will be here so uh 2 4 9 10 will come and 8 and 12 these will come in the left partition and the other elements 16 19 20 22 28 these will come in the second partition in this case I have taken the solution only but let us say this was not the case so we do not know where the partition would be put that is what we have to find I am repeating again and again ah so let's say the partition was here two elements then we need four elements here so the partition would be 2 4 8 12 19 20. and in the right will be we will have 9 10 16 22 28 but is this partition okay no because we see that elements in the left partition 2019 these are more than some elements in the right partition so ah this the maximum in the let's say second array whatever is the second array the maximum here or maximum among these should be less than minimum among these elements so here the maximum is 20 so 20 is coming from this array so clearly we need to move this partition to the left so let's try here 19 and so this will move right to keep the number of elements constant so if in the second array we move the partition left it should move right by same amount so now let's try the new values and check whether it works or not so I am doing a Brute Force now then we will arrive at optimal solution so now uh three elements here so three elements here but 19 is again less than 10 so again we need to move this left so let's move it here and then this one will move by the same amount now we see that it's correct we have 2 4 9 10 8 and 12 which are less than all the elements in the right partition 19 20 22 28. but if we move it by one step at a time again the time complexity will be of the order of M the minimum among these but that is equivalent to uh in a way M plus n so this does not improve the solution by much now we will use the fact that these are sorted so instead of moving by one step we can use some sort of binary search approach so first we can take the partition in the middle ah so we have three elements and the other will be ah 6 minus 3 that is three so we have these two partitions now the maximum here in the first arrays would be less than minimum in the right of it's already less than all the elements in the right so no need to compare here and no need to compare in the left part since these belong to the same group so only thing that needs comparison is that Max in the left partition of first array should be less than or equal to Min in the right partition of secondary so this is one condition and also we need to compare that the maximum here in the second array in the left partition left of partition should be less than minimum of right partition of first array we do not need to compare with right partition of the second error itself since all the elements are already sorted and all the elements here are more similarly we don't need to compare with the left partition of first array since these belong to the same partition so the other condition is that Max of left partition of second array should be less than equal to Min of right partition of first array so these two are the condition if these two are satisfied then this partition is correct in this case it's not correct since 19 is not less than 10. so now we need to shift the partition how we will do that so we will follow the binary search approach so first we pick the middle element and that's coming from the binary search way of doing things so we know that if let's take a generic case so this is the partition in first array that is P1 elements on the left of this and P2 is the partition in second array that is P2 elements in the right of it and we know that Max L one is more than so uh let me draw it again so this is P1 number of elements in first array and this is P2 that means P two elements are here and Max of left partition of first array is more than Min of right partition of second array so minimal minimum element is here in the second array this one the immediate next element to the P2 and Max element here is P1 minus oneth element here so this is more than this element so this white one is more than the clo one so uh we need to move this partition left because this should not be more so the partition is too much right in the first array so in A1 we need to move the partition to the left similarly uh in the second array we need to move the partition to the right so in this case this was the left pointer so we were comparing with the middle element so again we can use the binary search way of doing things we keep two pointers left and right so left was equal to 0 and write was equal to m is the size of first error now we will move this right pointer to one left of P1 so now in this case if this is the case then we will make right equal to P 1 minus 1. because P1 cannot be in the partition because if it is in the partition then again it will be more than this so This our solution will be to the left of P1 so that is why right is moving there may be other condition of violation that this element here this is the maximum among left partition of second array and here it's the minimum in the first air so there may be case that this is more than this so what is this case its Max of L2 is more than Min of are one in this case ah this partition is too much left so we have to move the left to the one right of P1 by the same logic so in this case we have to change L equal to P1 Plus 1. and if the condition is satisfied this condition these two then the partition is correct we just need to find the this maximum Max among this left partition combined left and minimum the combined right and take the average or just the maximum amount the left partition depending on whether the total number of elements is even or odd also there are a few edge cases which we will see once we start writing the code or let's see it straight away let's take this case so in this case ah let's take the partition m is 4 n is 2 4 6 so total number of elements is M plus n is equal to 10 even so ah initially P1 will be here two elements and P2 will be here three elements because this will make five elements so number of elements in the partition will be M plus n plus 1 by 2 that is Eleven by two that is 5. so now we compare this Max here with Min here it's fine so Max L2 to denote the secondary L denotes the left partition of secondary is less than Min of R1 that is 30. so this is fine now the second condition was Max of L1 that is 25 should be less than equal to Max here Min here sorry Min R2 that was 8. but 25 is not less than it so this condition is violated that means this P1 is too much to the right so we have to move P1 left so now in this case let me erase it so here L was initially zero R was four and middle was 2 p 1 was P1 denotes partition one number of elements here P1 was two so this partition is too much to the right since it was more so we will make ah r equal to P 1 minus 1 that is one so now L is 0 R is 1 so the middle will be 0 plus 1 by 2 that is zero so partition comes here just one step this is a small example so it's shifting by one if it's a big array it will shift by half of this left part so now again here the partition will be shifted to the right so now we have minimum here is 22 and maximum here is 10 again the condition is violated that means this is too much to the right so shift the partition left again so now uh R will become so now L is 0 R was 1 so now R will become P1 minus 1 so P1 was 1 minus 1 that is 0 so both L is 0 R is 0. so partition 1 will be zero so there will be no element to the left of partition so all elements will be in the second partition so this is a edge case so in this case what is ah so here P1 is empty P 1 L is empty P1 R contains all the elements that is 22 25 30 34. and here the number of elements will be 5 that is 2 4 6 10. and eight so and in the right there will be just one element 15. so this maximum here is 10 Which is less than minimum here this is fine but for comparing this there is no element in the left part of this so what should we compare what is less than 15. so in this case we will this is The Edge case where there is no element in the left of any of these arrays partition so we will make it minus infinity negative of infinity in code it will correspond to intamin similarly there may be case where all the elements in any of these arrays come in left partition there will be no element in the right partition what we need to make this comparison so in that case we will have plus infinity or int Max in that case now I think we have covered all the cases let's start writing the code uh so first m is nums 1 dot size similarly n is nums 2 dot size so uh before writing the code let's also analyze the time complexity here so um we have two arrays first length is M second is n let's say we always find partitioning the smaller array you can also do it in the bigger array but it is wise to do binary search on a smaller since binary search takes log of n times so if n is smaller it will be better for us because once we find partition is in one of the arrays we know the number of elements in one of the arrays we can straight away know what should be in the left partition of the other array because we know that number of partition in each array should be M plus n plus 1 by 2. so we can subtract P1 to Find P2 similarly if we know P two we can find P one by the same formula so its better to do it in a smaller array so we find partition in a smaller array the middle point and then reject one of the parts and depending on whether this was less than this value or this was more than this value or we will either change the left pointer or right pointer so left will come here if that is the case or right will come here so we will reduce the size of this smaller array by half and again do the binary search so it will take log of M time where m is the smaller of this so we can write log of Min of M and N so if the first array is smaller we will continue if the first error is larger we will call the same function with numbers reversed so instead of A1 A2 we will call the same function with e 2 a 1. so that way the first element will all first array will always be smaller or equal now let us write the code so we will compare that if m is more than n then we will call the same function find median sorted arrays with nums to nums 1. else if this is not the case we will continue our logic so we will have L equal to 0 are equal to m and we will continue our search till it becomes more than right left becomes more than right and also this returns a double uh it returns because uh we may have to take the average of two middle elements in that case it will be a double value if M plus n is odd then it can return int but that is not always the case so while L is less than n we find the partition one equal to L plus r divided by two and similarly once we find this P2 is simple number of elements in each partition is M plus n plus 1 divided by 2 so this is the number of elements in each partition but P1 we already know number of elements in the left partition from first array so we have to subtract it here so that we can add the remaining elements so if you add P1 and P2 it should add up to this half of the number of elements combined number of elements so P2 plus P1 is this P1 will get canceled and it will remain so these are the initial partitions now we have to check our condition that uh Max in the left partition of first arrays should be less than Min in the right partition of second array so for that let's first find the max so we will write Max all right L1 is equal to so remember that there was a edge case where there were no elements in the left partition in that case it will be minus infinity so if P1 is equal to 0 in that case it will be int Min else it will be nums P1 minus 1. similarly we are finding a Min in the right of first array so again the same Edge case that there is no element in the right partition of first array in that case P1 will be equal to m so we have to take int Max else nums should be nums one first array nums one p one similarly the same thing for second array so left of second array right of second array P2 and this would be nums 2 this would be P2 now we have the value so we can check the condition if Max L1 is less than equal to Min of R 2 this is the first condition and Max of L2 is less than equal to Min of r 1. then we have found the partition is correct found partition so in this case again there are two cases if the number of elements were odd or even so if m plus n mod load 2 is 0 in that case we have to take the two middle elements that will be Max of Max 1 Max L one and Max of L 2 Plus Min of Min R1 and min R2 divided by 2 but we have to return a double so in case of 0.5 it will get double so in case of 0.5 it will get double so in case of 0.5 it will get lost if we do integer division so you can do either divide by 2.0 or you can explicitly cast it to a 2.0 or you can explicitly cast it to a 2.0 or you can explicitly cast it to a double but if the number of elements is not ah even then we have to just return the max in the left partition now if this was the case for correct partition if that is not the case then it may be violated two to one of these conditions failing so the first way of failing would be that Max of L1 is more than Min of R2 and there will be one more condition else that will be Max of L2 is more than mean of R1 so no need to write the condition since that is the only case left so if Max of left of first partition is more than Min of right of second partition then that means partition in the first error is too much to the right so we have to shift it left so in that case we will change the right pointer to point to P1 minus 1. and in the final case the other case is that the partition in the first area was too much to the left in that case we will move the left partition to the right of P1 and that's it let's see if it works or not uh so there is some typo here so we for missing the if case so else if so there is some error let's see so I looked at it and one of the errors I can see is that I forgot to change this in so let's see if it fixes the problem yeah it does solve the problem so at least it passes for this case now let's submit if there are any failures and it passes so all the test cases are accepted so this solution seems to be ok and you know the time complexities of minimum of log m so m is the minimum of the two arrays so that is the time complexity so if you don't understand it you can try to see the video again so the main concept here was that we are trying looking for Optimum partition in one of the arrays if you know the partition in one array you know the partition secondary since it should be divided equally so we know the elements in each partition so if the Crux of the problem is that if the minimum if the maximum in the left of first array is more than this minimum in the right partition of secondary that means this partition is too much to the right so we have to do a binary search in left part in the other case if the minimum maximum in the left of second array is more than minimum in the right partition of first array then that partition in the first air is too much to the right too much to the left we have to move right so this is the only concept here and every time we are ignoring half of the array so that's why it is taking log of M time
|
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 |
4 |
hello everyone welcome back here is vanamsen with another recording session and today we got something really uh special for you finding the medium of two sources errors but in Rust and you hear this right we are diving into rust for a crisp fast and safe solution to a classic problem so before we Unleash the Power of rust Let's Get Grip on the problem statement we have two sorted arise so uh yeah num1 and num two and our task is to find the median of the merge array while aiming for o log minimum between n and M so uh task is quite straightforward so given RF for example one two and second three four after the merge yeah so merging to we need to find a medium so medium will be two plus three so it's two and a half uh yeah divided by two in case of uh even number of elements and a middle element if the number of elements is odd so quite straightforward but how to solve it efficiently so before we dive into the code let's understand the logic behind the solving this problem so the key lies in the finding Perfect partition between two arrays and those conditions are as false so all elements on the left are smaller than all elements on the right and the number of elements on the left is either equal 2 or 1 less than those on the right and to find this perfect partition we will use a binary search but here is the catch we are not using it to find an element but rather a perfect partition a point in our all right so uh we will partition num1 at partition X and num2 at partition Y in such way that Max X and Max y will be the greatest element on the left side of the partition and minimum X and minimum y will be the smallest element on the right side so now let's dive into the coding so we need to make sure that num1 is the smallest array so let's start implementation so let's move table num1 and motel num2 and if num1 Len greater than num2 then num2 num one and else it will be num1 and num2 so why do we do this by ensuring number one is the smaller array we make our algorithm faster as we perform binary search on the smaller all right so now uh variables so let m n um one Len num2 Len and let moon table low table I 0 m so uh what are these variables so M and N are the length of num1 and num2 while low and higher will be the boundaries of our binary search now we need to perform binary search Loop so while low less than High let partition low high divided by 2 and let partition why m n Plus 1 divided by two partition X and let Max X if partition x equal zero minimum else will be Nam one partition x minus one so uh what's happening here so we are entering the realm of binary search and we calculate partition X and partition y to find the best partition and then we need to calculate max X minimum x max Y and minimum y so let's code it so let's minimum X be if partition x equal m Max else one partition and now let Max y if partition y zero minimum else num2 partition y and let minimum why if partition y and so max else num2 partition why okay so now if Max X less than minimum Y and Max minimum X so what we are doing here we are calculating the maximum and minimum elements on each side of the partition in both array and this will be a crucial to know where we found the right partition and last part is to validate and update a our code so if Max X is less than minimum Y and Max X is greater than Max why we evalidate our partition points and if they are valid we calculate the median otherwise we update our boundaries so if modulo 2 0 then return Max of Max why minimum four divided by 2 and else it will be return Max x max why s f 64. and else if our Max y greater than Max I will be partition x minus one and else now will be partition X plus one and close everything and zero otherwise if so we tackled a complex program broke it down let's test it to see if it's working for this test cases so hopefully it will yep so all good now that it's working let's submitted to see if all go well so yeah and as you can see we solve it yeah correctly in rest beating 100 with respect to runtime and also 25 with respect to uh memory so this wasn't just about a finding median this was a master class in algorithmic thinking uh so quite a nice program especially coding it and in Rust and as you can see performance uh yeah zero millisecond and 2.3 megabytes comparing millisecond and 2.3 megabytes comparing millisecond and 2.3 megabytes comparing to previous solution in Python 89 Mega yeah milliseconds and 60 megabytes so yeah rust probably is one of the fastest programming language so also good to know uh apart from Python and other programming languages so uh if you found this session valuable don't forget to hit the like button and subscribe for more tutorial challenges machine learning Tech and much more and if you have any question or suggestion for next episode uh please write a comment down below and also I will provide implementation in other languages like python C plus go in the description below and yep keep practicing stay motivated and happy coding
|
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 |
821 |
welcome to february's lee code challenge today's problem is shortest distance to a character given a string s and a character c that occurs in s we turn an array of integers where the length is equal to the length of the string and the answer i is the shortest distance from s of i to the character c in s if we have this example here and our character was e we can see that like the first position is going to be three because the closest e is three spaces away in the same fashion if we had this letter here we could see that the closest e would be two positions away um yeah so if we want to solve this straightforwardly one might think we could do this in some sort of nested for loop start with this position and just go throughout go through the entire string until we find the first instance of e so here like let's see with l we'll find uh move one two three so we'll go three two one once we hit e will be like zero and we can do that like in a nested for loop right but there's an issue with that because not only do we need to check everything from the right side we also need to check what's the closest e to the left side so that makes it a little bit trickier like we can still do it but we'd have to go from this position to the right and also this position to the very beginning but there's a very key insight that comes from that kind of thinking instead of doing it inside of a nested for loop what if we just went through one pass and stored everything from its left most that's going to be the distance and then everything from the rightmost which is going to be its distance so what i mean by that is if we started here we might say hey count up everything that we see until we see an e so it might be like one two three uh once we see e will go zero and then each time we increase we'll go one and it'll say zero one two three four zero so this kind of indicates to us how far the closest e is to its left side now there's an exception to that is these numbers don't count because there's no e right here that's kind of a mistake so instead of storing these numbers what we have to do is store some sort of like placeholder maybe the infinite number uh until we see our first e then we could start counting them up now we'll do the same thing but from the left side so this will start with zero and we'll say okay count up one two three uh and then four sorry that's not a good way to do this here and then so on and so forth counting up all these zeros but again the only exception to this would be if this didn't start with an e we had some other characters here like fff we'd have to make these like infinite numbers some sort of placeholders now if we have these two arrays or these two values all we need to do is store the minimum number between them and that's going to be the shortest distance from its left and the short distance from this right and we'll compare them get the minimum one the only one you need to be careful about is these uh initial numbers that don't have one to the right side so we can either skip all the way until we find the first one or we'll make some sort of placeholder which i'm going to use like the infinite okay so let's start by initializing the length of n which would be the length of the string and what i'm going to do is have three arrays i'll have the left the right and our output and each one of these are going to be the same will um let's see i guess we'll just make him none times n and we'll do the same thing for these two like this okay so the first thing is from the left side right uh what i'll do is first store i guess i'll call it temp i'll make it a float of infinite and we will say 4i and range of n we'll first check to see hey is this position is it equal to our c because if it is then we know that this temp value should equal zero otherwise update our left of i to equal the temp and then increase it by one and each time we see our character it's going to reset but the very big first ones because of this infinite aren't going to increase at all they'll stay the same now we want to go backwards we'll do the same thing but we'll go backwards for the right so four i in range of n minus one we're going to do the same thing but make it to the right side instead and i'll have to also should we set our temp to be infinite here all right so now we have our left and right now finally all we need to do is update our output for i and range of n oops make our output of i equal to the minimum between our right eye and left eye and finally just return that output okay so let's make sure this works now is that working three two one zero one two one zero yeah it looks like it's working let's submit that and accept it so time complexity wise is o of n and we're using some decent amount of space here so that's also o of n and the truth is you don't actually even need these left and right outputs what you can or arrays what you can do is update these values as you move along and then you don't even need to do this you can just compare its minimum between what we calculate and what's already in there but i want to do this to kind of illustrate better what's going on hopefully that helps so yeah that's it so thanks for watching my channel and remember do not trust me i know nothing
|
Shortest Distance to a Character
|
bricks-falling-when-hit
|
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`.
The **distance** between two indices `i` and `j` is `abs(i - j)`, where `abs` is the absolute value function.
**Example 1:**
**Input:** s = "loveleetcode ", c = "e "
**Output:** \[3,2,1,0,1,0,0,1,2,2,1,0\]
**Explanation:** The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
**Example 2:**
**Input:** s = "aaab ", c = "b "
**Output:** \[3,2,1,0\]
**Constraints:**
* `1 <= s.length <= 104`
* `s[i]` and `c` are lowercase English letters.
* It is guaranteed that `c` occurs at least once in `s`.
| null |
Array,Union Find,Matrix
|
Hard
|
2101,2322
|
381 |
how's it going guys with another video here in this video we're going to do number 381 insert delete get random of one duplicates allowed so this is a follow-up to a prop that i've this is a follow-up to a prop that i've this is a follow-up to a prop that i've also done on the channel so i do recommend that you guys go back and watch that if you haven't already because it is a very similar concept and if you really understand that i do believe that this is not actually a hard problem i would describe it as kind of more of an easier problem right so anyway randomized collection is a data structure that contains a collection of numbers possibly duplicates i.e a multi-set it should support i.e a multi-set it should support i.e a multi-set it should support inserting and removing specific elements and also removing a random element so you want to implement the randomized collection class randomized collection initiates the empty randomized collection object boolean insert inserts an item into the multiset even if the item is already present returns true if the item is not present false otherwise boolean remove removes an item value from the multi-set if present returns from the multi-set if present returns from the multi-set if present returns true if the atom is present false otherwise note that if the value has multiple currents in the multi-set we only remove currents in the multi-set we only remove currents in the multi-set we only remove one of them and into get random returns a random element from the current multi-set of element from the current multi-set of element from the current multi-set of elements the probability of each element being returned is linearly related to this number of the same values in the multiset contains so you must implement the functions of the class such that each function works on average of one time complexity note the test cases are generated such a get random will only be called if there's at least one item inside of the randomized collection right so let's take a look at the example here so here we're just initiating the randomized connect collection here we're putting one so one and we have a value of one in our list right and then we obviously return true here because there's nothing in there and then we have another insert here but this time duplicates are allowed so we're going to do here and then we're also going to put it in our list and we're still going to return false though because we are allowed to have duplicates here then we have another insert we're going to insert two then we have two here and then we have get random so get random here our probability to get it is we have three elements it's going to be a two out of third equals zero point six etcetera right so obviously they are getting a number one so balance of probabilities right and then let's see get random we remove one so let's just say that we remove this one doesn't really matter which one you remove at the end of the day and then now our probability decreases from 1 over 2 which is 0.5 right it's a little bit which is 0.5 right it's a little bit which is 0.5 right it's a little bit messy but you get the point there so that's exactly what's happening here so let's code the solution up now so what we're going to do is we're going to initiate our hash map as usual so what i'm going to do actually is this time i'm going to use collections dot default simply because i want to initiate a set here right it's going to make my life a lot easier and then obviously i want to initiate a list to keep track of what values actually have here so it's an easier way to look it up right so now let's go over the insert function so here we're asked to return true or false depending if it's already present but add it anyway so it makes sense logically that the first step is that we actually add it first we have to do some sort of a check at the end to see if it actually occurs more than once right and i'll show you how you do that so self dot hash map you have the value so this is our key value pair here dot add and we add the length of the self.list self.list self.list right because obviously we have the default dick here so it's going to be a little bit different from uh the just this your standard dictionary right then you have self.lifts.pen you're just going to add self.lifts.pen you're just going to add self.lifts.pen you're just going to add the value into the list to look it up and then here's where it's a little bit different from the other problem so what we're going to do is we're going to return the length of the self.hash map self.hash map self.hash map at the value right equals 1. so this is going to return true if this length is at one or false otherwise now what's the reason for this right because think about it we're adding this into the uh we're adding our values into the hashmap let's just say that we had one two three four five six for our list and we had our hash map here we had zero one uh one two dot you kind of get the point there but then we added let's just say that it was seven or no i'm just gonna add the same one so it's gonna be one and then zero one right we notice that if we take the length here at the value you see one and you see two so that means it's more than one that means it's going to return false and that's the reason why i'm doing it this way is since we're adding it we still need to add it because we're allowed duplicates but that's another reason why i use the default dick it would allow me to do this and it will allow me to check how many times it occurs inside of the array right so that's how it kind of works there so let's go to the remove one right so remove one's relatively straightforward here it's the same concept as 380 insert delete get random of one but without duplicates so let's code that up the only really difference is since you're using a default dick it's the syntax is going to be a little bit different right so if not self.hashmap self.hashmap self.hashmap value aka if it doesn't exist in the uh gray we're going to return false right and else last element equals self dot list negative one and index is equal to cell dot hash map dot value or not dot value but rather square brackets dot pop so self dot lists index is equal to the last element here we're just switching the uh two values like we did earlier so let's just say that this was your target value here you would want to switch the last element in this one and then once you have this one on this side then you're simply going to pop it out that's basically what i'm doing here right so self dot hash map last element dot add index and then now we have to pop it out once we've switched up our two uh our two numbers here no self dot hash map last element capitalize that there uh discard length of the self.list self.list self.list minus one basically i'm just discarding it from here the collections of default dick and lastly self dot lists dot pop and then finally we're going to return true and lastly what we have is our get random which is the exact same thing as uh before which is random.choice uh before which is random.choice uh before which is random.choice self.lifts because self.lifts because self.lifts because you know as our array gets bigger so does this length over here so there's really no changes and the probability there is just there to kind of uh confuse you right so random dot choice self.list and everything should work if self.list and everything should work if self.list and everything should work if i didn't make any silly errors here it does and we're going to click submit all right and there we go it's accepted and obviously this is an o of one solution and since we have to go through the array we have to create the hash map it is going to be an o of n space complexity right and then this is going to be time complexity so if you guys enjoyed the video don't forget to hit like comment subscribe really supports the channel leave me a comment tell me what you thought about it and i'll see you next time
|
Insert Delete GetRandom O(1) - Duplicates allowed
|
insert-delete-getrandom-o1-duplicates-allowed
|
`RandomizedCollection` is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.
Implement the `RandomizedCollection` class:
* `RandomizedCollection()` Initializes the empty `RandomizedCollection` object.
* `bool insert(int val)` Inserts an item `val` into the multiset, even if the item is already present. Returns `true` if the item is not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the multiset if present. Returns `true` if the item is present, `false` otherwise. Note that if `val` has multiple occurrences in the multiset, we only remove one of them.
* `int getRandom()` Returns a random element from the current multiset of elements. The probability of each element being returned is **linearly related** to the number of the same values the multiset contains.
You must implement the functions of the class such that each function works on **average** `O(1)` time complexity.
**Note:** The test cases are generated such that `getRandom` will only be called if there is **at least one** item in the `RandomizedCollection`.
**Example 1:**
**Input**
\[ "RandomizedCollection ", "insert ", "insert ", "insert ", "getRandom ", "remove ", "getRandom "\]
\[\[\], \[1\], \[1\], \[2\], \[\], \[1\], \[\]\]
**Output**
\[null, true, false, true, 2, true, 1\]
**Explanation**
RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1); // return true since the collection does not contain 1.
// Inserts 1 into the collection.
randomizedCollection.insert(1); // return false since the collection contains 1.
// Inserts another 1 into the collection. Collection now contains \[1,1\].
randomizedCollection.insert(2); // return true since the collection does not contain 2.
// Inserts 2 into the collection. Collection now contains \[1,1,2\].
randomizedCollection.getRandom(); // getRandom should:
// - return 1 with probability 2/3, or
// - return 2 with probability 1/3.
randomizedCollection.remove(1); // return true since the collection contains 1.
// Removes 1 from the collection. Collection now contains \[1,2\].
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 * 105` calls **in total** will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Hard
|
380
|
77 |
Hello everyone welcome you are going to do me channel ok lead code number 77 is medium mark but it is not medium at all ok the name of the question is combinations this is going to be a very easy problem because the template which is very family of back tracking is exactly like this OK, but today I will clear a very common confusion for you guys, we will solve this problem in two ways, and one of them is such that many people get confused, so I will clear it, so see. Before setting the question, let me first tell you why this is a question of back tracking. Everyone says that find out the combination and possible permutations. This type of questions are of back tracking only. Okay, so in the question it has to be said that you have been given two interiors. N and K you have returned which are k number of possible combinations. So you have 5 numbers i.e. one, two, three, So you have 5 numbers i.e. one, two, three, So you have 5 numbers i.e. one, two, three, how many possible combinations from five numbers. So you can do it as usual and as usual, how do we solve it? We will solve the traditional template of bag tracking, plus one mom important lesson which you will get today, okay, it is very important to learn that too and so that your confusion gets cleared from it, many people have confusion, that is me. I will tell you what is the confusion, okay, so let's start, then you will know what is our traditional way of back tracking, that we tag any element, okay and explore it, okay, then what do we do with this element after that. Then we reject it, we don't take it, we give it more, let's explore, okay, here also it is the same thing, we take mother from the forest, if there is 5 , the combination is okay, then look, you have the option here, right? If you choose this one, then one is gone in your list, if you take mother, you have taken it, then what will be left here, 345 means not two, it means here too, you can also take three. Even if you can't take it, there are two options for 3, that is, if you take 3, then 2 will become 3. You were already there and now 3 is gone, so the option is back, what is the option at 4 and 5, but K has become zero. Because you had to take only two elements, then one answer, you store it as dog, it will be zero, three, you can take two elements at once, then what happens is 2 becomes 4, then here it becomes zero, meaning. If you have taken your two elements, then this is your one answer, okay, and or if you had not taken the update from here, then maybe you would have taken three, okay, for the elements, you have an option, there used to be a template and that too. It used to be very simple, I will solve it, okay, so I will tell you where I am starting from, remember, I was told to start from one, right, I was told to start from one, and k is how much is and one is a temporary vector. Look, here in which I am appending the answer, I am taking a vector named camp, so I am taking a vector named camp, okay, I have a vector, it is clear till now, I did it yesterday, so now let us see. The most important thing to solve is to see that first of all, how should we write the base, brother, if k becomes zero, k = 0, what does it mean becomes zero, k = 0, what does it mean becomes zero, k = 0, what does it mean that you must have taken the elements of k, like look here, k becomes 0, then this is my answer. What will be the value of tempo? Otherwise what will I do? Whatever vector my result will be, I will push this time, I have pushed back this tempo result, I have stored it and I will turn from here, there is no need to do anything else. Ca n't take another element because it has become zero. Okay, if K is not zero, then what I said is that maybe you take this starting element, right, let's take the starting element. I was pointing to one in the starting. So you take it's okay, if you take it, what will happen, we will add it to the temp, that is, if we have taken the start, then we will send the start plus one forward and we have taken one element, then we will make it K-1, even if it is clear, then Now look here, pay attention, I said that here I have taken the start element and then explored the start element, but I had said that it is possible that I may not take the start, so I remove it. Removed it and even if I don't take it, I will have to store it. Okay, I didn't take it and let's explore that too. Brother, if I have n't taken the Start one, I will go to Start Plus One. And I haven't taken the helmet yet. Look, I popped it. Only the cake will be left, that is, we still have to collect the comments, we are sending more time, till now it is clear that this is my most basic template Okay, this is the most basic most of the people, meaning many people have used this one. You must have made sure that this one is not taken up, after not taking that one up, you have skipped ahead, that is, except for the start, it will run on start plus one. Okay, in the start, if the one on the start key would have been one in the starting, then I must have put one in temp. Then it must have flooded further, okay and look here, even after removing one, it became empty, after that, who has gone to start one in Star Plus, that is, they have gone to store 2, right, when the request will go, when this request will be given tomorrow. If it happens, then look here, now you will send me, look here, you are sending me, okay, again the thing with you, rest of you, whether I take you or not, then this one recjan tomorrow, here in the temp, there will be already one, so I will take you. If I take it will go to 12 A. It's okay. If I don't take it will remain one. If I take you, then it will go to R. If I don't take it will remain empty. Okay, it is clear till now, so basically the trick is that I am taking each element once and exploring it. Then I am rejecting it and then I am exploring. This is the most of D question. This is how the question will be formed. I also wrote two similar questions and as soon as I finished this question in the description, I made that and that, the name of one is permutation of one. The name is com, both of them are made up and will give a lot of confidence. Okay, this will be made from the template. Okay, now I will solve it also. I will tell you the time in TV. Look, what is the time complexity, pay attention. Clear the very simple time question. How many elements are there in total, there are many ways to select k elements and k elements i.e. many ways to select k elements and k elements i.e. many ways to select k elements and k elements i.e. do NCERT, we had read in school what is the meaning of NC, how many ways are there, it will give you i.e. how many ways are there, it will give you i.e. how many ways are there, it will give you i.e. infractorial by n - k * k factor. After that, we will come up with a second way to solve it, that too will be templated with back tracking, but it will not look like the standard, the child will actually be following this template, that is also a way of writing this template, but that Let me submit this to you first and then I will come to the second way. Okay, so let's submit it quickly, so let's do the court first way and solve it on our own. First of all, it is okay with the method I told you. First of all, I What I will do is to return a vector and print the vector, so I will create a vector named result here in which I will store my result and take a vector of internet in which I will store the temporary result which is the current result. I will store it in that, okay, let's start solving. I had given that you can take an element from one and up to one and till where tomorrow you can get it so that my starting element does not cross and K because we have to Only the same elements have to be picked, we will go on putting our result in another temp, what will we return in the last, we will return the result, okay, whatever is created at the time, we will go on putting it in the result, okay, this vector and temp is fine and I have already told you. It was said that if I become zero, it means that they have taken Kalamanthus, it is okay, put push back temp in the result and return from here, which is clear till here, after this and I had also said that the element which is start is your greater den. And if it is not there, then do not do anything according to it should be returned immediately, which is not there, we can pick up the helmets from one to more, okay, now let's do all the elements one by one, first, I am late, take team dot post underscore back start. Took and explored start plus one k minus one forgot a parameter here remember here we were also passing n right and n okay so here we passed n k - 1 because we have passed n k - 1 because we have passed n k - 1 because we have taken one element And after passing the temp, I have taken the element here and have explored it. If you want to see the possibility of not taking the element then pop the underscore back. Okay, I have taken it here and also popped it here and then Explore even later, okay Star Plus One will remain N and K because we have not taken the element. Look, the team has popped. Okay, I hope it should run. What we had explained is exactly what is written here. Look at its time. The constant is also very less, so see, this is what happens in the back tracking question, because see, their time complexity goes exponential, and factorial / can factorial / can factorial / can manage the factor in these, the factorial is fine, see, and did they have passed which date it is cases. We have made it in this way also and now there is one small thing which I want to clear for you, generally people are confused in the problem of back tracking whether we can make it anyway or not, so let's focus on that now. Now look at this. Second is the same, just the way of writing is different, it will be exactly the same but there will be a slightly different way of complaining about the same thing. Look, pay attention when we said that n = mother, let's take we said that n = mother, let's take we said that n = mother, let's take five, so we have 12345 and Maa, let's take K = 2. We have given Maa, take K = 2. We have given Maa, take K = 2. We have given Maa, so I told you that first you take both, then explore, then don't take the forest, and then go ahead and see what answer comes next, then if the forest is If you take it, then one A would go here, then it is exploring its solution, in which it will see what is there on 2 3 4 5, its ok, if it is my start, then you would have sent start plus one, otherwise you would have come here, then its After that, lay down one floor further, your recension is less, that tax is fine, if you take the mother, don't take the one, then the discussion starts from here, okay, so the one I had put in the temp, I am the one. Delete the delay and then try again, then you also have the option of not being late or being late, if you are late, then the vector of mine which was inserted earlier, you removed it and inserted it again and then you have to explore this too. He said, don't be late again, then I will be late on 3rd, so here you are paying attention to one thing, we are doing something like this, it is okay, we took the first start, and till how far can we take it, i plus, and then send it. What else was there that I would have sent it on time, this is what is written here, this is the one line written here, look at the two lines, actually this is what I have written, I have put one in the tempo and to store this which is my tempo, I have written it in this. I have taken one now, I don't take it means I will have to pop it now, I have also done the temp, after that whose elder will come, your elder will come, whether you take it or not, but look at me, he will reduce it, see, then write I plus. I found a way, we have written a loop on one, okay so don't get confused, both are exact and exact is the correct way, the thing is happening in both, it's just that the method is different but you can also write it with a loop, either do it like this and write both. If you dry iron then you will see this thing happening, I took Start, then Start is my one, later there will be Start Plus One, that is, you will be there and so on, if you do not take Start One, then I popped it and then in Start Plus. It means that I have explored you and then I will break up for you, then there is an option for you too that I will take you, then these two lines are only reducing my tomorrow which I am looking at. To do it tomorrow, to do it tomorrow, but he will run me for all the possibilities right here, I = for possibilities right here, I = for possibilities right here, I = for start, I = for star plus one, but never think that both the different methods are fine, so it is a simple thing, this one but with a loop. Also, let's code now and see if you pass the example desk and submit it or not. Okay, let's code this too. Then see, I will modify the code. What did I say, these are different when I write like this? But I write in the loop, only this part has to be removed, forint i = start i <= n, we removed, forint i = start i <= n, we removed, forint i = start i <= n, we can go till i plus, ok, after that I sent it to do i+1, ok, we after that I sent it to do i+1, ok, we after that I sent it to do i+1, ok, we will do n k - 1 because i We have will do n k - 1 because i We have will do n k - 1 because i We have taken it here, right, it is clear till now, after that we will do team dot, then again it will be i plus, then the value of start will become start plus one, then we will explore that also, isn't this thing clear? I did this by removing that and look, this formula is already taking care that the value of i should never be more than n, so we can remove this check, it makes sense, so let's run this also and see, something will pass. It is not different, we have put it in the loop and now do the dryer in. Okay, hold any one example, take a small example and see how to do this form progressive tomorrow, see if you will be driving by yourself, then you will There will be more information and it will help you, that's why dry iron must be done. Take a small example of the lake to see how the look is being made, how it is going and how the previous process is going on, okay see, this should also be submitted. Gaya Hai I Hope I am Able Tu Help Any Doubt Ho Reason in D Comment Area Tree Tu Help See Velen Next Video Thank You
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
1,573 |
uh hey everybody this is larry this is me going over the bi-weekly contest story going over the bi-weekly contest story going over the bi-weekly contest story force q2 number of ways to split a string uh so for this one um i made a mistake with the mod i just forgot to mod and that cost me five minutes of penalty um but basically the idea is um okay this is a very commetorical problem uh so i broke it down into two cases uh where okay they're all zeros what does that mean right um well and if you and this is very intro to combo torx but if you're not familiar with it or you just haven't practiced it then it could be a thing right so basically you know it's basically stars and bars right let me get a link up there uh classic stars and bars um and you know i'll put the wiki link in the comments below as well but basically here you want to put these dividers within these zeros right well you know that you can be you can't put one here or here so that means that given a length of a string of length n they'll only be n minus one gaps in the middle right uh because you know you could even do it inductively like if n is equal to two then you have one gap in the middle you have n is equal to three you have two gaps in the middle and so forth so then you just have to choose any two of them uh so that's how i got this one i'm counting zero and i forgot the mod so that cost me five minutes of penalty and then the other case of if there are ones well first of all you have to check that there is um there is a uh the number of ones is um it's a multiple of three because if it's not then you know there's no way such that the number of characters of one is in the same in three strings right i think that part is you know okay uh and then after that then it's just about um separating out so that each string um has that at the same number of ones so for example in this case there's six ones so that means that uh you know that the middle chunk also will have two ones and then what i did is that i just count the number of zeros to the left and then the number of series to the right because that's where you can place them uh place your divider again uh so now let's you know tokenize this for a second so basically now you know you have these things and then you could put the divider here or here and so forth right so the fourth place to do it for three zeros uh and three places to put up with two zeros so then um and that's pretty much it so then you multiply them together uh also cometorically um and that's basically what i did i just counted the number of left zeros and the number of right zeros and then i just multiply them and make sure i mod uh and that's how you do it um the visualization on this bottom i need to get a drawing but i know my bad but hopefully this is a good enough explanation let me know what you think you could watch me solve it live uh next hmm hmm um this hmm do you hmm okay oh messed it up hmm this way oh hey everybody thanks for watching uh let me know what you think about this format uh hit the like button hit the subscribe button join me on discord and i will see you next contest bye
|
Number of Ways to Split a String
|
find-two-non-overlapping-sub-arrays-each-with-target-sum
|
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** s = "10101 "
**Output:** 4
**Explanation:** There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
"1|010|1 "
"1|01|01 "
"10|10|1 "
"10|1|01 "
**Example 2:**
**Input:** s = "1001 "
**Output:** 0
**Example 3:**
**Input:** s = "0000 "
**Output:** 3
**Explanation:** There are three ways to split s in 3 parts.
"0|0|00 "
"0|00|0 "
"00|0|0 "
**Constraints:**
* `3 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
|
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.length. If you are still stuck with how to build prefix and suffix, you can store for each index i the length of the sub-array starts at i and has sum = k or infinity otherwise, and you can use it to build both prefix and suffix.
|
Array,Hash Table,Binary Search,Dynamic Programming,Sliding Window
|
Medium
| null |
1,026 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is maximum difference between node and ancestor so in this question we given the root of an binary tree we have to find the maximum value V for which there exist nodes A and B where V is the maximum difference between any two nodes so a is an ancestor of B so a should be higher in the binary tree compared to B only then you can take the difference a node a is ancestor of B if either of the condition is true if any child of a is equal to b or any child of a is ancestor of so for example eight has no ancestors three's ancestor is eight six's ancestor is three and8 Four's ancestor is 6 3 and 8 so as you can see you have to go up the order till the root the ancestors will be the nodes above them until the initial route now let's take this example and see how we can solve this question so this is the tree given to us let's calculate the difference between every combination and see how we can improve that so8 8 is the root right it has no ancestors so 8 - 8 root right it has no ancestors so 8 - 8 root right it has no ancestors so 8 - 8 is equal to 0 so that is the maximum difference for three there is only one ancestor so calculate the difference 8 - ancestor so calculate the difference 8 - ancestor so calculate the difference 8 - 3 is equal 5 so this difference is equal to 5 now let's calculate the left child of three it has two ancestors 3 and 8 let's calculate for three so 3 - 1 is let's calculate for three so 3 - 1 is let's calculate for three so 3 - 1 is equal to 2 so that is the difference and 8 is another ancestor 8 minus current value 1 is equal to 7 so the distance between this and this is equal to 7 now let's calculate for the right hand of three it has two ancestors 3 and 8 so ancestor minus current value so 3 - 6 is ancestor minus current value so 3 - 6 is ancestor minus current value so 3 - 6 is equal to 3 8 - 6 is equal 2 so this equal to 3 8 - 6 is equal 2 so this equal to 3 8 - 6 is equal 2 so this difference is three and the difference between and this is 2 now four has three ancestors 6 3 and 8 let's calculate the first one 6 - 4 is equal calculate the first one 6 - 4 is equal calculate the first one 6 - 4 is equal to 2 so this is 2 next we have to calculate for 3 ancestor minus current value 3 - 4 is = 1 so this difference is value 3 - 4 is = 1 so this difference is value 3 - 4 is = 1 so this difference is 1 next 8 - 4 is equal 4 so this distance 1 next 8 - 4 is equal 4 so this distance 1 next 8 - 4 is equal 4 so this distance between 8 and 4 is equal to 4 now we take the right side of 6 there are three ancestors 6 3 and 8 for 6 - 7 is equal ancestors 6 3 and 8 for 6 - 7 is equal ancestors 6 3 and 8 for 6 - 7 is equal to 1 so this height is 1 3 - 7 is equal to 1 so this height is 1 3 - 7 is equal to 1 so this height is 1 3 - 7 is equal to 4 so the is distance between 3 and 7 is 4 and the third ancestor is 8 so 8 - is 4 and the third ancestor is 8 so 8 - is 4 and the third ancestor is 8 so 8 - 7 is equal 1 so the height distance is 1 now we go here it has only one ancestor so 8 - 10 is equal to 2 so this so 8 - 10 is equal to 2 so this so 8 - 10 is equal to 2 so this difference is 2 now we calculate for 14 it has two ancestors 10 and 8 so first 10 - 14 is equal to 4 and then 8 - 14 is 10 - 14 is equal to 4 and then 8 - 14 is 10 - 14 is equal to 4 and then 8 - 14 is equal to 6 so this is 4 and this difference is 6 next we have to calculate for 13 it has four ancestors 14 10 and 8 so 14 - 13 difference is 1 14 10 and 8 so 14 - 13 difference is 1 14 10 and 8 so 14 - 13 difference is 1 so this is 1 10 - 13 difference is 3 so this is 1 10 - 13 difference is 3 so this is 1 10 - 13 difference is 3 so this distance is 3 next 8 - 13 that this distance is 3 next 8 - 13 that this distance is 3 next 8 - 13 that difference is five so this difference is five out of all these the difference seven is the maximum that is the difference between 8 and 1 8 - 1 is difference between 8 and 1 8 - 1 is difference between 8 and 1 8 - 1 is equal to 7 so that is the maximum difference that is the output which is expected here now here in this case we are calculating the combination of every note how can you improve this so you can make one observation that there is no need to compare all the notes so here you will find the difference between 6 and 4 is 2 and the difference between 8 and 4 is 4 so here there is no need of calculating this combination because there exists an ancestor which has greater value 8 value is greater than this ancestors value so the difference between that current node and this node is obviously going to be greater which is four than this combination which is two so you have to pick ancestors with the maximum value and minimum value so that you can eliminate a few calculations so here in this case let's see what all you can eliminate let's start from the top 8 - 8 eliminate let's start from the top 8 - 8 eliminate let's start from the top 8 - 8 is 0 so there is no need to eliminate anything here in this case there is only one ancestor 8 so we can't eliminate anything here in this case Min ancestor is three and Max ancestor is eight so here in this case Max an of four Max of 6 3 and 8 which is 8 and Min ancestor of four is min of 6 3 and 8 which is equal to 3 you have to calculate this difference and you can eliminate this difference because this difference is greater as you can see so this you can eliminate the calculation so there is no need to compare this you can remove this calculation now let's check this we need two calculations Min is 3 and Max is 8 and here also you can eliminate something there is no need to calculate this difference again because there is a minimum value less than six so Min ancestor of 7 is equal to 3 here and Max ancestor of 7 is equal to 8 which is here since the difference 4 is greater than 1 there is no need to calculate this ancestor so you only have to calculate the Min and Max ancestor for every node in that path so you can remove this calculation similarly in this case you need this calculation you need this Cal calculation so this is min ancestor of 14 is equal to 8 because Min of 8 and 10 is 8 and Max ancestor Max among 8 and 10 is 10 so you need both the calculations and from here you can eliminate one calculation Max is 14 so you need this and Min value among all these three ancestors Min ancestor of 13 is equal to 8 because that is a minimum value so you can eliminate this calculation here there is no need to perform that calculation because the difference between 8 - 13 is 5 difference between 8 - 13 is 5 difference between 8 - 13 is 5 difference between 8 - 13 is 3 since 5 is greater than 3 - 13 is 3 since 5 is greater than 3 - 13 is 3 since 5 is greater than 3 there is no need to do this calculation so you can remove this and if there are more nodes here you can remove more calculations this node here for example you can calculate only the Max and Min ancestor until that note till the root whatever is min ancestor and Max ancestor and only compare those two values and rest of the between values there is no need to calculate the difference among that because it will be between the range of these two values so there is no need you will get the maximum difference using only these two values so that is the main idea now let's code this and debug the code coming to the function given to us this is the function name and this is the root given to us first let us create our output variable as a global variable because we also need to use this inside the elbow function I'm going to name it Max difference inside the function I'm going to initialize it with zero because that is the max difference until now and now if root is null we can directly return zero as which is the max difference until now so if root is null return zero or Max difference is zero so you can return Max difference now we call the helper function which will take three parameters I'm going to name it helper it will take the current route will take the maximum ancestor and minimum ancestor since root is8 it doesn't have any ancestors but for the next left and right side this will be the Max and Min ancestor so pass them so current value of the root is going to be the Max and Min ancestor initially for the next iteration and finally I'll return this Max difference as the output so this is a void helper function it won't return anything but it will update this value since it is a global variable the updated value will be returned now let's create that it is a private function so it does not return anything the return type is void and let's copy this and this is a tree node let's name it root this value should be the current Max ancestor so I'm going to name it current Max and this value is the current minimum ancestor so this value will be keep on updating inside the so these values will be keep on updating inside the helper function so for every node we have to update the current Max ancestor and current Min ancestor from that node until the topmost node so inside this helper function we can only process the ancestors values only if this root is not equal to null so it is important to check this if root is not equal to null only we have to process if root is equal to null it will directly skip it like for this node does not have any children left or right side so we have to end the recursive call here now inside this we calculate the current difference so I name it a variable current difference so it will be the max value of we have to calculate two values so for every node we have to calculate two values Min ancestor and Max ancestor difference with the current node so current node minus so root. Val minus so current Max ancestor and root. Val minus current Min ancestor so we have to calculate this value and maximum among that will be the difference so for example in this node we calculated the Min difference that is the Min ancestor minus current value and Max ancestor minus current value and maximum among that is three because Max of 3A 2 is three so for this node this will be the max difference and here as you can observe we have to calculate the absolute difference for every difference so place this values inside map. abs and also here now we have the current difference for every node there will be a current difference like for example this value difference is zero this node difference is five this node difference is three that is a Max difference this no's difference is seven this no difference is four so every node has a current difference and our final answer will be the max difference among all the nodes which is seven in this case so we have to update our Max difference so max difference is math. Max of current Max difference and current difference and now we have to update the current max value for the next iteration so current Max is the current Max ancestor so max ancestor is eight so we have to check so map. max of current Max or that no value so for this node the max ancestor is eight and for the next iteration we have to check if it will remain eight or it will be this value so this value for this iteration is root. Val right so we have to check with root. Val now let's do the same for current Min we have to update the Min among the current uh Min and root. Val so after debugging you'll know how the process is happening and now we have to call the helper function for the left child and right child of every node so helper so first let's call the helper function this is a recursive call for the left child first rot. left and current Max and current min so these will be the updated values for the next iteration so I'll copy this once and do the same for the right child so root do left will become root. right and the rest of the parameters are the same function will be returned here and max value will be updated which is returned as output let's run the code the test case are being accepted let's submit the code and the solution is accepted so the time complexity of this approach is of n where n is the number of nodes inside the tree and the space complexity is also of n uh there will be n recursive calls where n is the number of nodes inside this now let's debug the code inside an ID so I've taken the same function and I created the same example one as a tree and I place two break points here to debug the code so let's start again so we pass the entire route so the current node value is eight now we calculate the difference so current Max and current Min is eight because they have been passed here ask root. Val so current Max and current Min are updated to eight initially now current difference is zero because 8 - current difference is zero because 8 - current difference is zero because 8 - 8 is 0 and 8 - 8 is 0 Max among them is 8 is 0 and 8 - 8 is 0 Max among them is 8 is 0 and 8 - 8 is 0 Max among them is zero so current difference will be updated to zero so current difference is z Max difference is also zero Max difference and current difference are zeros now we have to update the current Max are also same eight and8 they will remain same now we are calling the left side so we finished processing eight we got the difference as zero now it will go to the left side so we have to calculate for node three so in the next iteration node value is three now current difference is 8 - 3 and 8 - 3 so current difference is 8 - 3 and 8 - 3 so current difference is 8 - 3 and 8 - 3 so 5A 5 Max is five so current difference is five now current Max is initially eight so that is the max ancestor right so 8 is the max ancestor and current Min is also eight because this node has only one ANC so those are the Min and Max both so max difference is five now because that is the difference so here 8 - 3 is equal to the difference so here 8 - 3 is equal to the difference so here 8 - 3 is equal to 5 so that is the max difference until now in the next iteration root do V is one so it will go to its left child in the next iteration now we have to calculate max ancestor Max ancestor is eight so it has two ancestors right Max of 3 comma 8 is 8 and Min of 3A 8 is 3 so these are the two ancestors 8 and three so first it will do 8 - 1 which is three so first it will do 8 - 1 which is three so first it will do 8 - 1 which is 7 next it will do 3 - 1 which is two and 7 next it will do 3 - 1 which is two and 7 next it will do 3 - 1 which is two and Max among them is seven so seven is the max difference which is between 8 and 1 so that is what is going to happen now current difference is seven because it calculated this and picked Max among them so ma. max is 7 so 7 is the current difference now we have to update Max difference is five current difference is seven you have to pick them maximum among them Max among them is seven so this will be updated to seven so here as you can see Max difference is seven so that is right till now the difference was five here and we have difference seven so max among five and seven is seven so max difference is seven now we have to update the ancestors current Max is eight it will remain eight current Min is three and current nodes value is one so current minan is one so it is updated to one here in this case if they had any children for this node the max ancestor is going to be the value of 1 3 and 8 which is 8 and Min will be Min value of 1 3 and 8 which is 1 But Here There Are No Children it will go back and it will pick this node next as there are no nodes here this value will be returned as null so here as you can see they returned as null it has gone back to three and now it will pick its right side is six so right we are processing this element now pick the max is 3A 8 because of the two ancestors Min is 3A 8 so it will pick three the difference is 8 - 6 which is 2 three the difference is 8 - 6 which is 2 three the difference is 8 - 6 which is 2 and 3 comma 6 which is 3 Max of 2 comma 3 is 3 so max difference is three and it will check with the current Max difference Max of 7 which is current Max and the difference is three right and this will stay seven so that is what is going to happen current difference is three so as you can see we have got three now it will check with the max difference Max difference is 7 and current difference is three it will remain seven so max difference is still seven so here Max difference is still seven and we update the current Max is current Max or nodes value which is8 current minan is three and node do Val is 6 minus three so it will remain three so similarly it will happen for all the uh notes and finally Max difference will remain seven because here the max difference is 2 here the max difference is six between 14 - max difference is six between 14 - max difference is six between 14 - 8 which is 6 and here the max difference is 5 which is 8 - 13 5 among all this 6 is 5 which is 8 - 13 5 among all this 6 is 5 which is 8 - 13 5 among all this 6 5 2 0 3 7 and here 4 and 4 so all this Max is still seven which is this so 7 will be the output so let's forward this and see what the output is so here as you can see 7 has been return returned as output that's it guys thank you for watching and I'll see you in the next video
|
Maximum Difference Between Node and Ancestor
|
string-without-aaa-or-bbb
|
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105`
| null |
String,Greedy
|
Medium
| null |
96 |
today hell they are today's legal in challenge questions but unique binary search trees so we have a positive integer number n that stands for the number from 1 to n integer number sequence 1 to n that we want to store using a binary search tree and the question is basically asking us to account the number of structurally unique binary search trees that can do this job store the number from 1 to n the example we have a number equal to 3 so we are looking at a binary search tree to hold the value 1 2 & 3 here in the example the value 1 2 & 3 here in the example the value 1 2 & 3 here in the example part it shows you the five total distinct structural structurally distinct a binary search tree that can hold the value of 1 2 & 3 hold the value of 1 2 & 3 hold the value of 1 2 & 3 since they are 5 antonio we return 5 so that's the question how we're gonna solve this notice that basically depends on the choice of the rule node the question can be breaking to three different smaller problem right so if we choose one we're gonna count to the number of structurally unique binary search tree when one is picked up as a root and it's going to be the same or a similar question for if we pick 3 to be the rule note what's what are the number of structurally distinct binary search trees that can do the job and to so and so forth basically we're just gonna divide the question into three different smaller problems and add those numbers together so let's think about one particular example if we pick let's be a little bit large than 3 here 1 2 3 4 5 if we pick some middle numbers 3 as a root node for this product how many structurally distinct a binary search tree are there if the Swiss picked us the real node we start to think about we need to think about the property of a binary search tree the definition for a binary search tree is actually kind of recursive if a pick node randomly pick a node inside the binary search tree of course the rule who did the letter subtree has to be a another smaller binary search free bodies no smaller no larger than the parent low the right subtree has to be a smaller binary search tree with the largest value no smaller than the parent node so if I pick 3 as the root note the left subtree has to be a binary search tree with two values and the right subtree has to be a binary search tree with another two values so we can get the number of trees from both sides by just calling this function with a smaller end and then basically just to return those two x together because you have to twice on the left hand side you have two choices on the right hand side then the total variations you can have is 2 x 2 that is 4 so just going to put it down here so we're just gonna add total to be left and multiplied by light and that we're basically just gonna do more rules in range 1 to 5 the right-hand side is range 1 to 5 the right-hand side is range 1 to 5 the right-hand side is exclusive so 1 2 5 we're gonna do this so yeah so that said basically we divide the problem into n different a smaller problem and each problem it's going to be two recursive call because once we pick the root we break this number line into two sections and for each of the section you have to be we have to build a binary search tree to hold that many different number of names we basically can use the function recursively to get to the number of ways and solve the bigger problem so before we actually kind of go about and cut this I just got to think about the base case a little bit the basic case is basically if we have the root to be the very first note that means the left-hand very first note that means the left-hand very first note that means the left-hand side then left the subtree is totally empty that's just the one choice one variation one more pointer so number of trees zero is gonna be one and also it's very easy to reason that if I just have one tree one no to form a binary search tree there is just one variation so this is this two at the base case yeah so what's this I think I'm good to go to cut this thing up so here the first line we handle the base case then we initialize a variable to accumulate to this total and we're just gonna pretty much just gonna copy the pseudocode here we need to figure out the number of nodes on the left-hand out the number of nodes on the left-hand out the number of nodes on the left-hand side which is going to be so the two basically if you look after that and that's the root subtracted by one so that's the route sub factor by one right is going to be we have another two in this particular example which is equivalent to and if I subtract the choice of the root 5 subtract 2/3 that's choice of the root 5 subtract 2/3 that's choice of the root 5 subtract 2/3 that's equal to the number of those on the we have to form the right subtree which is also a binary search tree so it's n minus root and our total is incremented by those two multiplied together in the end we're just gonna return this total it should be the solution but notice that we're gonna have a lot of duplicated calculations inside this recursive function cause so to improve the runtime and do a memorization we start you should be a memorization version top down solution let's see if it works okay I have to add at least here so that's a the top-down solution let's so that's a the top-down solution let's so that's a the top-down solution let's look at how we're gonna solve this from Barnard so basically we can see what we are doing here using a loop is to break this calculation let's make a separating line here and that's equal to some of some helper function over a choice of route and at the total number or rules in range 1 to n plus 1 and we can see that the helper function is basically this real line here so we translate the helper function definition here which is gonna be calling this but with a smaller input smaller number so root subtracted by one multiply that by and subtract the root so if we substitute this helper function definition back into this formulation what we get is you know just directly copy this and replace that would get a double loop here sum which is yeah sorry I'd say this is a single loop we sum up over the for loop over the real choice which is from 1 to N minus 1 to solve this we basically see that to get the number for a larger input we have to first calculating this number smaller number of trees so we can solve this by you know populating this two first and just using this formula to gradually populating the number sighs 1d array here so that would be the bottleneck approach so that's gonna be a for loop from zero to n to gradually populating the of this 1d array and every iteration in every iteration of that loop we will be a nested for loop to go from the choice of the rules and looking up at the prior calculated number and populating this new number so that's gonna be the one another approach so it's gonna cut it up a really quickly I'm sort of like a rush now because I have closing the yard and it's a started raining really terrible yeah so they're just gonna call this number please and it's gonna be zero and we'll pre-allocate and plus one location pre-allocate and plus one location pre-allocate and plus one location because we have to deal with a lot of trees from zero to n and the base case the two case here so the Lupus kind of populating the and from because we already populated zero and one we just go from 2 to n and inside each iteration here we can enumerate over all the possible choice for the route that's going to be by and basically just enough of this I to increment this by the two branches so that's going to be I subtract a lude subtract the lawn right the reason being that sorry this is the number of nodes we are looking at and this should be left and so we iterating over this one less than that then here is the left the right-hand side is basically I subtract right-hand side is basically I subtract right-hand side is basically I subtract I left a subtract the white so yeah that vest should be the relationship and we just gonna return the basketball does it work nope jeez doctor hurry yeah so this is the bottom up I have to go
|
Unique Binary Search Trees
|
unique-binary-search-trees
|
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 19`
| null |
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
|
Medium
|
95
|
1,678 |
hello everyone and welcome to another short video on solving a lethal problem with apl today we will be tackling problem 1678 gold parser interpretation now what the problem statement says is that i'm given a string and the string consists of the alphabets just a single letter g open and closing parenthesis and then open parenthesis a l close parenthesis in some order and the objective of the problem is to take a string that consists of these three let's call them tokens and then interpret them into th this thing right here so g's stay asg's an open and they close parenthesis should be replaced with the letter o and then open parenthesis a l closed parenthesis should be replaced with a l and they give us a couple of examples as per usual so this right here should be interpreted to go and this right here to go and this thing right here to whatever this is i'll go log i'll go look or something like that yeah so let's see how to tackle this in apl and let's take this example to check our solution as we go along so let's see my string is going to be this my character vector in apl and i think the at least to me the thing that i the solution that i could come up with first or immediately is to use um regular expressions so these are the three patterns on the left and then i can use quad r for replace and then i can type in what i want these to be replaced with and then i just apply this to my string except this is definitely not what i wanted what the hell did i do um oh right of course these need to be escaped because these are parentheses sorry about that so yeah okay so the thing is parentheses have a special meaning in regular expressions so i need to tell apl or the regular expression that i want this parenthesis to be interpreted literally and that's why i'm escaping them with the backslash so this is the i think this is the first solution that comes to mind and then obviously we don't need to replace g's with g so we can just remove this from here and actually in fact we don't really need there's something else we don't need to do so or there's an alternative way to tackle this and it will segue nicely into a another solution that doesn't use regular expressions and that is if we have this pattern we replace it with a l sorry the other way around so if we have this pattern we replace it with o and then we just need to remove the remaining parentheses from the string so we just drop them okay and this is interesting because now we can write another solution that doesn't use regular expressions it just looks for the open and closed parenthesis it replaces it with a no and then drops every remaining parenthesis because we don't care about them and now don't judge me too hard but i'll show you the very long it's not very long but i'll show you the little lengthy solution that i came up with and then i'll show you the proper apl solution that makes better use of the primitives and what i'm about to show you is kind of wait what this should be rotating the string a not the two rotate so this is not rotating the string why is that because i need to do this of course so might as well just write this like that so what yep okay so now what i'm doing is i'm taking this string and i'm putting it on top of the one rotate of the string so i'm shifting things one um one character to the left and now the idea is that i can check when the first row is equal to the open parenthesis and when the second row is equal to the closed parenthesis and when they are aligned for example here now i wonder if i can select these two things vertically i can't so the open parenth is so is aligned sorry with the close friend right so this means that at this position we have an open and close parents so what we can do is we can compare these things so we want to check for equality but now we want to map each of these characters so each of these scalars to each of the rows of this matrix and a row here has dimension one that's why we are using the rank and now all we need to do is see or find the locations where the ones are vertically aligned so it's an end that's applied vertically and these are the positions of the o's now what we do is we use this to let's call this a mask a boolean mask or mask and now we use this mask to replace the open parens with an o with the at operator now the open panes were replaced with os and now what we can do is we can drop all remaining parenthesis because we don't need them now i was i wrote this down and i was fairly happy with it and then suddenly struck me i was being very silly because apl has this primitive that you can find right here and it's called find and you can give it a pattern and a string and it will it doesn't need to be a string but you can give it a character vector two character vectors and it will look for the pattern given on the left in the whole array of the right and so this is the exact same thing we did here but much easier to read and so this mask that we are trying to compute here we can actually do it with find so what we can say is that well can you please find the open and close parens in s except i did something wrong right i need to parenthesize things because i'm a new so this is a this right here is it asset function and then we apply everything to s so let me just show you so what this tested function does is let's call it find parens and that's just this right and now fp on s gives you that and now the at operator can take a replacement scalar on the left and then a boolean function on the right and now what it does is it applies the boolean function on s to determine the positions where the o should be inserted so that's what's happening and then finally we drop all the parentheses that we don't need with this piece right here and we are using the without function and the commutes to avoid even more parenthesis so this is equivalent to having the without right here and so that's well that's it our solution is just the the dropping all of the parentheses that are left after we replace the o's in the positions where there's an opening and the closing parenthesis that's consecutive so that's it that's our solution let's see i only have simpler examples left but we can give them a go and so sol on this string right here gives us a goal with a lot of o's and the simpler test case the simplest sorry the simplest test case it's just gold and yeah well that's it i hope you learned something and i hope this also gives you or teaches you the lesson of always think about like the primitives that apl has to offer right i was thinking about this problem and i immediately came up with this solution and as it turns out i was just being very silly because all of this was replaced with a single primitive the find primitive so yeah take your time to get accustomed to the primitives that apl offers and feel free to comment any questions you might have or alternative solutions you might have and if you do comment those um on youtube um take the time to write a couple of maybe sentences explaining what it is or whatnot because when youtube finds a comment with too many apl glyphs and two little english texts it thinks it's i don't know maybe some weird kind of spam and so it deletes them automatically it's not even me it's youtube deletes the comments so while i try to fix that issue try to write comments that contain letters i guess yeah and other than that i'll see you in the next video bye
|
Goal Parser Interpretation
|
number-of-ways-to-split-a-string
|
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
|
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
|
Math,String
|
Medium
|
548
|
837 |
hello hi guys good morning firstly oh God questioning the complexity of this question the understanding the HK says the things which are being involved you can see Mass probability DP sliding window edge cases like this question is going to be us yeah before further Ado let's start with this uh like I know the video is bit late because uh it took a lot of time to actually make these notes which you can see down below so basically what I do is actually make the notes for you guys so that you can refer to it just as a at a glance you don't have to go through the entire video to actually go and have a look at a specific part of video which you like you want to refer later so if you don't know the sheet is coming up in that sheet you can add I have a notes column you have like you can just add a link there of the sheet and it will be good but yeah uh well for that let's start with the question itself new 21 game so it's a standard Booker game uh it's a standard game uh in casinos and Club so it's a 21 game in which you have to go close to number 21 so let's see okay how this modification is um because it's a new game right game so cool uh Alice plays the following game Loosely based on the card game name 21 cool Alice starts with zero points remember Alice which starts with zero points and draws a number and she will draw a number while she has less than K points and basically she will draw the number until she has reached K points at each draw she gains an integer number of points randomly from the range from 1 to Max points because as we say okay he she will draw when I say he she please because Alice can be he and she also so here is she but I've seen in code forces a few times at C so yeah uh Alice uh while she has less than K points she will keep on drawing and basically what she can draw from one to Max points number of uh points cool uh where Max points is an integer cool each draw is independent and outcome have equal probabilities which means at any point of time she has an option to draw any of the points from one to Max points right if she draw let's say one two let's say eight so the probability of 3 to draw and probability of 4 to draw a five to draw or six to draw or one to draw or eight to draw is all same and what it is equal to one by eight so probability of drawing each number so how we find the probability okay number of favorable outcomes upper number of total terms of outcomes number of favorite outcomes is one drawing and number and say number of all the outcomes it can be it from one to eight I can try I can draw any number it is the reason how you find the probability of drawing a number out of the range from one to n provided all have equal chances of coming up cool that is the first part as soon as we read the question you will find okay it is a probability which is being asked to you cool Alice stop drawing when she gets K or more points good as soon as Alice reaches a point K or more than K she has to stop good we have to find the probability and as we were seeing above also we are finding the probability and stuff uh we have to written the probability that Alice has n or fewer points okay Alice should have n or fewer points cool and for ultimately at answer probability so it's in double so we have written the answer in 25 like but we were simply written the form of a double but cool we have to find the probability of if Alice has n of your points now we will just go on okay how this is all happening but ultimately what we saw here is okay every number from one to Max points have equal probability of coming up and that is 1 by that number of points which is Max points cool and as soon as the points go more than equal to K we have to means Alice have to stop Alex and all we are on the same team so we will play accordingly and also we have to return the probability that she has n or fewer points and when she will stop at K points and has to accommodate up till the end points so I have to find the probability sum from K to n points cool we'll go into examples as we look but let's start with a quick example which we think of ourselves a way of example if let's say n is 25 which means I have to find the probability of finding 25 or lesser points case 21 which means as soon as the points reaches to 21 Alice has to stop maximum points which means Alice can pick any points from 1 to 3 at each draw which means a card having written okay one two or three Alice can pick any of these cards out of three cards cool now if Alice has to start from zero Alice has three options to draw one two or three so basically current point of Alice is zero Alice as soon as she draws one card her point will become one or she can draw a card of value from Two and she can draw a value of a car of value three her point will become three so it is one card is drawn cool one card is drawn but Alice has many options because maybe I'll say Okay Alice can go very like as many times she wants it's just that okay the K it should loss it should be as soon as the K becomes more than equal to 21 which means as soon as the points you have becomes more than equal to k then you have to stop the points are three one two if we don't have to stop right because it's less than 21 so I can just go out again now at this point when Alice had only one point right now she again has three options okay she can have one two and three as a card she you can choose so the new points will become as two three and four again for this two she would have three options so the new um points would have become three four and five for the three she again has three options it will become four five and six you saw kind of a trees becoming okay at one option at One Step At One card drawn I have three options of cards one two and three and how it is okay because of this Max points now at another next step I again build an entire tree out of all these points and again some new points are being formed and it will just go on and go forth something like recursion you can see here okay cool for sure and also we can see okay the points are being drawn but we'll actually look on to it later but yeah now we can just imagine okay how this is actually coming up because I want the points I want the probability that Alice has n or fewer points so basically I have to find the probability of every point from K to n so probability of K plus 1 K plus two up till N I have to find the probability so for every point I have to go and say okay what is the probability contribution of that point cool now we have to Output the probability we have to Output okay we saw something it would look like this we can easily find the probability but let's think of what edge cases we can have so see firstly we can have a rough idea as soon as we had a rough idea now we will think of hes okay um when we see how HKS okay it is very less very much Beyond some exceeding limit like this okay cool now we have three variables n k and Max points Max bonds will not affect us n or k can only affect aside maybe Max Bond can affect us we will see it but if we just look at it when a threshold because K was a threshold because as soon as the points which is K or more than K as it has to stop initially Alice has a zero point itself and his and that is the question saying okay K is 0 which means threshold has reached Alice has not even started and she has been told hey stop because you have reach your points but also say okay I have not even started what are you doing that is the reason Alice which means we have reached the threshold so basically we can't even start the game that is the reason the probability to get n or fewer points is one you will say Aryan but it is not even possible to reach any points at all because we were starting at this hero our points I reach was Zero but I will say you're not even you 21 started the game if it had been that okay you started the game and then you were not able to reach end points then I would have said okay your probability is not one it is something else it is zero or anything but you did not even get a chance to start the game to actually reach any point at all thus the probability is one always consider that without even trying you can never say that you failed which means if let's say I say okay um I failed but I did not even gain the exam how can I fail that's reason if you just give the exam only thing you can feel without giving the exam I can't say you failed that is the reason the probability at k equal to 0 for sure she has no score at all it was saying okay find the probability of n or fewer points she has no points at all but still she was not even given the chance to start the game that is the reason for the probability at k equal to zero is one it's a way very important case now okay cool that was an amazing Edge case like it's very hard to think right but it's not the only one if we look at the examples itself and go back okay um K is one okay for sure Alice got a chance at least to draw one card but Maxim points which means Alice can draw any card from 1 to 10. but okay I was saying Okay can Alice you reach any card which means because I have to find the probability that Alice reaches n or lesser points n which means 10 or lesser points and yeah at one as soon as my card value becomes one or more than one iron to stop but at least one I can put which means okay as soon as I put a card as one two three four five six seven eight nine ten at all these points my value reaches one or more than one so basically I have to set up a step stop at all these points but as all these points which means maximum points was 10 so I can put any card value from 1 to 10. and at first step itself which means as soon as I step one card my K limit get exceeded so I have to stop but ultimately I was able to achieve all 10 cards all 10 points and I was asking okay hey what is that okay you can achieve 10 or lesser points yeah I can keep 10 9 8 7 6 which means I can achieve all the points that is the reason probabilities one so it is one such case that Q will have to find I will just make it generalized but it is okay if you are able to achieve those points which are required then for sure you are good to go which means and how you will say Aryan uh what all points I can achieve because see it was said that you have to stop the game at K points which means you can continue the game at K minus one points when I say continuous game which means you can draw any card at K minus one points I can draw any value of points to add in my number which means any card any value I can add and what is the value I cannot I can add one to up till the max points which was given so basically at the last step I can achieve a maximum value of points as K minus 1 plus Max pts which is the max point so basically the maximum value and let's say this maximum Max points right now I have considered it as a Big W but maximum points maximum hours maximum point you can achieve is K minus 1 plus W right now if I say okay maximum voltage you can achieve right here is this now I am asking you hey if n would have been here up till or more than it which means maximum points okay it is the maximum achievable points and basically n is beyond that so basically all these points I could have achieved let's say it is the points from 1 to up till n k points it has to stop but K minus fun points it can still have a chance to go to maximum value it can reach and maximum value it can reaches by adding the maximum number of points so maximum points reachable for this person Alice is this which is K minus 1 plus W it didn't ask max number of points it can achieve which means these are the reachable points right out of and I am saying okay hey Aryan uh what is the probability of n or lesser points then I have all the reachable points which I wanted right I have all the reachable points I will see probability of finding uh achieving analysis points it's one because I have all the points right what I wanted I am not counting the unnutable ones because it is never reachable and I'm going to want that at all that is the reason at k equal to 0 you will also see that okay those were not even possible because I didn't even start the game that's the reason you have all the reachable points you had for sure your probability is one which means your n is more than equal to which means okay you have reached the points and because your option was to get n or more n or lesser points and for sure uh you have all the original points with you then you will say okay if n is more than equal to K minus 1 plus this W is the max points thing if it is then I will just return a 1. these are the two edge cases and one also for sure is if I'll just show you that okay if n is less than k then also you have to just return a 0 because but in the question it's always given that n is more than K I'll show this particular part but these are the two major education which you have to consider I'll explain them very well now going on to actually a big example that okay the above thing which we saw okay how it is actually valid again um it is okay k equal to one which means okay I can place any card any value but as soon as it passes a value more than cat to stop so I have maximum points as 10 so basically at one step I can put one two three up to ten so basically all the reachable points are 10 but I was only capable of six points which means I wanted to see for six points but reachable points were 10. I am asking for six points six by ten consider I only considered the reachable points at the bottom in this example your reachable points were 10 right now as soon as this n would have been let's say 12. here you have to put that edge case above that okay number of reachable points you have you can just get those visible points and here the reachable points were actually 10 but I have one to only six so the probability of getting those six or lesser points is six by ten because both 6 and 10 are reachable points cool now you got the edge cases so basically this is which I showed you n is more than equal to K minus 1 plus w k is equal to zero then you have to return a 1 because game didn't even start at all and you're good uh if n is less than k um for sure which means that I have to find the probability of finding points n or fewer points which means n of your points the probability of that but I can't find the probability until unless the games ends and game ends at K points if n is less than K which means the game never ended which means that I cannot even find the priority of that cool that's the reason I will just can't find that it's probably zero but yeah it is not the case ever because RK is always less than equal to n so it is not the case but yeah it is minus case if you have your interview lined up cool now coming back to the actual example we have considered the HKS we have got now coming back okay earlier in the initial we saw the recursion happening kind of thing and we know okay kind of we find that if we want to find the probability of contribution of every number how many times it's coming up what's the contribution of that number so for sure um number is being repeated in the recursion three we know that okay DP is being applied but you will see how we take the example again back n equal to 22 equal to 21 Max points as three now I need to find the probability from what I told you from K to n because it is the n or lesser points which means n is 22 lesser points up till it is 21 if it had been any let's say 20 or something then I would have put it like this but right now I took the example like this okay n to K I will just add the probability which means my final solution will have the probability of getting the number as n minus 1 up till the k right cool it is my final solution which I need to have now as we saw in this earlier question team what was happening we can easily see that a point because see I just want to find the probability of n or fewer points which means if I need to here find the probability of let's say this 0.4 so this point 4 is being contributed 0.4 so this point 4 is being contributed 0.4 so this point 4 is being contributed here also and here also for sure I have to find the contribution of each point now for the probability of reaching that number I here I showed you four now it can be via multiple ways because it's a tree and buy a tree you can reach a specific point by multiple ways that is the reason this okay it's a recursion and as we have the same problem being repeated again that's the reason we can see we can apply our DP here no I just for sure okay it's a recursion tree looks like and we have to find the DP and it's a it will be actually easy when we just see okay it is being repeated and we just want to consume that same value again and again how let's see it's much better let's define as DB State DPO file now it is the probability of reaching the number I as we saw okay we can reach this number 4 we can reach this number four now with this number 4 what other number I can reach off you saw a Fibonacci series you saw uh the frog jump series like the question of frog jump it's exactly the same which means I can reach a number I don't remember I can reach I plus one I plus two I plus Max points this is the number I can reach so I will Define my DP status the probability of reaching the number I now if we come back to our example and take the then any point let's say 14. if I want to find the probability of reaching my number 14 I can use the existing probability stored in my DP consider the fact okay let's say my DP has a value stored consider the fact that my DPA has value stored I can just go and check but quickly what is the DP of 30 which means the probability of getting the point as a 13 and after that drawing a value as one because 13 that's when we become will become a footy so I would say what is a probability of reaching 13 and then a drawing a card with a value one or adding a value one out of options available are three which means option available are three one two or three that is the reason it is the probability I am just marking and stating every word it is the probability of reaching 13 which means getting the points as 13 and then the drawing one value card out of three cards probability of reaching 12 and then drawing two value card two valued card not two values two valued card which means I had one two and three other values right two valued card out of three cards probability of reaching a point in 11 and then drawing a point three a valued card three out of three points now as I say the probability of drawing a one card out of three cards it's nothing but one by three and as we know the cards will be Max points cards so in total it will be one by Max pts that's the reason you will see that okay I just put a one by three out of here and I'll just replace that with one by Max points that is you can reach to any of the probability because you remember that the DP of I is the probability of reaching the number I that is how you can Define the recurrence relation or the simple relation that okay DPF I minus 1 which means reaching the I minus one card but then you know you have to draw a one value card which is one card with a hobby with having a value one out of all the max points cards uh then reaching this particular value and then drawing a car of value to because it is just one card of value two and then out of these points cards and ultimately I can just repeat the same process I just repeat it I just showed that same thing firstly by values this all things are by values considering this example and then I transform into a general surface it is very important to actually move in like this way because it actually help make it easier to understand stuff and also for you to write in the actual competition contest or away or interviews also so please go via values and not directly as okay I just show you what is DP for I minus 1 I minus 2 and up to I minus Max points it will not help you at all so step by step will go around it will help you now I have this dpfi I'll just bring all the max points of I sorry Max points of i as out and it is simply if I just say okay this one to up to Max point that is nothing but if I just say I have the pts points so basically my PT is it goes from one until the max points I want the answer for DP of I minus PT where my PT goes from 1 until the max points point just remember this because in DP I am taking my DP of I minus PT I will just use this later on so please remember this part now this condition was already looks good you have a DP and then because of that to reach that EP of I you are using the existing dp5 machine I must Ms Max points but is it this simple that okay or there's something else involved in this particular condition of finding DP there is something else if you just look closely in the starting and ending when I says which means your see your DP is nothing but an adding right now if you have an array for sure this array is okay starting from the value 0 and go up till the max points because ultimately you want to figure out the max points now for this starting with the zero and you are considering all the values earlier and also Max points which means Max point is bounded by n and K so for sure something would might have happened in this any K or initially in the zero that's the reason I will just check back if I want to find let's say because you remember ultimately I have to find the sum of probability from K to n because it was the probability of finite points lesser than n or lesser points right which means ultimately have to find the probability from n to from K to n if I just take an example of finite probability of 22 let's say which means finding the 22 points then relation I would have grabbed DP of 21 into one by three it help you after 20 into one by three and if you're 17 it is I would have done by remember what was the meaning of this it was the meaning that okay reaching the point 20 and then drawing a value 2 reaching a point 90 and then drawing the value 3 it is reaching a point 21 and then drawing a value one but my game itself ends at 21 which means the last point I can jump from is the 20 itself and not 21 I showed you also if I have these points my K game ends the last jump I can make is from the K minus one so which means 21 I cannot make any jump I cannot use this one that is the reason if you just remember this part I showed you it is DP of I minus PT so basically your I minus PT should be less than K only then you can actually use that part to actually jump to your next dpfi you can use your DPF I minus PT to jump only when it is less than K because if it is equal to or more than k then for sure you cannot use that for jump because your game has already ended before that is the reason you have to just do this one condition in if condition while just having this uh your DP statement you have to add this if condition but is it the only thing okay Aryan you showed this part which is at the end part but also we have seen uh some starting but also comes in if it's a linear array some starting part also have an edge case so yeah that is also the case if we are finding let's say DP of 2 then we would have DP of one DP of 0 and DP of minus one what does minus one represent reaching a minus one point and then jumping three steps minus one point you can never reach that is the reason although you can just pass in as 0 so but still I'll just recommend just not consider it as at all just say okay your this value was I minus PT so I minus PT should be more than equal to 0 only then you will consider that value that is the two cases which you will have to add in your for Loop while calculating your DP and that is all you know everything now the two base cases which you show above the proper relation of uh Loops to find the DP and the DP cases also you know the main case of uh DP and also the two if cases if conditions of that DP now let's quickly look go and look back at the code as simple as the possible uh firstly the two Corner cases which I showed you the one corner case where n is less than K is not there because we are given that K is always less than equal to n so that is not even cool now I just go and find the max points possible and I know that okay K minus 1 is the last step that I can reach I can just add Max points to that so basically ultimately number of Max reachable points are Max point right now it is my DB which will store okay the probability of reaching that particular number I and for sure I will just try with every of those points start searching its Max points now initially to get the um points as hero as I'm starting with the zero itself so the probability of reaching a point zero is actually one cool um then I just go and pride of every of those points which means from one to the max points I try for every point I now for every point I you remember to find the probability of a point I you need to do a i minus PT where p t goes from one up till the max points you remember this part right then I'll simply just repeat the same stuff I have this I will do the I minus PT where p t goes from one up till the max points and I'll just do the I for I'll do I minus PT and into one by Max points I showed you that part also one by Max points it is I minus PT it is 1 by Max points cool it is repeat same for same stuff but also saw the if condition should make valid I will only and only do it if I minus PT is more than equal to 0 which means this condition I my speed is more than equal to 0 and also foreign calculated and then ultimately you know remember I have to find the probability of n or fewer points which means K up till N I have to find the probability that's the total probability of key up till n thus I will just go up till K to n and simply find the sum of probabilities and the probability of every point from K to n just add that and return in my answer but the complexity of this you can see is simply Max points you are just going on to the uh you are simply your or you can simply go up till n also it is simple as that it is no worries at all um so it is kind of that okay if it is from because you can if Max points is more then also no worries but secant simply go up till these Max points and then you can simply find out or here also you can just put a condition of n but it's simply n into max points which you can have in your answer at Max and both are like kind of funny four so no words on that part also which ultimately show you that okay complexity will be around 188 which um although in very best case it will not give because it's just a border for complexities it's just the border of complexity so a few times it can give a few times it cannot but in legal it gives but yeah we cannot force optimize it uh much better space is all of maximize because we are using a Max points array but we can first optimize it um how we can do that we can simply or you can simply also have a Max points itself maximum Max points so simply it's Max points into max points anyway you can just see if you just have a n then you have to add a few more conditions of few more optimizations here and there but it is more or less both are n and Max points both are like this so simply your complexity anyway will go up to 18 only but can we optimize this because it will give you tle for sure cancel optimizes yes we can how if we just go back and look at our DP of 14 again then it was something like this DPF 13 12 and 11. which I can write this as one upon Max points I just bought it out and then it was deeper 13 12 and 11. if I just try to find out DP of 15 it will be DP of 14 12 and 11 right you will see DP of 1413 sorry 14 13 and 12. you will see that these two remain same only this part got removed and this part got added so as he will go on to the next DP of 16 just one thing which means it will just get removed the last one and again DP of 50 will get added so basically it will just happen that you have this whole window as soon as you reach on to the next to find the next I plus 1 or I in element this last part will get removed and again a new part will get added it's nothing but a sliding window approach which is being used to optimize your existing DP solution you saw how good this question is yeah it is now the thing you use the for Loop to find the DP of I entirely by going on to every of those dpfi minus PT that won't be required at all because you can just use a sliding window which is like nothing but Computing okay what is a sliding Windows sum accordingly at every step okay I will just remove this last value which was there and then add a new upcoming value and then in the next step if I had a row something like this I just removed this and added another value so in the next step it took something like this I'll again remove this and another value it will look something like this I'll just again remove this and add another value it is how the sliding window approach works by this simple optimization everything remains exactly same I have this as um my basis is exactly same as I also showed you I you can have anything match points are n um no worries at all because both go simply uh simply find up till Max point just simply find it up till n anyways whatsoever you want uh probability which is the final probability which we already also had in the existing problem also if you just go and look existing but also has a probability sum now ultimately one modification is the windows sum because I need to maintain that Windows sum and with that Windows sum itself I need to shift that windows up to find the current this range sum I will just get with this window sum and initially probability of getting the number zero the point zero as one we saw earlier also then I just simply go on to every of those n points because ultimately I just want to find the answer for K up till n points so n points are more than sufficient for us now to find that okay what is the point because the ap of I is storing nothing but it is storing the probability of reaching the ith point so it was nothing but this window sum upon this Max points so it is nothing but this window sum upon the max Points asym Plus that and also we just remember that okay for the next step I just have to add my new dpfi because for the because see for this window right now it is this window for the next DPO 15. I need to add a DP of 14 it will add DP of 14 and also I need to remove my ap of 11 which is I will add which means I will add EP of I will add a DP of I and I will remove a DP of I minus Max pts right I'll do the same stuff I will just add a DP of I and I will just remove the I minus Max pts value to actually get the next windows up by these two things I'll get it but you also remember that you have to find the probability also although you can make it in the last also but also you can just accommodate this in this step only that okay if your I which means okay if you have exceeded n and because you have exceeded your K and for sure your Loop is going to end so from K to n it will just find the probability sum and it will just add in this sum chord probability and you will ultimately return this probability ultimately you will have just o of n because of the N Loop and also of n because of the space of VP you can also have of Max points also but still you have to make again a new step of computing your probability sum from K to n because you are only considered from K to n part only and then also it will just change but still the complexity will for sure remain same either if you take Max points or you take as n both are same that is you will just get the answer and code of C plus Java and python is down below for your reference I hope that you guys got it was an amazing question of mass probability uh sliding window DP oh God amazing if you guys liked it then please do smash that like button to make these notes it took around three hours and yeah
|
New 21 Game
|
most-common-word
|
Alice plays the following game, loosely based on the card game **"21 "**.
Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets `k` **or more points**.
Return the probability that Alice has `n` or fewer points.
Answers within `10-5` of the actual answer are considered accepted.
**Example 1:**
**Input:** n = 10, k = 1, maxPts = 10
**Output:** 1.00000
**Explanation:** Alice gets a single card, then stops.
**Example 2:**
**Input:** n = 6, k = 1, maxPts = 10
**Output:** 0.60000
**Explanation:** Alice gets a single card, then stops.
In 6 out of 10 possibilities, she is at or below 6 points.
**Example 3:**
**Input:** n = 21, k = 17, maxPts = 10
**Output:** 0.73278
**Constraints:**
* `0 <= k <= n <= 104`
* `1 <= maxPts <= 104`
| null |
Hash Table,String,Counting
|
Easy
| null |
1,569 |
hey what's up guys juan here so today let's take a look at the last problem in last week's weekly contest number 1569 number of ways to reorder array to get some to get same bst okay so your it's a hard problem you're given like an array of numbers that represents a permutation of integers from 1 to n and we're going to construct a binary search tree okay by inserting the element of numbers in order into the initial empty uh bs3 so find the number of different ways to reorder numbers so that the constructed bs3 is identical to that formed from the original array nums okay so for example you know it gives you like uh two uh three nodes here and the sequence is two one three so to form a binary surgery right you know the first you will insert the two first okay and then the second one is one which will go to the left and the third one is two okay so that's basically that's the original binary search tree okay and you it asks you to find how many other ways to form the same binary search tree okay so another way is we just uh another way is like what they said they show you here it's a array should can also be a 2 3 1 here because for 2 3 1 since the root doesn't change it's 2 right and the 3 goes to the right and 1 go to the left so which means with 2 3 1 we can also form the same binary search tree return a number of ways to re-order the nums ways to re-order the nums ways to re-order the nums okay such that the bs3 is the same and since the number will be large return it's too modular like return the modular of this one this number okay so a few more examples here uh so this one three four uh five one two okay and they're like five ways of forming the same like uh binary search tree uh yeah so if you guys uh keep looking at this pro uh look at all these uh different combinations carefully you know okay so i think the key point of here is that you know the first thing the first one is the root note assuming we have this array the first one is the root node and we cannot move the root node because if you if we move the uh change the position of the root node for example uh this uh the three here then the binary surgery will be different so our rule of thumb is so the first element cannot be changed but as you guys can see right so all the five possible permutations where the combinations right they all have three at the root but the rest can be changed but so what's the rule of the rats basically you know for three here and one and two needs to go to the left of the of three right and four and five needs to go to the right of five so the rule of thumb here is that you know the relative position of all the left tree a lot all the left nodes and the right nodes should be the same which means one should always come to the left uh one should always uh come to the before to wise that right because we need one and two to form the left subtree you know so one and two will be forming the sub tree if the relative position of this uh left sub tree changes for example from changing from two to one then the live sub tree will be different because for one two we have a one and two okay that's the left subtree but if we're changing the relative sequence of this one and two for example we change it to what two and one then the left subtree will become two and one okay two and one and this 2 sub 3 is not the same so in order to make sure all the subtrees are identical you know we can change the sequence betw uh across the lab subtree and the right subtree but not within the sub tree that's exactly what this example is doing here right see one two four five or one two four five okay one two four five right okay so that's the first uh observations okay yeah as you guys can see the uh the output increased uh exponent exponentially right like it's going huge right that's why we need to do a modular but okay so now the next problem is the how can we calculate all the other combinations all the combinations of the left tree and the right tree okay i mean this is like a classic combination math problem you know if we um you know if we have a left right if we have a length of left let's say we have a length of left and we have a length of right so what's the total combinations right for the uh for the left one and the right one so um i guess for this one you guys need to try to refresh your memory in your uh during your in your high school basically it's going to be a c of like what uh like uh n of l right either l or right it's uh it's the same one right so to choose the left one out of n or to choose the r one out of n is the same result basically for this one basically we're choosing like uh choosing two right basically how many ways we can choose we can put choose the left ones out of four here okay yeah so and to calculate this combination what's the combination right so that's going to be the n factorial right and divided by what divided by the uh the let's see if we have l here of the x factorial times n minus l factorial okay so in this case it's the length of the left plus right so basically this one is the left plus right okay and here actually it's the left and the right okay the length of the l and the right um okay so that's the uh given like a fixed uh left and right that's how many combinations we have okay basically the c uh the combinations of uh n or we can do this let me do this is the l plot plus right okay but that's only the one but that's the possible ways right let's say we have a left equals to left is two and uh three and four okay let me give you another example here five six okay now this is not a good example here let's say there's a five four six and one and two okay let's say for this example right so the left is one and two okay right the right is uh four five six okay so the total combination from this uh from this earth basically where five out of two will be a c uh five two okay equals to what equals to uh so if you calculate that it's gonna be a five three gonna be a five times four times three times two times one okay here is like two times one times three times two times one okay so here uh it's gonna be 10 okay so that's the combination right for this given like left and right but since you know this is kind of becoming like a recursive function recursive problem because why is that because the 5 4 6 is only you know for the left of course because you know one of the base cases if the length of the array is like less than less or equal than two then there's only one possible way because like for example the one two we cannot switch we cannot change the switch the root but for the right side right for the right side uh besides four or five besides five four and six actually there's another way of forming the left at the right subtree a binary search subtree which is a five six and the four right so with this one we can also form the right one basically you know since this is the only one of the combination base because with this five six four we're gonna have another 10 choices here that's why you know our formula is like this is the waste okay it's the basically that's the we're gonna have like hopper functions here right basically how it's gonna recursive function uh or working card like a waste maybe weighs off left okay times ways of right okay times c here that's the left plus right uh of l either l or right so that basically that's our formula that's that uh the function or you can call it basically so this one is a given so this part is the it's a combinations it's a choices given like a fixed l and r but we could have different ways of getting a different uh l sub array and an r s right sub array that's why we need to multiply all three together to give us the final result okay uh cool and another thing is that how can we calculate this uh this like factory right we can i think there python did there's a math uh library or we can cache all the other factorial results until n and so that we don't have to pre-calculate it okay pre-calculate it okay pre-calculate it okay so with that being said let's try to code these things up here okay um first the mod okay it's ten to the power of nine plus seven okay and i'm gonna define the weights okay so that's gonna be a waste of the what array quite array here and so the base case like i said if the length is of the rays uh it's equal greater than two okay then we simply return one because there's only one way of doing that okay otherwise right so the root is uh array zero right that's the root of the current uh of this current array right and then we have a left equals to what uh number uh for num in array okay if uh left is smaller than root okay since you know another constraints here i think all the numbers they're different yeah all the integers in them numbers are distinct that's why we don't have to worry about uh if this uh if the number is the same which uh you if we should go to the left or right since they're all different we can simply uh safely check this because here even though the same the first one is the root but the root is the same right so it will not go to any it will not go to either left or right okay so right for in array in if uh okay num is greater than root right so that's that and like i said right and then we just need to do uh like uh we just need to return what return the ways of left right should be parenthesis here um ways of right times this is like combination right the com combination of uh left and right okay and in the end we simply return what return the ways of the of nums okay you know at another part is another thing is that it asks us to find the uh the all the combinations right besides this one itself so we need to do a minus one and then we do a modular by the model by the mod okay yeah that's pretty much so now it's how can we calculate this combination right like i said we need to do a factorial of that so basically the uh let me define like half function to help us define the combinations of this 11 right i believe python also have like butane libraries but i never use that's why i'm just trying to use this so and uh actually i just need a length here yeah length of right the left and length of right okay so here uh we have a uh how else okay maybe there and l and right okay that's the length so i mean we just need to return right the factorial of the uh the left plus one basically the so like i said i think we can uh just uh cash pre-calculates those factorial cash pre-calculates those factorial cash pre-calculates those factorial numbers uh in advance basically we're gonna have like factorial uh equals to the first one is one okay uh the length is n right because the total right the total number do we have n here because we haven't defined n right so let's not okay because the biggest factors we will ever need is the left is the total one total left plus right which is the length of n that's why we just need to pre-calculate pre-calculate pre-calculate up to n here and yeah so for i in range factoria uh is the length here let's see less two to three i think we might need to do uh um plus one no actually and it's enough i was thinking about the length is one base but that's the uh the rate the this factor is zero base maybe i need to do one plus one but i is enough why is that because let's see the longest right the longest one is the uh this is the first uh recursive call which is the uh the root is this but the left and right so the left plus right equals to what equals to n minus one right because we want the left right the root itself is it has already been uh i mean excluded so which means the left and right the total length of the left and right will be n minus one that's why the uh the end is perfect so we so the n is enough so basically the factorial i sorry equals to uh factorial i minus 1 uh times i basically right for 1 is 1 for 2 right for 2 is like 2 times 1 for 3 times factorial two basically we're using like a recursive or like a this is like a dp right some sort of dp to precalculate it all the factorials yeah or you can call it like a pre-products right so now here we simply return what returned the uh the formula of the combination right which is the uh factorial of uh left plus right divided by a factorial uh left divided by a fact area of uh of right okay basically that's the that's how we calculate the combinations of l and right left and right so and yeah i think that should work let's try to run the code uh oops mod okay submit cool so yeah task yeah and space and time complexity right i think it's a lot logan right so it's uh well it's not a log and i think because the you know for the tree for traverse the tree is the log n but to calculate the factorial this is n right this is n here this is o n and for the tree for the weight here because we are doing like either left or right and uh yeah basically the so here's an okay so for the recursive call right and uh the worst case i mean the best case scenario right we have a n log n that's the best case scenario but for the worst case uh every time when we split the left and right it will go always have like uh you always have the uh um uh only one left or everything is on the right so the worst case now worst case scenario is n square yeah basically so i mean the worst case scenario which means it's like a list like this one right so the worst case scenario will be like uh like n plus uh n minus one plus and minus two plus n minus three which will be n square so but for the best case scenario every time we'll be uh basically splitting this like this array into two parts evenly right then the best case scenario will be uh unlocked okay uh cool i mean this is a very tricky problem you know it has a lot of things you need to understand i mean especially for me and i think every time when it's a math problem i'm i'll be having a hard time to solve this problem yeah because you know you because you first you need to understand you need to know like what's the what are the different ways means right it means that uh you cannot move the root but you can move the left right the left part and then right part like freely but while you have to keep the relative positions of the left and right so basically it's not like permutation it's a combination right so and also you need to understand what's the difference between a permutation and a combination so for a permutation right you basically for the permutations you can uh you cannot uh also uh like basically you are you're free to make any change even with the one and two chain one two to two and one but for this one it's not a permutation it's a combination okay i think for the permutations it's like we have a different like uh a calculation here but for combinations and then you need to understand how can you calculate the combinations right and then with that in mind you also need to know like uh now i need to use the a recursive call right to calculate all the different ways of the left and the right and for given for fixed left and right what how many uh weights how many like combinations we have okay by using this one cool anyway so that's uh it's a good problem yeah i think i hope you guys learned something at least i did okay and thank you so much guys for watching the videos and stay tuned i'll be seeing you guys soon bye
|
Number of Ways to Reorder Array to Get Same BST
|
max-dot-product-of-two-subsequences
|
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from the original array `nums`.
* For example, given `nums = [2,1,3]`, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array `[2,3,1]` also yields the same BST but `[3,2,1]` yields a different BST.
Return _the number of ways to reorder_ `nums` _such that the BST formed is identical to the original BST formed from_ `nums`.
Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 1
**Explanation:** We can reorder nums to be \[2,3,1\] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
**Example 2:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 5
**Explanation:** The following 5 arrays will yield the same BST:
\[3,1,2,4,5\]
\[3,1,4,2,5\]
\[3,1,4,5,2\]
\[3,4,1,2,5\]
\[3,4,1,5,2\]
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 0
**Explanation:** There are no other orderings of nums that will yield the same BST.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= nums.length`
* All integers in `nums` are **distinct**.
|
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
|
Array,Dynamic Programming
|
Hard
| null |
1,071 |
Ha Ga Namaskar welcome to the channel we are doing 90 days kasi proof this is lead code 75 question number two lead code 1071 great common divisor of the strings okay so let me look at the question what will I analyze I will analyze the question What to do in the question, what to do, then what is the solution approach, how to do it, why to do it, after that I will analyze the time complexity and finally I will talk about how I was able to think about this question. Could n't think of it, so I will try to do the same analysis in every question, so first of all, what is the question, what is the solution, so first understand what is, then this is the question in front of us, so let's give our two questions. If it is kept like A B C and A B C then we have to C A B C and A B C then we have to tell the biggest string from which this can be formed and that can also be formed, what does it mean like Y A and this A then A is only A to A Repeat this twice, string becomes two and repeat it thrice, string becomes one. Okay, now there is no such string for the lead code, by repeating it we can create the code as well as the lead. Look inside, if there was A S A and A C, then ABC is the string which is repeated once to form string two and by repeating it twice to form string one, I think it must be clear what the question is, okay again. Let's talk about what is the question so like given a string you have anything let's say I do this a b c d a b sad and string to Let us say A B CD A CD You are told that is the longest string identification the question E Now understand carefully look at how I'm scheduling my discussion The next thing you have to understand is what is the solution Because Why is the solution is sharp then if we start understanding what and why together then it will not be thought then first I am discussing what is the solution then I will discuss how is the solution working meaning we would code it then we will discuss Why is the solution? Then we will discuss more than one. And finally we will discuss time complexity. If I could not think of this question then how could I have thought. So what is the solution. Let's discuss what is the question. The next discussion is done, you have to do it yourself, see what is the solution, there are two parts of the solution, what are those two parts of the solution, it is also possible that there is no answer to these two strings There is no string dividing The answer exists. If it is not so, then the answer itself does not exist. In that case, you have to return blank. OK, Y, its Y, not to be discussed yet, so what is the solution, we are discussing. So the first part is if solution one ps solution two is equal to solution two p solution then does it exist? The answer does not exist. Okay, now when the solution does exist then what will be the answer? Okay then the answer is very simple. The length of both. Grab, its length was 12, its length was 8, find the GCD of both these lengths, the greatest common divisor, the largest number that divides both of them, is four. 4th is 8, 4th is 12. Okay, so the first four characters of any string. Pick it up and return it. Basically, what does it mean? What is the solution? What is solution 1? Check solution 2 to see if it is equal to solution 2 + 1. Check solution 2 to see if it is equal to solution 2 + 1. Check solution 2 to see if it is equal to solution 2 + 1. If not, then the answer does not exist. And if it is equal, then Find the GCD of the lengths of both. Let us say that a is string and length b is string. Find the GCD of both. Let us say that you have written a method which you called and found out the GCD of both. You have the GCD. Answer. Do you know what is string 1 substring of 0c I think what of the solution is clear we will not discuss it for now the next thing we will discuss is how of the solution let us code it up how the solution I hope you know how to code GCD because GCD I will not teach you how to code. Okay, so here we go. There is no need to actually code. Okay, I will code quickly. I will code only what is told. Look, if you want to compare strings, then keep one thing in mind. Whenever we compare strings, we use equals, double is not equal to two, if you do not know this then you should do this research and in fact if you go to Pep Coding and watch the lecture on strings. There is a lecture in level one, so there is a discussion on why you should not use equals. Okay, if you want it, I will show you where you can find out why you should not use the major functions of strings. Where I have Discuss string list so introduction yes this one you can see the discussion string turning end table and after that string builder usage and performance so the video you have to watch is introduction to string builder ar list okay after that you have to watch This is Introduction to String, then String Interning Ability and String Builder Usage and Performance. Inside this you will get clear why to use Equals, why not to use L, Right but I am coming back so I am saying String anytime. If you compare then use it through equals then string two ps string and k are equal then the answer exists otherwise if the answer does not exist then return blank now what is the answer here take the length of string one take string two key Take the length and find the GCD of both. Find the largest number which can divide both A and B. Then I will write a method which will give the GCD and then my answer is very simple. Find the length of the GCD from string one or string two. Cut it and give it. If the GCD is four, then select the first four characters and give it. It's okay, only one piece is left. If the GCD method is written, then I will do the GCD with the division method. If you don't know ya, then it means it is pretty simple. Division method: Do means it is pretty simple. Division method: Do means it is pretty simple. Division method: Do you remember what is the division method of GCD? Let me tell you quickly, like if you have to find the GCD of aa and 12, then we take out aa and divide 12, then we get four. Now we The last divisor is made the dividend and divided with the reminder, then when the division is done, the last divisor is the answer. The last divisor is the answer. Okay, this is simple. Look again, look, the eight is placed here, 12. If it is okay here, then a number is being divided. The last person who succeeds in dividing a number is considered to be the answer. It is okay and it does not matter whether we keep a smaller number outside or a bigger number inside, it does not matter. If you keep 12 outside then it will be 120 0 and then that reminder comes next time it becomes eight times, so we do not need to calculate the big and small, it works fine, so I kept eight outside and put 12 here. From us this number is a this number is b the one dividing a is the one dividing b is the dictionary it doesn't matter the reminder came four next time now who will divide the reminder will divide so this was a reminder so let's pick up a and take it here Come, now you will divide, who will be divided, the one that was at last time will be divided, it will become b, okay divided again, this time it is divided, so the one who had divided has become the answer, okay, it would have been simple. Look at the algorithm, what will we do here? Till the time b is divided by a, division will continue in the reminder, till b is divided by a, take out the reminder, b is mud a. Now see next time divide. The one is called a, who will divide next time, the one who will divide as per the reminder, then a will divide, so I received this reminder in A, okay, who will divide, the one who has to be divided is called B, so the one who had to be divided last time. If the divisor of was, it will be divided, then B will become A, the one who divided last time, will be divided this time, the reminder that came, it will divide, then A, the one who divides, B, the one who will be divided, then this is a simple code for GCD. I used to assume that you would know this and I would prefer to leave this kind of thing in the further discussion, then we will divide till zero comes because no, for many people it is like that, Sir, this is childish. So if it comes then there should be more, it means that the series I am doing is not for beginners, this series is for those who know a little bit, who have done at least level one of Pup, who have done at least 200 Questions have been made till date, DSA is for those who have not started till date, it is not for those who have not done any graph question till date, it is fine, at least 10 questions of graph, 10 questions of DP, why is it a priority? If you have done 10 questions of Hash Map, then this is for you. If you want to know whether you should do this series or not, then I will tell you the same. You should have done at least 20 questions of Rikers. You should have attempted at least 10 questions on DP, 10 questions on Graph, five questions on Priority Queue, five questions on Hash Map, at least 20 questions on Trees, and at least five questions on Stack Queue. Yes, ask at least five to seven questions from the five link list, then you will be able to follow me, then I will skip things like GC. Alright, so I hit submit. This would be submitted. The spelling of subst is wrong, so one more. Question solved How to do it Okay if I go back to the beginning of my discussion I think at this moment I know what of the question What of the answer is known How of the answer is known What is not known That is Y why are you doing what are you doing after that time complexity and intuition so let's discuss time complexity once Y because it is difficult ok let's discuss time complexity then there is no space complex T because we have not discussed any The array was not created like this, the time complexity is this: string 1 was complexity is this: string 1 was complexity is this: string 1 was added to string two, this is the work of O and comparison with equal is also done by O, so here if the length of string one is n, the length of string two is m then n + m This is what n length of string two is m then n + m This is what n length of string two is m then n + m This is what n p m has been found ok yes sir so it is a log code when it is a division code then it is logarithmic no need to worry then n p was this if their length is n p then n P is G is added to the base The remaining things are intuition and well, let's discuss it too, so what was I able to guess and what was I not able to guess, so I was guessing that the answer would be related to the GCD of their length. Will be off course is n't it like the first string if it is 12 length from let us is 12 length and the second string if it is four length sorry eight length is eight length then this is 12 length That is, their GCD is of eight length, their GCD is four, so look, if you do not take the GCD length, then it will not be duplicated by repetition, so it was understood that GCD is going to evolve, okay, this is all I could think in intuition, so I If I had done it myself, who knows what I would have done, I would have taken out the GCD of both, I would have taken out the GCD and first of all I would have taken out the GCD length meaning from inside both the strings, I would have taken out the sub strings of the GCD length, I would have copied these four characters of the short string and then I would check whether it is capable of dividing, meaning if I put a loop in the whole, then I would check, brother, this is the first is equal to this, the second is equal to this, the third is equal to this, the fourth is equal to this, the fifth is equal to the fifth. Sixth is equal, sixth is equal to the second, seventh is equal to this, eighth is equal to this, meaning here I would be using the model, then one is finished, then its second is not to check that then this is equal to this is this This is equal to this is the thought coming in my mind, ok, it's true, if you think about complexity, then this solution is not bad, n + m is the solution is not bad, n + m is the solution is not bad, n + m is the length of both, took GCD, tried GCD, ok but If my GCD length had failed, I would have tried a lesser length. If he had failed, he would have tried a lesser length, so on and so forth, he would have become stupid. So what did I do? After trying for a long time, then I read the solution and after reading the solution, I can give you a formula, when to read the solution, like you tried for 20 minutes, after that read the solution because volume is also important, read the solution, do not submit just after seeing the solution, read the solution. Understand as I have taken out all the y, after that submit it without reading and take notes. Submit and notes so that you remember your y. It is important. Okay, now I will discuss it for you. First of all one thing has been done. It was that string one plus string two is not equal if string two plus string y is not equal then there will be no answer so we can do this why look man look let us say the answer is ok let us say the answer is such a big answer I Let's not talk about it but one answer exists, this string one is made of 12 keys, suppose I made string two of eight, then the answer comes from let us, the answer comes of two lengths, for example, some answers exist. Which by repeating it again and again becomes string two. By repeating it again and again it also becomes string one. Similarly it is said that let us say or I take the values of nine and six or I take the values of nine and six or I take the values of nine and six for this question. I accepted it as nine, it became nine and I convert it into six. Yes, no and six, then from Let Us, my answer of three length has come. I am wondering, so from Let Us, the answer of that three length is ABC, if that three If the answer is of length, then string two is A B C A S, it is formed by repeating it, A B C A B S, it is formed by repeating it, A B C, and string one is A B C A C S, it is formed thrice, ok, I am happy with this answer. Let's say As x is copied only twice but any which way I here x is not your character And due to the combination of x, some number of times is formed by combining but it can be represented as x. String one can also be represented as If we can then look at string plus string two what happened first string one is 3x and then string two is 2x and string two plus string one what happened is first string two is 2x and then string three is 3x and string one is 3x then it is only 5x Well, here x is representing ABC, so it means when I write It is possible that string two can also be represented by a copy of x, which indicates that x is our answer. If x is our answer, then string two can be represented by Can be represented by copying x. If both string one and string two can be represented in copies of If string 2 is equal to string 2, it means x does not exist, so the first proof I understand is that if it is not equal, then why would the answer not be and If it is equal then why does the answer exist? Okay, this is the first question you had to understand. The first thing you had to understand is that if it is equal then why does the answer exist and if it is not equal then why does the answer not exist? I hope first why. In my view, it was clear to me that if the answer It is made but it does n't even work in the other two ways. How many copies of Let's Above five, Below three, Then if I do string 1, string two, then I will still have some copies of If only copies of If it is, then why will only GCD length give the answer? Why can't any other length shorter than GCD give the answer? The second thing is very deep. If the sum of both is equal then why will only GCD length give the answer? Apart from GCD length, why can't any other length shorter than GCD give the answer? GCD, do you understand what is the biggest number which is dividing both of them, why will it give the same answer? Let us think about it. Yes, see, it will be proved by contradiction. Let us say that the answer exists. Okay, whose end Let us say that the answer is x so and let's also assume here that x is not the GCD of their length. Let us say again that the answer is equal to GCD of s1 and s2 length will be their length. GCD is not correct, but at least one thing will be accepted that s1 has been made by copying x and s2 has been made by copying x, then divide the length of both. So it does this, then you will agree, at least you will agree that s1 is made by copying x and s1 is made by copying x. You must have accepted that the length of x will be divided by the length of x. It is assumed that the length of There is another method also, from Let us, I find GCD of some big number, 144 is a number which comes in the table of 12, I find it, from Lettuce, I find GCD something like this, let's choose another GD with 36 180. Okay, I don't even know, one string of ours is 180 and one is 144, so let's find the GCD. I won't find it by division method, I'll find it by factor method. 272 26 I'll find it by factor method. 272 26 I'll find it by factor method. 272 26 2 29 33 31, I will write all the factors by factor method. 290 245 315 a 35 5 1 so 144 can be represented as 2 * 2 * 2 * 2 * 3 * 3 and 180 can be 2 * 2 * 2 * 2 * 3 * 3 and 180 can be 2 * 2 * 2 * 2 * 3 * 3 and 180 can be represented as 2 * 2 * 3 * 3 * 5 so do you represented as 2 * 2 * 3 * 3 * 5 so do you know what our method of finding the greatest common divisor is? Like this has two twice, this has two four times, so you can pick as many maximum twos as you can from here, pick the one that is common, three, this has two times, this also has two times, pick all are ok, so whatever is your greatest common divisor. It used to come 2 * 2 * 3 * 3 This is the largest number which can 2 * 2 * 3 * 3 This is the largest number which can 2 * 2 * 3 * 3 This is the largest number which can divide both 144 and 180 Okay because All two's maximum two could be taken from this, maximum three could be taken from this, maximum was maximum common two and maximum common three, maximum common factors were taken. Okay, so what is this number of mine 2 T 4 3 12 3 36 pho and 36 5 180 is ok so the length of your a from lettuce is 36 not saying right now it is 3600 gcd no our nor the length of gcd was the length of our av the length of av was 144 the length of a2 The length of the GCD was 180, how much was the length of the GCD? 36. In front of us, I have just calculated the above using the factor method and I am assuming that my answer is the length of one, it is not the length of G, it one, the length of one, it is not the length of G, it is smaller than that, okay, but I am one. I have already told you that whatever you consider to be the length of x, but the length of If it is made up of then it must be dividing both of them, so that I want to remind you of one thing, then what can be that Leave that two. If you leave this two, then it can be 18 or leave a three. Whether you understand it or not, look, if this was your greatest common factor, this was 36, this was your greatest common factor, then what will become x. We have said that x is what it is. It is not equal to GCD but it divides s1 and s2, so the largest number dividing s1 and s2 was this, which was that if we have taken all the common factors, then I will leave some of them, so a number like this If I leave out any one of these, then a number will be formed which is capable of dividing both of them. This number will be formed only by leaving out some of these, then if I leave out this two, then I get 9 * 2. 18 So yes, the length of It I get 9 * 2. 18 So yes, the length of It can be 6 but the important thing is that the length of It was thought that both s1 s2 are divided by one, then x will be formed only by leaving out any of the factors from which the GCD is made, which means that the GCD is also made up of a copy of x. Okay, now think once. Look, we said this is our string one, 180 characters, string two, 140 characters, 144 characters, this is our GCD, 36 characters, we said, four copies of our 36 characters and five copies of 36 characters, our answer is no. We said like this, we said that I copied the length of 18 eight times. If this is the answer, then both s2 and s1 are formed from its copy. So where did 18 come from? Did I leave out any one of the GCD lengths? I left out one of the factors like this. Assume that 18 is our answer, 18 length is our answer, then both s1 and s2 are made from its copy, so I paste 18 eight times, 18 terse is pasted eight times, then s2 is formed, paste 18 10 times. Given 10 times, s1 is being formed, but the important thing is that by pasting 18 twice, GCD is also formed. Okay, now by pasting 18 eight times, your s2 is being formed. By pasting 10 times, your s1 is being formed twice. If a GCD is being made from , is being formed twice. If a GCD is being made from , is being formed twice. If a GCD is being made from , should I stick the GCD four times? Instead of sticking A1 eight times, wo n't s2 be formed? Should I stick A 10 times to make S1? Instead of sticking GCD five times I should not make the GCD of 'f' five times not make the GCD of 'f' five times not make the GCD of 'f' five times because the GCD is made from the copy of 'x', the GCD is actually double made from the copy of 'x', the GCD is actually double Instead of this, can't I make s2 by writing double x four times and ca n't I make s1 by writing L If it divides the length of G, then it also divides the length of GCD, which means GCD is also its copy and if this is the answer, s2 is being formed from its copies, s1 is being formed from its copies and GCD is being formed from its copy. If yes, then s1 and s2 will definitely be made from the copy of GCD. Okay, I hope you would have understood it. It is a heavy thing, it is a deep thing, you will hear it three-four times, then you will understand. Okay, so hear it three-four times, then you will understand. Okay, so hear it three-four times, then you will understand. Okay, so now look at these types of questions. If you are not able to think the answer to that question on your own, then what is the analysis to be done? First understand the question and then understand the solution. Look at this time, layering is very important because at one time you can put a tension in the mind if When you think 'Y', your mind will explode. think 'Y', your mind will explode. think 'Y', your mind will explode. First you have tried and failed. So when you are reading the solution, consume it in layering. What does the author want to say as a solution? Consume everything he has to say and then try it and see how it is going, then think about why this author was saying this, what was the reason why he was saying this, then only when you will understand. If you are focusing on what then you will be able to consume the whole thing of the author. Many times you know what happens is that our inner voice which is asking why is actually the one which does not allow us to study from the teacher or it does not allow us to do well in the world. The liner does not allow us to assume that the other person is speaking but we have questions, we do not want to listen to him, we want to express our views, we want to listen in our own way, then we know what happens in listening as per our own, the author's story is bad. If it happens then when you have tried and you are not able to do it now while consuming you use what how y first listen to what the author has to say use faith use that if yes the author has written it then it must be coming from him And he must have given the solution to my doubts, so I keep it in my Y side, first I listen to what he is saying, first I listen completely to what he is saying, then I try using it, now I think, man, he has done this. Had the question been answered? Had this question been answered? Is it okay then the philosophy wood work is actually okay and then if you have now got the wise make notes of that submit it without watching the solution because these ones which You yourself did not think that you most like this and you will forget it later, so that is why it is very necessary to make notes. Okay, so there will be questions like this which I myself was not able to submit. Such questions There are 75 questions in this list which I could not submit myself. If I have to see the solution, you will get their analysis in the following manner: What is the question, what is the solution, how you will get their analysis in the following manner: What is the question, what is the solution, how you will get their analysis in the following manner: What is the question, what is the solution, how is the solution working, why is it working then we We will discuss time and intuition, how much we were able to think on our own and how much we had to understand, right, yes, we will meet in the next question, when I asked this question for the first time, I had left it, so I am tired, now I understand it very well. I can defend someone in an interview.
|
Greatest Common Divisor of Strings
|
binary-prefix-divisible-by-5
|
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters.
|
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
|
Array
|
Easy
| null |
57 |
the insert interval problem so given a set of non overlapping intervals you have to insert new interval and you may need to match if it's necessary okay so the problem statements intervals the given 1 3 6 9 and new interval is 2 5 okay for this problem the main thing we need to do it is you know up in the new interval and then sorted uh based on the start value so that is one of the important things we need to do and once we sort uh we need to check if we can merge it so for example uh we have two uh scenarios here the first scenario is we have a start time one four and the second one is three seven so we already sorted it and now we need to merge this so in this scenario what happens is you just need to compare the first interval end which is the four with the three so if it is equal or less if the second the one which is interval the second interval is three seven if three seven the start is less than the end which is before interval then we need to merge it so this would be like uh we would check the start of the second with the end of the first for merging so that means it has to merge and then we uh emerge the end so the end of first is four in the end of second interval is seven so the whichever is greater that would be the end of the new interval the new merged interval so the merged interval is one seven this is the one scenario and we have another scenario here uh which is the first uh interval is point four so we have sorted it based on the first uh start alone so always it should be one two so that's how the sorting works but we not started based on the ending so what we need to do is once we sorted from the first we need to compare the second first with the first uh end and if it is lesser than greater then we have to merge it in then we have to also check whether the end of the second interval is lesser or greater based on that our merge condition would be uh getting the end of the merged interval so here what we do is first interval is 1 4 second interval is 2 3 so obviously the merge interval has to be 1 4. so this are the two conditions which we need to evaluate before we understand how to do this problem so one is sorting so the algorithm would be i just sort first i'll append the new interval and i'll sort it based on start okay based on start i'll sort it and then what i can do is uh i will have a result array so i'll have a result array with the first element added to it and then uh we can i trade sorry and we can i trade over the interval and check for previous start which previous element in research so that would be the last element in result with the current element just check for last element with the current interval so and you verify validate the start of the current interval with the last element of the first uh last element of the end and then you can you know merge the uh interval so that would be the strategy so first thing is if there's no intervals given so what we do is we will append the new interval so neutral is this and we'll return it because it's done else we will append yeah we'll start with this we'll have a resultant array containing the first element so we need to sort the intervals first so that's the plan so we'll sort it so third intervals and our key would be the first element so if you want to know more about the sorted i have one more edu so you can go through that so you can easily understand the sorted the keyword in python i've done one video on that you can check that out so here i would add interval to zero and then uh iterate from the first element one two length of intervals so intervals is sorted in result array is appended so this is done so oh now we need to check the current start and current end is nothing but your intervals i introduce i and 0 because it's another list and similarly your end is nothing but one so start and end this i have zero and i have one and your resultant the previous element the last element of result would be your previous data so this is one we have to validate it's nothing but your resultant last element and the pre-start would be index zero and the pre-start would be index zero and the pre-start would be index zero and three end will be index one okay so now uh based on the diagram so we need to verify this would be a pre-start be a pre-start be a pre-start this would be a current start check if the current start is lesser than or equal to restart right so that's the condition if the start is less than required to previous start then you have to merge so you can pop this from the result because we are going to merge it and what will be a new start and what would be the new end right so new start would be your same your new start would be your pre-start pre-start pre-start so add that right a new end what's the new end so new end is whichever of the uh end is greater is it max of pre-start and pn right so 4 of pre-start and pn right so 4 of pre-start and pn right so 4 3 four is max so you get max off pre end and end right so that should give the um then you append this new start and new end in the result right so that's what we're going to do so this is your new start that's a new interval and that's a new end okay if it does not we're going to just add the array element we'll add the current element in the interval so that just intervals of i and then we should be done let's run the code check for any issues okay it's done let's check the other conditions okay let's check this out ready for eight okay let's check one two three five four eight okay this is missing let's check why did we mess this so new and this okay let's print the result here okay one two three five four eight one two three five the start is less than or equal to please start sorry pre end isn't it so it should be pre-end so that's the condition so that works yeah start should be pre-end so that is what start should be pre-end so that is what start should be pre-end so that is what we need to verify this star this is pre-end pre-end pre-end so looks like this works let's submit it yeah it's accepted okay guys thanks a lot and that was a mistake but it's good to debug in you know get to the bottom of it thanks a lot i'll see you guys sometime thanks
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
334 |
Hello friends, welcome to your channel, today is our day of 18th co challenge, so let's go straight to the screen, so here I am on the screen, today's queen's number is 3344 and jo queen. The name of the increasing triplet sub is so let's understand what is the queen. For this, we had already placed our white board page, so basically what is there in it, we will be given a name, we have to return if the assist three indexes are true that I should be. Less then j should be lesson k It is okay if all the i j are smaller j it should be a little bigger than that j is bigger than that it is okay and along with this the names of aa jo hai should be smaller. What should be the numbers of h and numbers of k should be greater than these two? Okay, so if I get any triplet of this type, then what do we have to return true? If both of these conditions are there, we have to return true. If we have to do if no true persist return false then we if there is nothing like that then we have to return false like if I talk about this one r's our tooth fur f then there are many of our what is triplet kri triplet any triplet you like If I pick up 4 5 then this is also a triplet. What is this also doing? Return is also increasing. This is if I pick up 3 4 5, should I pick up 3 4 or take it down? Okay, so what will all of these give me? If you give true, then if I am getting Parjang triplet here, then it is also written here that true is valid, any triplet is valid, if I talk about this triplet, if I talk about 54321, then this one is 543 2 1. So this is our one, we will be seeing what is our decreasing L descending A in which element is J, there is no increasing number in this, it will remain false as it is, okay look no triple The answer they have given in this is 345. Basically they have given indices. What are the indices? 0 2 So we do not have these three elements. What are we making an increasing triplet? Okay, the index is also increasing. Okay, so let's see our triplet become something like this. If I look carefully, we also talk about triplet or butt-creasing triplet, then talk about triplet or butt-creasing triplet, then talk about triplet or butt-creasing triplet, then this is the best, it is together too, so it becomes our triplet in this way, so we also have to find the triplet with this type. Now what is this? The first approach that will come to anyone's mind, what will come to mind, so understand it well, now the first approach force comes in Apo Ma, what would all three of us take out, we take out all the triplets, after taking out all the lets, we will check the condition, then I booted. The code of the force has already been written for you. Okay, let's see how it is doing and know its time complex. So, I made it in this manner. The first loop that will run will be ours. The one from i will run from i0 to Nums dot length. If any such triplet of names of J is found then return true. Now if this one is seen in the name complex must case of our code then it should be coded as O or n. So what to do. First thing is that when is n in? So we don't do this in the code, generally we can do it but we don't do it because there is a lot of useless time complexity and it is also given in this question that you have to do it in O of A time has to be used and O of one. It is okay to use space, now someone has said, try using it like this, so let's see if there are some such approaches, let's go ahead, this approach was very simple, anyone can apply it, let's go to the next page and some more Let's take an example and then see how it will be 84. I put an end on Y, so I took this one, now what do I need, neither take three numbers nor numbers, so I took the first number as first, second and third number. What do I need in this? The smallest second should be a little bigger than that, the third should be bigger than that and the one present on their index should also be like that in our creasing fear of I in the creasing of J and the first should be great sorry I made a mistake a little I which should be and should be small We should have all these three conditions, these two conditions should be our math, then see what the approach is, first of all I am not in all these. I put na plus infinity. As soon as I come, I put plus infinity. He will understand why. Put plus infinity in all three. After putting plus infinity in all three, what will I do? Look, what do I want in the first place? The first number will obviously be present at the beginning of the array. The second number will be present somewhere in the middle and the third element will be present somewhere at the last, meaning it is going to be something like this. Now whatever I want in it, I have to put the smallest element of the beginning number first because that will give me the most potential. While going and making an increasing triplet, I say again, once I have to put the smallest element in the first, why do I have to put it so that because it will have the potential, the smallest element is okay to go ahead and make the largest triplet, so I look at it is okay. And which element do I have to put in the second? In the second, I have to put that element which is bigger than the first. Then I went to its approach. I asked A came to the first and he said that Ta first is already infinity, do one thing, you wanted a small number, so you take A, after that came fo four, again a small element, he also said to first, you are still big, do one thing, small element, because in first I am Talking about the smallest element Th, I again updated Th in Th, now came F. Now the largest element after the first can help us in making triplets, so if there is already a small element in the first, then What did I put in second, put five, okay, now seven came. Seven asked three that brother, you are smaller than me, aren't you small? Then he said to first, go away. Check with second to see if you are there. I am trying to make triplets, so I went to Five and asked Five, is Five smaller than me, no, Five is smaller than me, yes, it is smaller, then Five said that you are also capable of making the third number. You have the capability, as soon as we get the third number, what should we do by returning from here? Why should we return from here because we have got the chance as soon as we got all three numbers, then make it true from here. Even if it had happened, we would still need to go. It was not right, if you don't write more times, I understood it better, but I made the first number, it was first equal to two integer zero dot max. Okay, now I have to make three numbers, although I could have done with two numbers also. But you will understand better if you do it with number three, then I have also written this, after this, I have to make third number also, so I will replace it, now among the three, we have now put one loo then aa 0 aa le nam leth and aa p I took something in that way, now I take out the first element, this element lock was not needed, still for the sake of sophistication, to make it easier for us, I gave it a name, I wrote that which is my first number, I take the smallest number in it, if it is already If the element is bigger or equal then what will I call it? If the element is bigger then you take the element with you, so I said in the first element, in this case if this element is bigger than which element will be bigger than our first then it has the potential not second. If he is smaller than the second, if he is smaller than the second, then he will say, I become a second, your element. It took the place of the second element. Okay, else if both of these conditions fail, it means it is bigger than the first and second, so we got the same answer, but we will update it in the third first so that we know what we are doing. But from here we will return true because I have got all the three elements, first element, second element, third element, all three and if I have not got this then what do I have to return from here, return false if it is not true here. I was able to make the third element, is n't it? Even if we don't include the third element in it, our work would still be fine, but just in case, we could understand it well, that's why we took it and used it. If I talk to you, I will get something like this. In the first I put plus infinity in the second, plus infinity in the third. Now what is there in my element? First of all, I would have made this table, I have written this in the first, what is it in the first, if I talk about the second, then in seconds. What is there in the second also, in the second, in the third, I have written G, V and F, now I have written the value of P, first of all, zero, what is in the element, what is our A check, what is plus infinity. Greater than is equal to 8 is yes then first element which element will go to which will be stored first till here when we checked what is happening basically this is a minimum element till now so we also updated it in the hope that maybe If we find elements bigger than this, which are used to make triplets, it is very important to see what is going to be found next. It is also important to see what is going to be found next. Let us remove this element. Now the element that came in the element after the value of aa is not null. I came to check what is greater than equal to two now? Why is this updated? This update happened because four has more potential to make further maximum. Four has more potential to make further triplets because the smaller the four, the bigger element will be found. The expectation will be that much higher. Okay, so who did we update the 4? After the 4 is updated, after running the loop again, after running the loop, it has come, now it has come, you see, 4 is greater e, now th has even more. There is more potential, right? So we have even more potential to create further elements, so we have done this okay in the hope that maybe I can get more elements. Now let's go ahead and now the value of E has come. Now we will see that the game will change. A little greater equation would have been 5. This falsehood does not happen. Now what is the meaning of this falsehood? Do you know the meaning of this? Is the first saying to you, brother, you are bigger than me, then you might become my second number in this hope. Now let's see below what is written in it plus infinity greater itu hota haya so our second element is capable of becoming mab what has come in the second element ki and again ba aa ki wal bani aa ki After the formation of 'L', what is the ki After the formation of 'L', what is the second element, what is it? After the formation of 'val', second element, what is it? After the formation of 'val', what is the inner element? You make me my second element. The second element's father said 5 greater than equal 7. This is saying that you are bigger than me, so you can make me my third element. As soon as it went into others, it will obviously become the third element. Seven came into the third. From here the return became true. Now let's see the return from here became true. It has made an increasing triplet. First Second Third. Here we can see that an increasing triplet is being formed. 357 So this is how this question came about. I hope so you got this question. You must have understood this matter very well. If you have any doubt then you can ask in our twitter channel. Okay, I myself am very active there. Even our team is also very active. Any doubts, any queries. You can come there and ask and keep supporting us in the same way as we are getting support for this challenge, we have many more things coming in future too so thank you. See you guys tomorrow where we will answer the next question. are solving
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
463 |
hello welcome to my channel today we have leeco 463 island perimeter so you're you can see this is description right here so i assume you see it before uh seeing this video so in summary uh the idea of this question can be uh simplified in this form so now this will be the input of this 2d matrix so this is the grip so we input the grip to see what the island perimeter is so what is perimeter so for example you know what's island for you can see is one this one is connected to this one and this one have the four directional connecting to different ones right here and this all one are connected directionally so now this whole entire thing is an island in this simple graph right here representing the island right here so the outside border is the parameter so how do we calculate um total parameter of this island so in this question this is good way to practice dfs we're going to use dfs in here and also to come up with um a logical guess of how this um the pattern is so you can see if this area which is zero this is not island but now in here if this is island how many uh bar we call this yellow thing is called bar right now how many bar in here so this have one two three right so the pattern of this solution is when you see um island right here so we need to calculate the parameter so if it's touching the border line which is out of the bound then we have one bar right here so if uh left or right i mean if that area is empty on the side so we have a bar you know here same things areas of empty so it's have a bar right here so we're standing right here is looking at down downside that have a island so in that case we don't have a bar so for this particular island we have three bars right here same thing happened to this empty out of bound empty so three bar so in this one up is not empty it's not empty so for this particular island i have no bar so you can follow this pattern to calculate how many bars for each individual island i mean area land then you can come up with total for the entire land right here and then we just output the island perimeter for the solution so now we can take a look at the code now so we have in for the output right is called star is zero like what we need to do is loop through the whole entire matrix starting with i e to 0 i less than grid dot link so i plus so also we have a j for the column started with zero j less than grid um zero dot line j plus so that's how they look through the whole entire grip so now we capture i and j the location so f red i j we only care about when is one for example in here is zero so we don't have any a parameter right here so only when it's one it's when is the length then we can calculate the uh the parameter the bar right here so when this particular island is equal to one then we do things so we have four direction right so output so we have a dfs to calculate how many um bar for this particular island we can introduce that one later so the idea is the output is parameter will plus dfs actually it's not it's a helper function that put in the grid inj or actually we will need four direction which is i plus one j output um helper i minus j i miss one j so this is up going up and going down also output i have 11 right that will have i constant j minus 1 is left upper but sorry for the typing js plus one which is right side oh my god so now this is four direction we have a helper function to calculate the parameter accumulated to the output one is one so that's good after this one so we look through all the entire length and accumulate it to the output and we turn the output eventually so this is a public method right we have also have public method dot um calculate for that line how many perimeter it is so we have a helper function that taking the grid now grid right here you also have the location i and j all right okay cool um so now for example in here we have a land so if we check if it's our bound then for sure if i less than zero or j less than zero so like upper bound left bound is out then for sure is what do we do will return one because if it's out of bounds so here's need the bar so return one so also i bigger or equal than grid dot link which is at the bottom of bound and r and j bigger or equal to with zero dot lane which is the column right here outbound so this four hour bound four-way outbound four-way outbound four-way outbound they will turn a bar right here so that is um let me see i think uh okay also if you see the right side is not out of bound but is empty which is zero it's water and also grid i j is equal to zero then also give them a bar right here so this is four-way checking so this is four-way checking so this is four-way checking so other than that now we can see they're checking the area so at that time it returned zero if you're not outbound you're not seeing the water right here that means you're seeing an island if this have item in here no bonding need to be added so we turn zero so this is the helper function cool and i think that's it for this question let's see if it's working another typo my bad a lot of typo so that sounds good for this question and submit it cool and uh this is it for this question and i'm here to do more um time complexity right let's take a look at the time complexity for this one so first we look through the entire matrix for every individual um space right here we need to do up and down left and right the worst case will be um having everything's island so every space right here need to check up and down left or right we will look through the entire things that cost n because this whole matrix is n element right here for every element we have four direction to check so that is 4n for the time complexity uh that's worst case um that's type of complexity so the space capacity will be oh we don't have any extra space now we might have only this variable extra so time complexes is n o f n space will be off at one which is um linear uh actually i mean constant um that's it for this question if you have any uh question please comment below and i'm looking forward for your feedback so otherwise and i will see you in the next video hope you like it bye
|
Island Perimeter
|
island-perimeter
|
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water.
Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
**Example 1:**
**Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\]
**Output:** 16
**Explanation:** The perimeter is the 16 yellow stripes in the image above.
**Example 2:**
**Input:** grid = \[\[1\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0\]\]
**Output:** 4
**Constraints:**
* `row == grid.length`
* `col == grid[i].length`
* `1 <= row, col <= 100`
* `grid[i][j]` is `0` or `1`.
* There is exactly one island in `grid`.
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Easy
|
695,733,1104
|
647 |
hey yo what's up my little coders let me show you in this tutorial how to solve the need for question 647 piling drumming substrings basically given the string we need to count how many polynomial substrings there are in this string and the thing is if you consider this input string for example there are six polynomic substrings and as you can see there are some duplicates for example a and basically if this polyndromic substring comes from the different index it's considered as a separate substring same for this double a so here's one double a and there's another double a as well and the last one three a is basically the whole string itself is also a part in drum so we need to return six in the end okay let me just quickly code it and i will go through everything with you in a few seconds okay guys so this is all the code which we need to write and now let me just quickly go through everything and explain you step by step uh what we did and why it works so basically to store our result with the query variable here so outside the methods and after that we are iterating through every single index of the input string from zero until the end and here you can see that we are calling the same method twice however a second time we're calling it with this slightly updated variable the reason for that is that the piling drum uh string can be made from the odd amount of characters and else it can be made from the even amount of characters for example aba is the is one piling drum however it can for example be abb a that's why you slightly need to update the end variable which basically points to the end of the current substring and also there's the start which points to the start and obviously we need to pass the input string itself the positive whole string and we just pass another two pointers and let's just consider the same input string as they give an example so we start with the i is equal to zero right and we call this method right start is zero and is also zero let's check if we will go inside the while loop so start is greater or equal to zero that's correct and is less than the length of the string that's also correct and the character which points which is at index start is exactly the same as the character which is at index end because you know they have the same indexes so they point to exactly the same character right now so we are going inside the vowel it means that we found our first piling drum which is just a single letter a so we update our result volume but after that we decrement the start and increment the end so start is minus one and this one right now basically we kind of expand from the center of where we are at the moment and on the first expansion we will break here and we will not go on the second to the second iteration of the while loop so uh after that yeah this method terminates and we are moving to this one um and now we will consider two characters a and a because as i said the pony drum can consist of uh even amount of characters as well and in this case these two characters are the same so we'll go inside the value we'll update the result and after that you'll update the start end and yeah these conditions will not match anymore so we will not go in the second iteration of the while loop and after that we will increment the i so i will point right now so the start will point to the middle character and on this code the end will point to the same one so again we extract the single character palindrome update the start and end indexes and now they became become and now we can basically expand from the center so we will from here starts your point here and ends will point here so we will extract the whole string itself because it's also a point room and after that here we update this volumes again and we will be out of bonds so we will terminate and we'll go here so start points to this a and you'll point to this a we will extract this foreign drum double a after that we update the values will be out of bonds so we'll terminate you'll go next iteration when i will be equal to two so which is this single character we will extract it once we update the values we'll terminate and we'll go on the next iteration but you know if we do i plus one which will be equal to three this condition will not match you will not work and we will be out of bonds and basically yeah by this moment we found all the piling drums and we just will return them in the end simply as that guys i hope that it was very clear um yeah guys i think that's it for this tutorial please make sure you subscribe to us to my channel and guys challenge your friends to see if they can solve this question or not and i will see in the next video but before that let me just submit and see what's the score and this score is very good so now i can say goodbye to you and enjoy your day
|
Palindromic Substrings
|
palindromic-substrings
|
Given a string `s`, return _the number of **palindromic substrings** in it_.
A string is a **palindrome** when it reads the same backward as forward.
A **substring** is a contiguous sequence of characters within the string.
**Example 1:**
**Input:** s = "abc "
**Output:** 3
**Explanation:** Three palindromic strings: "a ", "b ", "c ".
**Example 2:**
**Input:** s = "aaa "
**Output:** 6
**Explanation:** Six palindromic strings: "a ", "a ", "a ", "aa ", "aa ", "aaa ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and 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
|
5,516
|
1,779 |
let's all lead code 1779 find nearest point that has same x or y coordinate so the question is that we'll be given several points okay like in this example each of the point will be an array of two integers the first one would be the x value x coordinate value the second would be the y-coordinate value along would be the y-coordinate value along would be the y-coordinate value along with that you are given explicit l x and y of which you need to find the closest points out of all these points given okay from this X and Y and the condition is such that the points you need to consider must be either on the same x coordinate okay x value or on the same y coordinate so either X should be equal to the x coordinate value of that point or Y should be equal to the y coordinate of that point okay in that consider then in that case you can consider that point and then find uh the minimum diff distance from the other value say if x value of that point and X is same then you need to see how far it is from y Point okay so and return the index of the point which is nearest to XY coordinate okay and if you find two such Solutions then they want you to return the first one that is found in this s okay so the question is simple so how am I going to solve this I'm just going to go through each of the point and check for the conditions that are given so I'll initialize index variable and minimum variable so index would be minus one so if I do not find any index then I'll return minus1 that's what the question says here and minimum I'll initialize with float uh to Infinity I could do that or I could initialize it with 10 to the power 4 that gives me 10,000 so because that's the 10,000 so because that's the 10,000 so because that's the largest uh the index that can be there right as per the constraint so then I'll go through each point and also take the index of and then check point 0 which means the x coordinate is equal to the X provided by explicitly the of the XY point that is provided if it is equal then I'll go into this block and check if the difference between the Y value given and the y coordinate of the point if the absolute difference between them is less than this minimum that I'm maintaining then which means that I have found the closer coordinate so I'll update my index to the current index and update minimum with this current minimum difference okay else if the y coordinate of that point is equal to the Y value given to us okay if they are equal then I'll check if the difference between the x coordinate x given to us and the x coordinate of the point and their absolute difference is less than the minimum which means we have found new minimum distance coordinate and so I update index to I and minimum to absolute value of difference between X and the x coordinate of the point finally I'll return the index after the loop is over let's run this and see it worked for all three cases let's submit it and that's how we solve this problem
|
Find Nearest Point That Has the Same X or Y Coordinate
|
hopper-company-queries-i
|
You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104`
| null |
Database
|
Hard
|
262,1785,1795,2376
|
1,583 |
hey what is up guys i'm back with another elite code video today we're going to be doing problem 1583 count unhappy friends so we're given a list of preferences for and friends where n is always even and for each person i preference i contains a list of friends sorted in the order of preference in other words a friend earlier in the list more prayer than a friend later in the list friends and each lizard okay so basically uh i'm assuming you've read the problem already if you're here by now so what are the preferences so um each friend has a list of preferences right so for number friend number zero these are his preferences friend number one these are his preferences number two these are press number three these are preferences and these are his preferences order so he prefers one more than he prefers two and he prefers two more than he prefers three so uh for friend zero and so these are the preferences and these are the number of friends we have a number of people we have and these are the pairs so these are hardly paired so we have zeros paired with one and two is paired with three and we want to check whether um these pairs are unhappy and how do we know they're happy basically if zero if one friend uh this is why i think there's a lot of dislike for this question but basically if friend zero prefers another friend and that so each friend how do i explain this so each friend is paired with somebody and if two people from that pair like each other more than the one people they're paired with then uh they're then they're both unhappy right so two friends are paired with two other people right two people are paired with two other people and now if these guys like each other more than they like the people they pay with then they're both considered unhappy because they could have been paired instead and they would have been more happier because that fits their preference a little more so that's that and that's what an happy friend is and we need to keep the count of we mean to count how many unhappy friends they are so the way we're gonna think about this is like this okay um it's actually it's not that hard we want to first ha we want to obviously uh go through all the pairs that's one thing we're gonna have to do so it's definitely n squared because we want to go through all the pairs and check with all the other pairs so we want to check this pair with this pair and check if any of these four people in this list are happy meaning if zero it would rather be paired with two zero and two would rather be paired with each other or one and three would rather be paired with each other or one and two would rather be paired with each other or zero and three would rather be paired with each other so if any of those cases right we know we have another unhappy friend so we know we're going to be iterating over the um pairs twice so it's already n squared and now the only issue is how do we know one friend would rather be paired with another friend and that's very simple we're going to before we start iterating over this or the pairs we're going to iterate over the preferences and we're going to create a hash map and we're going to maintain the order so we're going to do now is we're going to iterate over preferences and then we're going to iterate over this as well right and then we're going to keep track of that so i so friend zero right now for this case has a for has a preference um of one or zero you can say depending on its index for the number one and then one for two and then two for three right you just use their index to keep track of the number of preferences um it's a little tricky because in this case the lower the index that means the more they prefer right it's because one uh friend zero right in this case prefers one more than he prefers two and one is at a lower index which is zero and this is that index of two so that's how you kind of um keep track of that so this is tushar goda's answer i you know has one like let me like i like this answer so we're gonna use that um so what's he's doing here is over here he's creating the preference map as you can see you probably saw it on that i already had it up there copy paste it let me just use this uh in the description because i can edit it so um we have this a preference map right and it's mapping um then we're just filling it up and how are we filling it up well from i to this friend j from this friend i to this friend j right preferences i j will give you what purpose is i j will give you the number of the friend right so friend zero to friend one and then friend two the front three so from friend zero let's say in this case to friend one so friend zero to friend one he has a preference of zero which is the index so zero prefers the one j amount which is index which is zero well it's not really j amount it's kind of remember the lower the index the more they prefer so that's what this is doing so zero prefers one uh zero amount because zero is index right so zero will prefer it and then for two it'll be one j will be one so zero to two would be one so that's what this is doing this is pulling up the performance map and we have all this stuff these are the flags um this will kind of make sense right now in just a bit so then like as we mentioned you want to go over the pairs you want to check each pair with every other pair and we're doing that so we're going to go from zero to the pairs that length and then the second one we'll go from i plus one because when we check one pair with other then obviously we'd only check the other pair with the other pair because if you're checking one pair with another pair then you don't need to you want to make sure you don't recheck that pair with that same pair again so you're just gonna kind of move that forward the second iteration forward so that's that um and then it's really simple from here it looks a little complicated but it's actually really simple we're gonna get uh for the first pair we're gonna get the a and b the first number or the first friend you can say in the second friend all right for zero and one in this case and then for the second pair we're gonna do the same thing we're gonna get two and three right and we're gonna grab the preferences for both of them so how much a prefers b and how much b prefers a and same thing for hair how much this one prefers this one how much two prefers three and how much three performs two so we get the preferences for each one of them how much zero prefers one how much one prefers zero how much two four prefers three how much three prefers two and what this is going to do the same thing you want to grab all the preferences for between one of them so how much zero prefers two i'm a zero force prefers three tongue twister how much one prefers two and how much one prefers three and the opposite of that as well so that's what this is doing right here so now if how much a prefer prefers b is more than or in this case if it's greater than remember that means it's actually less than they prefer them less so how much a prefers b so just which can inverse this as we explain it how much a prefers b is less than how much a performs prefers um yeah how much a prefers who he's paired with right is less than how much a will prefer being paired with the other guy and similarly how much the other guy prefers who he's paired with is less than remember we're inversing is less than how much who he's currently paired with will say he's unhappy and we'll mark him as unhappy and we'll mark both of them understand happy actually right and we're kind of doing that for the same uh for each one of them so there's a little bit of tongue twister explaining this but um we're basically checking how much if zero how much zero is per how much zero prefers one is less than how much sorry how much zero prefers one is less than how much zero prefer is two and how much two prefers three is less than how much two prefer zero then we'll say both two and zero are unhappy and that's what this is doing so preference i to j will mean how much i prefers j and so it's going to check each of them and then we're going to set each of their flags true right and then so because if one is unhappy the other one is unhappy we're going to check all of them all the cases over here if and then at the end of that we're going to go through how many times we found unhappy people and we're going to return the account so that's the general answer a shout out to forgot his name he only has one like i'd like to answer the most so i'm going to use that uh you had a good explanation good clean code whatever why not give credit give a shout out hope you guys enjoyed leave a like subscribe if you want um comment and if you guys want me to actually go through the solution walk through it and type it out instead of just walking through the solution already typed out just let me know in the comments below as well thank you guys for watching
|
Count Unhappy Friends
|
paint-house-iii
|
You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`.
All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`.
However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but:
* `x` prefers `u` over `y`, and
* `u` prefers `x` over `v`.
Return _the number of unhappy friends_.
**Example 1:**
**Input:** n = 4, preferences = \[\[1, 2, 3\], \[3, 2, 0\], \[3, 1, 0\], \[1, 2, 0\]\], pairs = \[\[0, 1\], \[2, 3\]\]
**Output:** 2
**Explanation:**
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
**Example 2:**
**Input:** n = 2, preferences = \[\[1\], \[0\]\], pairs = \[\[1, 0\]\]
**Output:** 0
**Explanation:** Both friends 0 and 1 are happy.
**Example 3:**
**Input:** n = 4, preferences = \[\[1, 3, 2\], \[2, 3, 0\], \[1, 3, 0\], \[0, 2, 1\]\], pairs = \[\[1, 3\], \[0, 2\]\]
**Output:** 4
**Constraints:**
* `2 <= n <= 500`
* `n` is even.
* `preferences.length == n`
* `preferences[i].length == n - 1`
* `0 <= preferences[i][j] <= n - 1`
* `preferences[i]` does not contain `i`.
* All values in `preferences[i]` are unique.
* `pairs.length == n/2`
* `pairs[i].length == 2`
* `xi != yi`
* `0 <= xi, yi <= n - 1`
* Each person is contained in **exactly one** pair.
|
Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j.
|
Array,Dynamic Programming
|
Hard
| null |
1,525 |
hi guys hope you're fine and doing well so today we will be discussing this problem from the lead code which is number of good ways to split a string so it is the 16th problem of the dynamic programming series so if you haven't watched the previous videos you can consider watching them since it will be really helpful for you to understand the concepts in the upcoming videos and if you are new to this channel you can consider subscribing it and pressing the bell icon so that you don't miss any of the upcoming updates so let's get started with this question so the question tries to say that we are given a string s and we have to return the number of good splits so what is a good split it is basically when we are given a string s and we can divide it into two substrings namely left and right and if we concatenate both this left and right substring so they should result into the original string s that we are given and the other condition is that the total number of distinct characters in the left sub string and in the right sub string so in case they are equal so it contributes to a single good split so hence we are required to find the total number of code splits that we can make so let's have a look at the example so in this example if we look if we divided into this part so in the left substring it has one distinct character and in the right there are three so obviously one and three are not equal so this is not a good split so what we need to do here is like if we split in this format so in this format the in the left there are two distinct characters and in the right there are also two distinct characters so hence it contributes to a single type of good split so if we look at the total good split possible for the string they are 2. so now let's see how we can approach to this problem so now if we try to think of a brute force or a knife solution what will it be it will be simply that we will apply a single for loop from i equal to 0 to i less than n and i plus so i here n is the length of the string s and what we will do is we will create two strings so the first string will be left which will be from zeroth index to iath index and string right will be from i plus one to n idli should be n minus 1 because when we are standing at the last index so right string will simply be 0. so we have got these two strings so like if we are standing at the first time so what will be the left swing it will be the left string and this will be the right string and if we move on to like say i equal to 4 so from 0 to 4 this is 1 and the other is this so this is how we are forming these substrings left and right and now what we are required to do is we will simply iterate over this left let's create a variable c1 and c2 so we will just this c1 and c2 is the total number of distinct count of characters in left and right so for c1 is for left c2 is for right so we'll simply just count the total number of distinct characters in the left and distinct characters in the right so how can we do that it is just simple we can put the elements of the left and hash map and elements of right also in different hash map so we will just output their sizes so it will contribute to c1 and c2 size of map 1 and size of map 2. and now we will check if so this is inside this for loop only if c1 is equal to c2 c1 equals c2 will simply i increment our answer so this is the answer that we will be just out returning right so this is what a naive solution will look like so if we analyze the time complexity for it so for this for loop it will take o of n where n is the length of the string and in worst case when we have to iterate over all this right and left substring to check like how many different characters are there so it will also take off and time so this is simply of one operation again of one operation and this is also of one operation so from here we conclude that our time complexity will be o of n square because there will be two for loops so now let's have a look at the constraints that are given to us in the problem so the constraints are simply of the form 10 to the power 5 because we know that in one second we can just perform 10 to the power 8 operations approximately and if we are given in the worst case and as 10 to the power 5 so it will be simply 10 to the power 5 whole to the power 2 which is 10 to the power 10 so this will definitely give us time limit exceeded so now let's have a look how can we optimizer approach so let me just clear this out so what we will do is we will simply keep the count of all the characters while we are iterating on each of the characters of string s so for example we are standing at this particular index which is c so we have iterated upon a c and now this column will contain the total count of all the characters till this character so it will be like it will have two a's and b's will be zero c's will be one and rest of them all will be zero so we are just not keeping it a b c d e f it will go up till z so because we just have taken three characters in this example so that is the reason i have written till f so now let's see how we will fill this grid so firstly when we are add this first character so we will simply keep if the character is a we will simply increase the count to 1 and rest all of them shall be 0 and the next when we move to the next character so what we will do is we will add this a 1 plus we will check to the previous index like how many a's are there so they are simply 1 so answer for this cell will be 2 and similarly is the case with b so how many b's are possible here so it is there is no b at this index plus the total number of b's that were available to us till previous index which is also zero so for this case will be it is zero and for all of them it will be zero so now in case we are standing at c so what we will do is we will first check for a so how many is are available to us up till this index so it is at this particular index it is 0 plus how many of them were available till the previous index which are simply 2 so the total answer for this index will be 2 and for the b it is simply 0 and in case it is c so we will add this 1c 1 plus total number of c's that are possible till previous index which is 0. so for c the answer will be simply 1 and for d e f it will be simply 0 zero and now for the a if we are standing at this index it will be simply one plus the total number of phase till previous index which is two which thus so the answer will be in this case will be three so if we technically also check that there are only three is possible up till this index and that is our answer right so now let's check for b we will again be zero c will be zero plus the previous one which is one so the answer for c will be one in this case for d e f it will again be zero and now when we are at this b so the answer for a will be 3 which is 0 plus the previous one 3 and for the b it will be because we are standing at b 1 plus total number of b's possible till previous index which is 0 so total answer for this will be 1 basically these are all the counts that we are storing and for c it will simply be 1 so let me just fill it out so for this it will be four and here one and zero so this is how we will be filling this grid so now let's take an example like what we are trying to do is by keeping these counts for example we had a c a and we are just keeping the count of a's in this array right so for this the count will look something like 1 2 and 3. so if we want to find out the total number of a's in this range so what we will do is we will simply do like 3 minus this previous index we will subtract from it basically 3 minus 1 which will be 2. so this is how we can verify there are only 2 characters of a and in case we are just required to find out like how many is are available in this range so what we will again do is we just need to keep one previous index also which simply stores a value zero so this is zero yes so for this case we will simply mark these two indices and subtract the value on these two indices basically 2 minus 0 so it will be 0 so that is what we are like looking forward to do something similar in this grid so now what we shall be doing is since we are given the string as a c a b a so now we will be dividing this string into two sub strings so we just require one for loop like this and then we will be taking out the total number of count of distinct characters in this string and in this string so earlier what we were doing is we every time i trade iterated on this string and this string to find out the total number of distinct characters but after we have created this grid our operations have really simplified to just o of 1 or to be precise it is just o of 26 let's understand how so just let me take one case where it is a good split so if we divide it into the string and this string so if we are required to find out the total number of distinct characters in the left substring so it will be simply we will be standing on the c index which is here and we will simply find out the total number of values that are not equal to 0 which are this 2 and this one so they are basically 2 and in case we require to find the total number of distinct characters in this right string so what we will do is we will simply stand on this a and subtract the value at this c which is this a and this c so why are we subtracting just to show you that since c is present in this left string so definitely if we want to check that is it present in the right string what we will do is if we stand at this a and this value should be subtracted which comes out to be 0 and hence this shows that the total number of c's that are possible sorry available in this right string is 0. similarly we will be doing this thing for all the characters here so we'll take 4 minus this 2 so it is basically 2. here then we will again stand at 1 minus this 0 which is 1 and again we will go to this c character 1 minus and this value which is 0 and similarly so the answer for all of the values will come out to be 0. so now we have to see the total number of characters whose count is not equal to 0 which is 1 which is a character second which is b character so here the count comes out to be 2 so hence they are equal so hence this contributes to one of the answers of good splits so this is similar to range query problem where we are not required to just update the values but we are just required to find the total number sum of values in a range so now let's see how we can code this problem so firstly i'll be creating a dp array of size n basically 26 rows because there are 26 characters and n columns and let me just define n yes so now i'll start for loop from 0 to n and simply if i is equal to 0 i'll do something or else i'll do something so firstly i am just trying to build this grid so if i is equal to 0 we will simply just increment all the characters like on which character we are standing on and in case we are at the next character so we will simply increment these characters and what we will increment them to we will add the previous column also because we are keeping the total count till this index so dp of s dot cat of i minus a of i plus and in this case what we'll do is i'll start another for loop from j is equal to 0 to 26 and j plus and here we will simply dp of j of i is equal to dp of j of i minus 1 so basically here we are just adding the previous row and then we will again do the same thing which is this yes so now we will be dividing the given string into two substrings which is string left is equal to s dot substring from 0 to i and string right to s dot substring from i plus 1 to n basically so now we'll take out count c 1 for the left sub string which is basically 0 initially and now we'll apply the for loop from 0 to 26 because we have to find the distinct count of all the characters if dp off j of i is not equal to zero what we will do is we'll simply c1 plus so this is for the left and we'll create c2 variable for the right substring so we'll do the same thing but it is just that here it should be dp of i of j of i minus dp of j of i minus 1 not exactly i minus 1 here it should be dp of n minus 1 so from the last we are subtracting this last we are subtracting if this is the i we are standing on so we will subtract this i values so yes this is c 2 plus so now if c1 is equal to c2 we'll simply increment our answer which is i'm creating the answer variable is equal to 0 and i'll simply return this answer now let's see is it working correctly yes so now let's try to submit this problem so it is giving time limit executed so the reason actually why it is giving timely limit exceeded is that we actually don't require to again write this left hand right substring because it will again take off end time here so this for loop o fn and creating these substrings will also take often so we don't require actually them so let's now try to submit it if it is getting accepted yes so yes we have got the right answer so the time complexity for this problem is 26 multiplied by n which is basically o of n so i hope you understood the solution to this video and if you appreciate my work you can consider subscribing to my channel and giving thumbs up to this video so let's meet in the next video till then bye
|
Number of Good Ways to Split a String
|
queries-on-a-permutation-with-key
|
You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make in `s`_.
**Example 1:**
**Input:** s = "aacaba "
**Output:** 2
**Explanation:** There are 5 ways to split ` "aacaba "` and 2 of them are good.
( "a ", "acaba ") Left string and right string contains 1 and 3 different letters respectively.
( "aa ", "caba ") Left string and right string contains 1 and 3 different letters respectively.
( "aac ", "aba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aaca ", "ba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aacab ", "a ") Left string and right string contains 3 and 1 different letters respectively.
**Example 2:**
**Input:** s = "abcd "
**Output:** 1
**Explanation:** Split the string as follows ( "ab ", "cd ").
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
|
Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning.
|
Array,Binary Indexed Tree,Simulation
|
Medium
| null |
58 |
hey everyone welcome back and let's write some more neat code today so today let's go a little easy on ourselves and solve the problem length of last word if you're a beginner i would recommend solving this problem maybe you can try solving it by yourself and then compare your solution with mine later in the video we are given a string s consisting of some words and these words are separated by some spaces among all of these words in the input string we just want to return what is the length of the last word that occurs in the string and we're guaranteed that there's going to be at least one word inside of the string so let's take a look at a example the first example we have the first word hello separated uh with a single space from the next word world and then that's kind of the end of the string so what's the length of the last word well the last word is here world its length is five so we can return five the second example is a little bit more interesting so in this case we have some leading spaces multiple leading spaces we have a word then another space another word and then a few extra spaces another word a few extra spaces again another word one space and then this is actually the last word but even after the last word there are some extra spaces so in this case moon's the last word its length is four so we can return four this is about as interesting of an example as we can really come up with there won't be any you know other edge cases for this problem right all we could be given is a string with some spaces in it right so there's many ways to solve this problem you can kind of just iterate character by character every time we get a space you know just ignore it every time we get a character keep track of whatever the length of the current word is so for example we see the first character f that's one the next character l so then the length is two the third character y so the length is three and then we get to a space when we get to a space we basically want to reset the length because the next word you know is going to start back at zero so we'll set reset this back to zero get to the next character m increment this by one the second character e set this to two and then again have a space so reset it back to zero and then kind of just iterate through that and then whatever the length of the last word was we could end up returning that a slightly easier way you might think of is why do we even have to start at the beginning anyway why iterate through the entire array it's kind of a waste of time why not actually just start at the end and then get the length of the first word starting from the end and that's kind of how i'm going to do it's more efficient and i think it's a little bit easier to code so what we're going to be doing is since we could have some leading white spaces right the first phase of the algorithm is just going to be eliminating these leading white spaces right so every time so basically while we see a space character we're going to increment our pointer i and then keep shifting it until we finally get to the non-space character in this get to the non-space character in this get to the non-space character in this case that's going to be at this word n and then the second phase of the algorithm is basically going to be counting how many consecutive characters that we see before we either reach the end of the string or before we reach a space character so basically increment the length until we see a space or reach the end of the string in this case we'll see n-o-o-m our length will be four then n-o-o-m our length will be four then n-o-o-m our length will be four then we'll see a space character and then exit our while loop so then the second phase of the algorithm will be completed and we have the result that we want to return and then we can go ahead and return that result now the time complexity we might potentially have to iterate through the entire string if we have you know just a single word in the string so the time complexity is going to be big o of n there's no extra memory needed yes we have a variable that's keeping track of the length but it's just a single variable nothing more so the memory complexity is big o of one so that's the solution we're going to be coding so let's jump into that now okay so before we actually jump into that first phase of the algorithm let's initialize a couple pointers that we're going to be keeping track of one is going to be i as i mentioned and another is going to be length and i is initially going to be set to the end of the string right because we're going to be starting at the end so we'll take the length minus one that's the index of the last character and our length initially is just going to be set to zero so first phase of the algorithm is eliminating the leading white spaces starting from the end so while the character at index i is equal to a white space uh we're going to be shifting our pointer we're not going to be incrementing it we're going to be decrementing it because remember we're starting all the way at the end and then working our way towards the beginning so that's the first phase of the algorithm next phase is going to actually be counting the characters right actually determining the length so now our i character is going to be at the first you know basically at some word and we want to make sure i is in bounds right if we reach the end of the string we can of course exit this loop so while i is greater than or equal to zero and while the character at index i is not a space right because we want to get the length of a word if we ever get to a space character we can safely exit this loop so while we see an actual character we can go ahead and increment the length by one and once we're done with that we know we have the length of the last word so then just return that length i think this is a pretty good problem for a beginner especially because there's definitely multiple ways to do this function you can even use built-in functions like taking s and built-in functions like taking s and built-in functions like taking s and then splitting the words but i feel like that's a little bit cheating and that definitely makes things a little bit too easy for us oh uh one thing i just realized uh don't forget like me to actually increment your pointer because or in this case decrement the pointer because you don't want to get stuck in an infinite loop so of course i make that mistake when i'm solving an easy problem but yeah so this is the entire code on the left you can see it's you know this overall time galaxy this is as efficient as you can get it is just you know on leak code for some reason it just says it's somewhat slow but that's not super important i do hope that this was helpful let me know if you came up with a different solution if it was helpful 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
|
Length of Last Word
|
length-of-last-word
|
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
**Input:** s = "Hello World "
**Output:** 5
**Explanation:** The last word is "World " with length 5.
**Example 2:**
**Input:** s = " fly me to the moon "
**Output:** 4
**Explanation:** The last word is "moon " with length 4.
**Example 3:**
**Input:** s = "luffy is still joyboy "
**Output:** 6
**Explanation:** The last word is "joyboy " with length 6.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only English letters and spaces `' '`.
* There will be at least one word in `s`.
| null |
String
|
Easy
| null |
952 |
hello amigos welcome to cp edit in this video we are going to explain today's problem from the august lead coding challenge and it is called largest component size by common factor so what it says is we have a non-empty so what it says is we have a non-empty so what it says is we have a non-empty array consisting of unique positive integers and uh there are a dot length nodes and we have an edge between any two nodes if they share a common factor greater than one or we can say if we if they have any common prime factor then there would be an edge between those two nodes and the node values are a i and a j we need to return the size of the largest connected component in the graph for this example we see that four and six has two as their common factor six and fifteen has three and fifteen and thirty five has five so all of them are connected with each other it also fully follows the transitivity relationship okay then the answer is for an example one in example two only 20 and 50 share a common factor which can be 2 and 9 and 63 share the common factor which is 3 but these two do not share any common factor with 9 and 63 so the maximum size of any component is 2 in this case it is 8 is this case and these are the constants now let's see how we can solve this problem now i would be using i would be solving not uh i'll i solve this problem using disjoint set union let me just first write down few key data structures and variables which i used for my solution the first one is all factors it is a set with which contains all the prime factors which uh prime factors observed or found till that point this is a set and the second one which i mu which i used is fact id yes in this join set first of all i created and uh we first of all we would be having n sets as we have n nodes in our graph so we have to convert it into a graph for n elements we have n nodes and every node has a unique id associated with it so fact id is a map which tells me and for we have a factor there and it tells me the node id it belongs to so yes let me also tell you one more thing in each of the node suppose i have a node in disjoint set this is a just one disjoint set in this i'm maintaining factors prime factors which belong to this set and also i'm maintaining another value which is size which tells me the size of this disjoint set that is the number of nodes in that design set initially the size is one for all then all the sets so we have size there and we have prime factors so this for any particular factor it tells me the node i the set id it belongs to and yes i have just mentioned size it tells me the size of any disjoint set it is also a map so for any id that is the id of any disjoint set it will return the size of that disjoint set so and uh what else i used and yes there also i also use one parent i tells me what is the parent of that this of this node because in this join set we can we have we assign parents to every node like structure is uh something like this we have a one node with which represents the whole disjoint set and all other disjoint sets uh kind of our descendants or children of this particular node okay so parent of this node is this parent of this is and this one and suppose we have another node down here then the parent of this is this node the node 1 so yes i am maintaining a parent i and initially for any node parent i is equal to y as initially we have a disjoint set of size one so it we just have one node on our in our disjoint chart initially now let's see what we can do to solve this problem yeah so i have mentioned suppose this is one disjoint set i'm maintaining a list of factors which belong which belongs to this disjoint set let's say those are f1 f2 f3 these are the factors and i also have a size here which tells me the size of this disjoint set and i have id of this disjoint set and suppose i have one another disjoint set it has its separate id let's say it is id 1 and 92 it is size 1 and it is size 2 and it also have some factors let's say f4 and f5 now if i see if i find out any new disjoint set let's say it has id3 but it has factors f4 and f1 now i see that uh f1 is present in both of these disjoint sets so it means that there must be a some number which is present in this disjoint set by number i mean some node because we can have multiple nodes in one disjoint set which has a factor f1 and also in this particular disjoint set we are having some node which is having f1 as its prime factor so there should be an edge between those two nodes and if we connect these two those two nodes it also means we are in a way connecting or merging these two disjoint sets then after when we see that we have a common prime factor in these two disjoint sets we would be merging these two disjoint sets and i would be updating this size 3 is equal to 1 which is the size of this like not one let's say size three which is the size of this disjoint set is equal to size three plus size one because now i merged this earlier this uh disjoint set one node uh the set to this size has increased and i'm updating its parent now parent of this one is equal to three now this set is actually is it is a descendant of this set so i updated my parent and i updated size this these two things i'm doing in the union operation this is called union and also i'm also seeing that f4 is also present in set three as well as set to so i also need to merge these two sets so now after merging i have actually now i would be updating my size 3 is equal to size 3 plus size 2 also parent of 2 is equal to 3 because now this one is a descendant of this so we will keep on doing the will try to do we would be continuously doing this process and at the end we would be finding out the maximum size of any disjoint set because if we yep i think that's all for the explanation part don't yes there is one more thing in my solution i have used c function it is used to find out the prime factors of any uh num in log and time well there is a i will be sharing the link of some blog where you can learn about if you do not know about this c function i will be sharing a link in the description box where you can learn about this c function and for any to find out the prime factor of any number it will take logan time but it also have some pre-computation it also have some pre-computation it also have some pre-computation and that pre-computation will and that pre-computation will and that pre-computation will require and into log of login time so as far as our constraints are concerned this will not cause any problem to our solution so i have used this thing it will return it can be used to find out the all the prime factors of any number okay i hope you have uh what my approach i think you know if i see that i need to explain anything else during my code explanation i'll come back to this diagram so let's see the code now yep and this is the max set size which i would be returning at last at the end and this is the same function which is pre the precomputation which i was talking about this c function i wouldn't be explaining how it works i would be sharing the link the time is and into logan and this get factorization what it does is it returns a set which contains all the distinct prime factors of integer x so it can i would be using this function this is all for these two function yep so now in my for loop i'm going through all the elements first of all i'm finding out all the distinct prime factors of this current element of ai that is it will take all or it will take logan time now initially i am the size of this disjoint set is one as at this point it only contains itself and also the parent of this node is itself like it is itself its parent okay as initially we have only one node in our distant set now for current factors the current factor stores all the prime factors of a i'm seeing yeah all factors yeah i mentioned about all factors contains the prime factors which i have seen till this point like suppose if i am if right now if i am at index i then all the prime factors which i have seen from 0 to index i minus 1 all the distinct prime factors would be there in all factors so if i see that i have already seen this prime factor which is also a factor of this current number it means uh i have some disjoint set with which contains this number okay so it also must have some array element as well which is having the same prime factor which i am seeing in ai so then i need to merge the current disjoint set with some with the previous one as i explained in this diagram fc for suppose i am adding this one set at this moment so i've seen f1 epsilon f1 is already present here so what i need to do i need to merge it one by one i am going through these factors of my new disjoint set and if a factor is already present in some other disjoint chart then i need to merge them otherwise i'll just go on with my process yeah and uh i'm seeing if what is the parent of that disjoint set that is the parent of this which is already having that factor i'm seeing if the parent is not equal to i that is if it does not points to this current node then i am changing its pointer and then i went to union and in union i'm increasing the size of my current disjoint set and changing the parent of the older disjoint set to the new disturbance set yep this is for union part and now i'm changing the fact id that is the current factor belongs to disjoint set which is having id as i and i'm adding my this current factor to all factors as right now i have already have seen this factor which is x so i'm adding a two over factor and uh after doing all this in each of the iteration i am seeing if the size of the current disjoint set is the largest one i'm taking the maximum out of it at the end and returning its answer so yep that's all for this problem i think for to solve this problem you should be having knowledge about you should know about disjoint set unions and how it works what are the key properties and uh key methods which are involved in disjoint set union okay then yep take care and sayonara yep i'm not going at this moment so if you like our videos then please do subscribe as around 85 percent of our viewers are not subscribed to our channel yep yet this is the moment where i say goodbye
|
Largest Component Size by Common Factor
|
word-subsets
|
You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**.
| null |
Array,Hash Table,String
|
Medium
| null |
980 |
Unique 53 is given and you are the ending point and -1 from the obstacle on which you cannot walk. -1 from the obstacle on which you cannot walk. -1 from the obstacle on which you cannot walk. Okay, so what you have to do is to reach from the starting point to the ending point. All the zeros and ones on which you can walk. Can cover all of them, you have to walk on all of them, okay so like this is our van, starting point of our van and 2K ending point and these are all zeros and what is this, so what you have to do is to cover all the zeros, take such a path. So which leaf is there in it, this is the thing, okay, this is one thing, and the other thing is that we cover all the zeros and also reach 2, what do we have to do, we have to cover all the zeros and you We have to reach from van to 2. We can throw zero and one cell in one go as if we have traveled it in steel. We have to cover all the zeros and if we have to start from all the van then we can cover all the zeros. We will take the count because what we want is the same punch in which we cover all the zeros and if zero is okay then we will change the thing in which we hit all the zeros and if all the zeros are covered then first of all we want the zero's account then we will take A on the court. Let's go because it is simple for us, so what can we do, we have taken an account at the place where our hero is and we have taken an account at the place where our van is, it is okay because we will start from the van and we have taken the account of all the heroes, so it is okay. Total, we have taken the account, how many totals are there in it, like it is 345678910, what is there in it, where it is, it has become our starting point, so what will we do, we will simply run DFS from WAN, now what will we take, we will take widgetized because like we will use this WAN Okay, then if we go from zero to this zero, if we do n't go back to this zero, then for that we will take it as if our second new part will start, it is widgetized, it is our office, what will we do, then we will move for directional van. This one went to zero, this one went to you and we got the value of the account, then one, we got the answer, okay, and if it doesn't happen then what will we do, if we do back towers then this It will be fine, it will be fine, so this will be done, so this is done, then this is done, we will not update the answer in this, okay, the answer will not be updated here, then we will travel back and forth. What will happen to us, it should be unvested, it is unvested then where will we go, we can go in this direction also, we will go ok and how much will be the time complexity, when we asked the question, what do we have, like we have asked, what is the number of sales, number of Columns have been given
|
Unique Paths III
|
find-the-shortest-superstring
|
You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles that we cannot walk over.
Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_.
**Example 1:**
**Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\]
**Output:** 2
**Explanation:** We have the following two paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
**Example 2:**
**Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\]
**Output:** 4
**Explanation:** We have the following four paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
**Example 3:**
**Input:** grid = \[\[0,1\],\[2,0\]\]
**Output:** 0
**Explanation:** There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 20`
* `1 <= m * n <= 20`
* `-1 <= grid[i][j] <= 2`
* There is exactly one starting cell and one ending cell.
| null |
Array,String,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
| null |
507 |
hi everyone welcome back for another video we are going to do analytical question the question is perfect number a perfect number is a positive integer that is equal to the sum of its positive divisors excluding the number itself a divisor of an integer x is an integer that can divide x evenly given a integer n return to if n is a perfect number otherwise return false let's work for the code we iterate over integers up to the square root of n to find the factors of sum we sum up all such factors and check if the sum is equal to the noun time complexity is the square root of n space complexity is o1 thanks for watching if this video is helpful please like and subscribe to the channel thank you very much for your support
|
Perfect Number
|
perfect-number
|
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly.
Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`.
**Example 1:**
**Input:** num = 28
**Output:** true
**Explanation:** 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
**Example 2:**
**Input:** num = 7
**Output:** false
**Constraints:**
* `1 <= num <= 108`
| null |
Math
|
Easy
|
728
|
1,514 |
hello guys welcome to deep codes and in today's video we will discuss liquid question 1514 that says path with maximum probability so guys although this question is of an easy medium level but it is important that you visualize that how the algorithm works in the back end so yeah guys stick till then and watch the complete video now here you would be given one undirected graph and the edges will consist of some value and that value denotes the probability okay so uh that would be one probability associated with all the edges and the given graph is undetected further you will be given two nodes that is the start node and the node and you need to return the path with maximum probability as a question says that you need to return the path from start node to node with a maximum probability the output is not actually the path but the probability of that path okay and that probability must be up to up till 5 decimal places so if you take a look at the first example here the start node is a node 0 and the end node is a node two and these are the different edges with ah that probability now if you take a path from node 0 to node 2 directly see there is a direct path but the probability would be 0.2 if you go from probability would be 0.2 if you go from probability would be 0.2 if you go from 0 to 1 and then one two uh two then the probability would be 0.5 multiplied to probability would be 0.5 multiplied to probability would be 0.5 multiplied to 0.5 same so that would be nothing but 0.5 same so that would be nothing but 0.5 same so that would be nothing but 0.25 and this 0.25 is greater than 0.2 0.25 and this 0.25 is greater than 0.2 0.25 and this 0.25 is greater than 0.2 so yeah the VC would select this path and return 0.25 is our answer and return 0.25 is our answer and return 0.25 is our answer so guys um the question is very much simple here that we simply need to select the path with a maximum probability the probability of a path can be calculated by multiplying all the probabilities of that path and yeah at the end we need to return that probability output okay now this equation has some pretty precise knowledge of the graph of algorithms like Bellman fault algorithm or Dexter's algorithm then you must know these two algorithms uh to solve this equation so these are the prerequisites okay so but how you can for derive the intuition to solve this equation so one thing is see if in a given undirected graph if you don't have any weights or any cost associated with the energies then you can simplify the shortest path by using breakfast search right then the simple BFS would work to find the shortest path now whenever you are given some additional thing like a cost of the edges weight of the edges or the probability see probability is nothing but one extra parameter added to the edge right so that can be treated as a weight so given this type of extra parameters and then in that case if you if your occasion asks to find what is the best path then one such uh algorithm that will help you is nothing but dextra's algorithm so that's why I just told you earlier that you must have the knowledge of Dexter's algorithm how fundamentally distress algorithm will work then yeah we can make a slight modification in the dextrose algorithm to get the answer that we want so uh here uh since we need to consider edges weight or the probability so we would require a distance algorithm and simple BFS won't work here now originally the extras algorithm is something like this it is nothing but a BFS algorithm plus we solve the edges based on the cost in ascending order so in the distance algorithm we would either use minimum hip or a side and both of them sort the edges based on the cost in ascending order okay so this is the original Dexter's algorithm now here in this question we are asked to find the path with the maximum probability so if you trade this probability as a cost then we have to sort in descending order and not ascending right because we want maximum probability path so we would modify distress algorithm in such a way that we get the path with maximum probability so this BFS would remain the same but instead of sorting in ascending order here we would sort in descending order right that's why we would use Maxim okay so any in the in this originally BF original Dexter's algorithm we can either use set or minimum hip they both return the values in ascending order but here we want maximum probability path so we have to make uh the nodes to arrange in descending way so that's why we would use maximum Apo so guys this is a small modification that we would do in the Dexter's algorithm so if you uh if I would say that half the extras algorithm would work here then let's make a dry run and visualize how it works so assume this as a graph this is an undirected graph and this is the start node and this is the end node okay and these are the probabilities of each of the edges now we would initialize the priority queue or the max hip by 1.0 there is a probability as one and by 1.0 there is a probability as one and by 1.0 there is a probability as one and starting node so inside the priority queue or the max save we would take a pair of double ending so this would this is a double value and this is the integer value so we would take a pair of double and eight and we would initialize the probability one and a starting node is see the starting node has a probability one right and yeah and afterwards we from the starting node we will try to just explore what all nodes can be reached from the starting node okay so in the BFS what we would what we do usually do is we initialize the queue so this is the initialization of the queue and then in the next step what we will do we would pop out the topmost element or hear the element with the maximum probability so we would pop this element out and then try to explore all the adjacent nodes of this node so here the adjacent node are 1 3 and 2 okay so then from node 0 to node one the probability is 0.5 so we update one the probability is 0.5 so we update one the probability is 0.5 so we update the probability as well as the value one then the next node is the node three the problem with the probability 0.3 so yeah we add this the probability 0.3 so yeah we add this the probability 0.3 so yeah we add this and then 0.1 with two okay now the next and then 0.1 with two okay now the next and then 0.1 with two okay now the next thing is we would take the node with the maximum probability so we'll pop this node and try to explain its adjacent node so adjust the node of node one is node three see node 0 is already visited now to keep track of a node that is already visited what we would do is we would create one vector and that will store the value of uh the probability at which it was visited so let's say we would store that in a vector we would store Vector of a node zero it was visited so initially at the probability of vector of node zero was one right so yeah we've marked it this one uh then yeah let's say we visited uh node one with a probability 0.5 we node one with a probability 0.5 we node one with a probability 0.5 we visited a node 3 with a probability 0.3 visited a node 3 with a probability 0.3 visited a node 3 with a probability 0.3 see in this step I am talking about this step and then we visited node two with the probability 0.1 okay the probability 0.1 okay the probability 0.1 okay now here if you see that V from 1 in this tab from 1 we can again visit node three now do we have to visit or not so that decision is made by comparing the values of the probability so initially we visited node 3 with the probability 0.3 0.3 0.3 now if we visit from Node 1 to node 3 then the probability would be 0.5 then the probability would be 0.5 then the probability would be 0.5 multiplied by 0.7 so that is 0.35 so multiplied by 0.7 so that is 0.35 so multiplied by 0.7 so that is 0.35 so yeah this is a better probability then the original one so we update this value to 0.35 and that's why we push this node to 0.35 and that's why we push this node to 0.35 and that's why we push this node 3 inside our priority queue so this decision that do we have to again visit this node or not that is made by comparing the probabilities that is the initial probability as the probability of visiting the node in the current iteration that is from one to three so yeah that's why we change uh the Broadway to 0.5 because it is the Broadway to 0.5 because it is the Broadway to 0.5 because it is greater than the previous and also we added that node into our priority queue now in the third uh iteration we would remove this the one with the maximum probability from the priority queue and try to explore the adjacent so adjacent of node 3 is uh Node 1 and node zero but if you see that uh visiting uh node 3 for node 0 from node 3 is not good because the probability is 0.3 but node because the probability is 0.3 but node because the probability is 0.3 but node 0 is all already probability of zero of one okay there is already better probability here now if you visit uh this three to one then the probability would be 0.35 then the probability would be 0.35 then the probability would be 0.35 multiplied by 0.7 this would be the multiplied by 0.7 this would be the multiplied by 0.7 this would be the probability so this would result in something say 25 377 okay this would be the answer okay now 0.225 is not better than this okay now 0.225 is not better than this okay now 0.225 is not better than this right it is not better probability see if you are visiting Node 1 from node 3 then you would multiply 0.35 and this then you would multiply 0.35 and this then you would multiply 0.35 and this Edge cost right you will multiplying this probability and this probability so that would result in 0.225 and that is that would result in 0.225 and that is that would result in 0.225 and that is not better than 0.5 so we won't visit not better than 0.5 so we won't visit not better than 0.5 so we won't visit node one now adjacent of three is two yeah two is also addition of three to calculate 0.35 multiplied by one so to calculate 0.35 multiplied by one so to calculate 0.35 multiplied by one so it is nothing but 0.35 okay and it is nothing but 0.35 okay and it is nothing but 0.35 okay and previously node 2 has a probability of 0.1 but this answer is better than 0.1 0.1 but this answer is better than 0.1 0.1 but this answer is better than 0.1 so we would update this to 0.35 that so we would update this to 0.35 that so we would update this to 0.35 that means we have found one better way to visit node 2 that has better probability and that's why we were again push the node 2 with 0.35 probability to our node 2 with 0.35 probability to our node 2 with 0.35 probability to our priority view okay we have pushed this value now in the fourth iteration we will pop this out now whenever they pop any element from this priority queue we would check whether that element is the end node or not so yeah 2 is our node so we would stop and return the probability it is containing as our answer because that is the best probability that we can have here okay got it like the other probability is to reaching the node two would all would be lesser than 0.35 because you would be lesser than 0.35 because you would be lesser than 0.35 because you can easily get this that we are using the maximum map here so every time when we visit the node for the first time then that would be the best probability okay so here we are visiting the node 2 for the first time and that would be the best probability all right so 0.35 is the balance and we would stop so 0.35 is the balance and we would stop so 0.35 is the balance and we would stop so the core for this is also easy not that difficult here so we created the graph of intentable so intake will contain the node and double will contain the uh probability so we push all the edges inside the graph and then we took the makeshift priority queue we push probability as well as the start node and took this Vector to check whether the node V is visited and if it is visited then what was the probability so we initialize 0 for all the nodes initially okay then we uh see one thing I forgot here you also need to make start equal to one okay also do this here now further this is a typical BFS so what we do in Red first search is take the topmost element of the queue then try to then we check whether that element is the end and index or the end element or the end node yeah in that case simply written the answer else try to extort the different neighboring elements of the current element and the decision to take the neighboring element into our BFS relies on this calculation of the probability that means the initial probability present in this Vector if that is lesser than the current probability so there is current dot Force so the probability of the current node multiplying by The Edge right so yeah if we get a better probability then we would update this Vector b as well as push the new uh the element with the new probability into our priority queue so at this way we would recurse until we get this condition so if it is not possible to get this condition in the end we would return 0 as we hear from here we were we are dig already returning our answer okay so guys it is simple right if you would have known how to use priority queue and how distance algorithm work then this question was very much simple to do okay and now talking about the time and space complexity the time complexity here is M plus n log n by m because here we are traversing M edges so here I am considered I have considered M as number of H and N as number of nodes so in order to build this graph we have two towers M times so that's why this M plus this ah BFS call will take n log n so ah let us say if there are n nodes and since for each end time we are using priority queue that is uh insert as well as Pop operation so that's why it would be n log n time complexity and space complexity is M plus and M for this graph and N for the max shape that we are using so yeah guys that's all for this video if you guys are still any doubts and do let me know in the comment section make sure you like this video And subscribe to our Channel thank you
|
Path with Maximum Probability
|
minimum-value-to-get-positive-step-by-step-sum
|
You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probability of success to go from `start` to `end` and return its success probability.
If there is no path from `start` to `end`, **return 0**. Your answer will be accepted if it differs from the correct answer by at most **1e-5**.
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.2\], start = 0, end = 2
**Output:** 0.25000
**Explanation:** There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 \* 0.5 = 0.25.
**Example 2:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.3\], start = 0, end = 2
**Output:** 0.30000
**Example 3:**
**Input:** n = 3, edges = \[\[0,1\]\], succProb = \[0.5\], start = 0, end = 2
**Output:** 0.00000
**Explanation:** There is no path between 0 and 2.
**Constraints:**
* `2 <= n <= 10^4`
* `0 <= start, end < n`
* `start != end`
* `0 <= a, b < n`
* `a != b`
* `0 <= succProb.length == edges.length <= 2*10^4`
* `0 <= succProb[i] <= 1`
* There is at most one edge between every two nodes.
|
Find the minimum prefix sum.
|
Array,Prefix Sum
|
Easy
| null |
377 |
hey so welcome back and there's another daily Echo problem so today it's called culmination sum uh four I think that means four and so essentially what you're given is an array called nums and a particular Target and all that you want to do is find some combination of these numbers that add to that Target number and so one catch here is you can actually use a particular number multiple times and so if you do one well that adds to four or one two and so forth so in this case you can find that there's seven different combinations of numbers within this array that reach this target okay so this is actually a dynamic programming problem that's so and that's because well you can actually format this in a way that if you solve multiple smaller sub problems you can solve a larger one and so the way that we can kind of phrase this I guess in sense of a recursive relationship which I typically start with is say if we're trying to reach this target with these numbers initially start at zero and you can say okay I can either add one or add two or add three and so then that brings you to the state of okay you now have a total sum of one two or three and so say if you started down this path then you would have three more options and once again we're trying to reach four that's our goal and so we can either add another one to get to 2 sorry or we can add 2 to get to 3 or we can add three to get to four and well that is one possible path actually and then so forth you can kind of continue on from here so you can either add a 1 you can add two to get to four oops sorry you add one to get to three you can add two to get to four or you can add three but well two plus three is five and well we don't want to go down that path but we did find another Apostle path so expand this once again if we added one here that would bring us to four and that's another possible path but you can see we didn't really expand these potential paths and they would also lead to other possible solutions but this is basically what we want to do and we can actually solve this in a relatively good time and space complexity um using that approach so first I'll show you that approach using the top-down memorization and then we'll top-down memorization and then we'll top-down memorization and then we'll look at a little more clever uh bottom-up approach that's kind of the bottom-up approach that's kind of the bottom-up approach that's kind of the true dynamic programming way but let's start off with kind of the simpler way which is using top down minimization and so we're gonna create a DP function and this is kind of templated code here that you usually write when you want to do this in Python and so initially we want to Define our base case and well that's going to be okay once we reach a Target that is kind of greater or equal to or once we reach a number that's kind of greater or equal to our Target then we want to stop there and so if our current number is greater than or equal to our Target then we want to return kind of true if our number Hits that Target otherwise it will return false and just say okay we've added too many numbers that's greater than this possible Target and that won't be accepted otherwise we want to kind of continue parsing on from here and so we want to continue but we're going to expect to return like some results some final amount here and so initially this amount is going to be zero but we want to add kind of the number of combinations that we can get here all right and so we can reach these n case or we can kind of reach our Target by adding all the numbers or a any of these numbers in our nums array okay and so basically all that we want to do is this is like the current number or the current kind of uh number that we're at so we could have reached maybe the state two and to get to 4 well we can either add one or we can go down two or we can add three so this kind of represents the current number that we're currently at but we can go down these kind of three possible paths that's defined here right it's all that we want to do is then say okay let's call our current function with a new number which is essentially the current number Plus this new number that we're iterating through here all right and so all that we want to do really is just say okay let's add to our current result uh one if this ends up returning true and that we hit our Target all right and so let's go ahead and run that looks pretty good and success so um for time it's base complexity uh what this is going to be is basically an arrow down here just uh o of the target times the length of the nums array and then the space complexities of Target because while we're caching it in that kind of recursive stack that we're creating here is going to be at most uh the size or the number of numbers in this target all right and so now let's go ahead and we're going to look at how we want to do the bottom-up approach using kind of the bottom-up approach using kind of the bottom-up approach using kind of true dynamic programming and so similar thing here but typically you go from a what is it a implicit um array or implicit lookup to a more explicit style so you go from like a DP function to more of a DPA array or DP hash map and so let's go ahead and Define a dictionary here that's initially an integer and typically you want to start with a base case here and that's going to be at index 0 we're going to say that okay basically this is going to represent um at least at this step this is going to say we're going to set this to one and all this means is that there is one ways to add to zero all right and so in that case it's basically not including any of these numbers it's kind of an option here all right and so essentially what we're going to want to do and this is a very common pattern that you're going to learn from here is that okay let's return basically the number of ways or the number of combinations that we can make and that's going to be stored at the Target and so essentially this default dictionary is going to say okay once we reach and we're going to build from zero to our Target so like zero one two three and then finally four and then the fourth will contain basically a number of ways to add to this target all right and so to do that all that we want to do is we'll just iterate oh I have to click on here again there we go and so we'll just iterate for basically I in the range of our Target plus one since it's non-inclusive Target plus one since it's non-inclusive Target plus one since it's non-inclusive and so we're just going to go from like zero all the way to our Target calculating the number of combinations and we'll just reuse pre-computed and we'll just reuse pre-computed and we'll just reuse pre-computed results all right and so this default dictionary here is essentially going to store or kind of cache those results so basically moving forward what we're going to do is we just say okay we have this many options so Four Non n enter nums array we want to iterate through the three possible paths or at least in this case there's three in this case there's only one and so we just want to say okay at this number right so the current number that we're kind of calculating its number of combinations is going to be essentially equal to the DP at the let's think here current number minus n and so I minus n and so what this is going to represent to say we're at the number two here so say this is currently at 2. and say the current number in our numbers array that we're looking at is one then to get to 2 it's basically going to be the number of combinations is going to be basically okay we're going to look at DP at one so how many combinations or how many ways can we calculate how to get to the number one and then basically we just want to add this number to it and so basically we're just taking however many paths it took to get to DP of one and adding it to the current number 4 2. all right and so let's go ahead and run this looks good and success so yeah I hope that helped a little bit um typically I like to do the top demo minimization approach and then try to figure out how to translate that to a bottom-up approach but yeah I hope this bottom-up approach but yeah I hope this bottom-up approach but yeah I hope this helped a little bit and good luck with the rest your algorithms thanks for watching
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
127 |
all right so this question is a word letter so a transformation sequence from the word beginning to the word ending using a dictionary word list and then this is a three different rule so you can only what you can only change one single letter per time and it has to be within the list of the word right and then the beginning word does not need to be in the word list okay so this is a function and also when you transform right the last rule has to be exactly the same to the n word so what doesn't uh what does it mean so for example one now you have hit and you're a clg probably pronounced cop right i don't know and you're gonna have the list of a word so for the first word you started with hit and then you transform i to o so you got hot it's hot is it inside the list right now heart transform to dot is inside of this right and dots transform to oh right from t to g right and this is it right and you transfer again go to a culture right and then this will be the m right so um so this is pretty much idea so in this question i'm going to give you uh two different um two different solutions for sure a one the first one is going to be one direction solution and the second one is going to be two direction solutions so what does one direction solution mean so you have beginning of word right and you are actually e g item right beginner and you are transforming the word per time all the way to the last rule so which is n right so you go one by one so this is one direction right so what does two direction mean so this is what two direction means so i have a star uh in the beginning which is star and this is going to be end so i'm going to transfer transform the world one by one individually like this will be the uh the set by itself right and then at some point they will definitely meet in the middle so i can definitely know okay this time i can return true so i don't have to trans i don't have to traverse all the fun time i can traverse uh probably a lot right and this is easier to do so um but once again so the first solution is only one direction so uh i do need a different variable so the first one is going to be one so i have a list of words i'm going to convert to the set so when i try to contain which is finding searching uh a word that is possibly in the word list this is going because of one right so if you traverse the list of string and then this costs all the fun but when you traverse the word inside the hash set right it's all the one right and then i do have and i do have one and i don't have a queue for the b for the starting so which is beginner world and i also need another set which is going to be seen so uh this is going to be why you don't want to recursively like uh recursively try to try favors the same word to another right so imagine i'm just imagine so hot right it traverses too lot and then you traverse back to the heart so in this one you are not allowed to do this because every single word you can only use once right and then you want to avoid the circle right i mean cycle sorry cycle and then and i think i did pretty much the explanation but the problem is what for every single word right heart right and this you probably need to try 226 possibilities change the word to another right which is inside the list of the word right so you have 26 possibilities right 26 possibility 26 possible and when you generate to another word right you have to push into the cube right so this is pretty much the solution for one direction and let's stop 40 and then i will be able to just follow them okay so uh just once again so the most easy solution is 1d1 if we're done if word list of contents the n word i'm going to return zero if not so if the list inside the word that's right if the word inside the word list does not have the word for any word right you'll return zero right so this calls all the fun right traverse okay now i need to what i need uh hashtag i'm gonna put a string i'm gonna call it 24 photo asset i'm going to traverse um uh string word so okay so you can do like a string and then do a list and then you will say that this is definitely fine but you can also do like this all right so this is another tricky solution now uh let's start with the starting queue i'm going to go q and this definitely is going to be english so i'm going to add the first word to the beginning to the since this was definitely use it so i'm going to say uh hashtag string set uh scene here new headset i'm going to put a word into the scene right it's inside but now i can actually uh keep traversing but before we traverse we need to know we have to return the hinge and then from here to here right uh you only have one transformation right and then basically that we need to have a counter and then we starting from one and i will tell you why we're starting from one and then we try to traverse the queue right and then at the end i will definitely return what uh return zero so why do i have to return zero over here because if i know that if i know the words inside the queue right and uh when i try to uh try to find out is the word is equal to the m then i'll just return a counter right away if not i'm definitely not going to return right so i'm going to just like this if size is equal to one q size i'm going to say if the word uh is the word no not yet so i'm going to transverse the current label here all right so this is uh this is the main point i need to traverse the current level q so i will try to call for workout 2. so i will say equals to the n word right now so i need to increment my counter over here right okay and this is pretty much it right so now i need to traverse again w to the zero w less than uh length right and then double it so for every single position in the world right i need to know like how many possibilities i can transform into another world right so i still knew what uh i'm gonna say charm right i will traverse the charge to start sorry so basically like i need to convert the uh the current world right the chart array i need to then i want to just change the current position to c right and then this is going to be changed one character only right this is the index and i'm going to just convert back to the screen this can be charged right and i need to check if the word does not use it right if the word does not use it and also is inside my uh total facing some next total and i will be able to work then i'll be able to push into the cube right and i can also what can also add to the set which is for the scene right then you just keep doing this and if you find a word that uh that's already right that's already inside the uh inside like uh the scene then you just return if nothing just keep doing and until you break out the while loop which you push me like the q is empty right so hopefully i don't make mistake okay i do so begin words all right so this question is one direction solution so the time in space is going to be like really complex so least unto the w square so what does it mean n is the number of the word that you need to traverse it's going to be all of them for the worst case every single word into the queue and this is going to be what the length of the word right and then this is going to be all of 26 right and uh this is pretty much it right but you also have a two chart right this is all of w right so all of w squares it came from here right and then this is 26 is constant so we don't worry about it right so how about the space won't be one this is a space so it has all of them and this but we have what we have all the w and so all of n times all the top so this is a space and this is a first uh the first solution it's going to be one way direction solution and the second one is going to be a two direction solution so i just want to remind you that two way direction the starting and ending and you just keep going one by one and then we meet in the middle and then for the timing space in this one is much shorter so they start coding so uh what do i need i still need a bit i actually have this case if the word is not contained the n word that's not inside right i'm going to just what i'm going to just return here all right then i need to and i need a beginning and hashtag and using a helper function i'm going for bfs because it does look like ps3 bfs right fibers uh one by one might enter the solution and then it's going to be one i'm going to put a star i'm going to put it in i'm going to put a total from the trunk and i'll return so i'm just going to create a helper function vfs i'm going to just copy and paste and i will have a step right so i'm going to just keep traversing based on the star so when the end the size of the end is greater than a star i'm going to swap so i'll just keep focu i mean keep focused on the first argument as i passed so if starter size is less than the indus sorry if it is clear in the size right i do the swap right so return vfs and start total set all right so uh now i need to one so just think about it if story is like the first word and it only has the first word as well right so we don't come to here we need to check the attend the possible word you can generate right i'm going to say headset i'm going to go straight i'm going to call a 10 right and you put a new high section and then i need to remove total have to remove so uh i have to remove the beginning set which is a star right because i don't i no longer need a space and in time to just searching or what right but i do need what i do need to traverse the uh the word inside the star so even though you remove from the total but you can still traverse the headset all right um now i need the index right i will either spend extra length and i plus twice so this is every single word position right index right and then i would different definitely the choice array i'm going to say charge usually what is that to charge and then i need my char c to the a like convert to convert the word to a character sorry to the to a to another single layer right so you might be able to know why i do have to generate a source array over here because for every single index you need to uh you need to back you need to generate back to the original one so when you want to put it right over here right when you change the index based on the c right you are not going to well you're not going to change it back unless you put it in but what happened if you just do like this is more easier to read and code right and i will i would definitely say okay try i is in i position right it's going to be c right now i'm going to say uh and then i would say okay if the total does contain if a total does contain a new word right i will have to just add to the attempt but i'm not finished if a total that contains a new word and also endless contains the new world so what is listening i always traverse the starting which is the star a star hash set right and then somehow it's already inside the end headset so which means they are interfaced right they actually meet with a mid meet each other right so again you say return step plus the reason why you need to plus one this is because you haven't reached the word yet you need what you need one more step so when do we need to increment our step it's right over here why because uh for every single word you can like possibly change one character at a time and this is like changing the position right like looking for the index and then uh you're still in the set and once you're finished uh this is going to be like you change one character follower and then if a 10 is empty which means you are not going to just add a word add a new word into it right so you finish the for loop and then you know okay the time is still empty now i know this is going to be what this is going to be returned to you all right you are not allowed to um you're not allowed to find a new string of word for choose headset right one is for studying one story right and everything else for everything else if you can find it and then you want to uh you want to just keep traversing based on the attend asset for the star so i'm going to say bfs attend an end we already increment by one we don't have to implement over here so uh step all right here's something so yeah this is definitely much more easier to read so let's talk about the time this is going to be all the fun elephant right so the worst case will be all of them but not finished yet well this is going to be the word uh starting war so uh the worst case definitely all of when i traverse every single one until the end right but um uh i'm not going to say that this is because if you put a word into the 10 if they were into a 10 and then you would just increment by one right so beginning you have one by a one only beginning you have one which is starting and this is ending and then once you add another one to it right so this one will generate i mean this one will get uh notice oh the starting set is definitely greater than anything now you want to swap so you swap this so ending with the starting point so you are changing what changing hashtags right so uh so this go by one and then you want to go this by one right so uh i would definitely say uh this is gonna be one at least and this uh this is definitely going to be old friend right this is gonna be definitely all of them and this is definitely going to be all over all of the w right w and this is 26. all right so uh yes so it's going to be all of w n times w so uh i'm not sure but this might be my time complexity and full of space is going to be definitely the same thing although sometimes stopping so the reason why is because the headset you can generate words all right so this is my two-way all right so this is my two-way all right so this is my two-way direction time and space complexity you might disagree with me because i'm not 100 sure this is the solution so if you have any question leave a comment below and subscribe if you want it and i'll talk to you later bye
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
1,460 |
Hello Hi Everyone Welcome To My Channel And Solving Digit Code Problem 1460 Make You Are Sick Valve Working Hours Se Problem Tours In This App You Can Select According Subscribe To ZuluTrade Channel Like And Subscribe Example Tours Unlimited Number Of Subscribe 40 Pathari Survey 12345 124 To side me vikram one hai tu 1243 left are the destructive veervikram 1234 subscribe 1234 se zor acid vo unlimited number of verses in aankhon mein doob skin 12512 example 400001 ko subscribe do and from in between more than 120 between 120 154 simplex cricket online through which used Library Functions From The Guardian WhatsApp Crop Acid The Target And Same That AIIMS MBBS Shot Are This Dot Maz And Third Villages The Can Return Gift Race That Dot Triple X Ko Target And Are Swadeshi Latent So Let's Compile Table Tennis Courts And For The Test Cases For The First President Rule 10 Chest Teri Kasam Subscribe 300 270 First And Second Raees Ko 3 711 Swift Return Forms Were Selected For Sacrifice For Seven Years So Let's Beaver Solution Bluetooth Setting Accept Is This Is Very Simple And Straightforward And Time Complexity Of Solution Is That Bihar Like Using Resort Beach Values Internal Vibes Short Term and Values Internal Vibes Short Term and Values Internal Vibes Short Term and Short for the Time Complexity of Sorting This Moment Login Adhere Ko 180 Likes The Ranges of Numbers Values from One to Ranges of Numbers Values from One to Ranges of Numbers Values from One to Three Two Subscribe Now to Receive New Updates Like the Channel Comment Share Subscribe Now In Turn Of That 501 Vikas PM Max Value The Roads Will Go Through The Flying Jatt From India Is Equal To 0.09 Target Plus After Will Is Equal To 0.09 Target Plus After Will Is Equal To 0.09 Target Plus After Will Be Difficult For One Are Subscribe Kare - Be Difficult For One Are Subscribe Kare - Be Difficult For One Are Subscribe Kare - - Subscribe Means The Points 208 - Subscribe Means The Points 208 - Subscribe Means The Points 208 Ki I Lash 1001 Shehnai plus that handsfree can start from one now there is switch from dj number starting from one if dlf particular is not equal to 0 simply return forms the researchers and after this all are equal in will return to sudhir visarjan convention a fetish compiling end Getting Its Correct Answers So Let's Submit Required Solution Which Tips Are Accepted For The Time Complexity Of Dissolution Of Button President Mirwaiz For Subscribe Thank You Like Please Subscribe My Channel For My Upcoming Videos
|
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,952 |
hello guys my name is Ursula and welcome back to my channel and today we will be solving a new record question that is three devices and we will be solving this question with the help of JavaScript so let's read out the question what the question is asking from us given integer uh and return true if n is exactly three positive devices otherwise written false so we have to return true or false if the condition is true we have written true and otherwise false so what actually we have to return to we have to return true if the number n for example a number n is 4 so if it has three divider we have to return to otherwise we have to return false so it should be exactly three not more than three or less than three so we it's written clearly here that exactly three positive dividers so what actually I divide this device is a number which are divisible by the nth number for example if it is 2 and it is if it is divisible by you can see that one and two so we have to return false here because there are two numbers which are divisible by 2 1 and 2. so similarly if you talk about four there are four three numbers which are divisible by four that is one two and four so we have to return true for this condition here so I hope you have got the point here so just before start coding this section please guys do subscribe to the channel hit the like button and press the Bell icon button so that you can get recent updates from the channel so let's start this question and I will be creating a variable here which will look here my I let I is equals to 1 and then I will be creating a let result is equals to an empty array in which I will be uh putting the values and then I will be creating a while loop for a while and it's greater than equal to I then if n is n mod I is equals to 0 then push all the values in the array here so I will be pushing result Dot push and put all n value which are divisible by I so if I talk about here in example number two I will getting what I will be getting in the result I will be getting let me comment out and show you what I will be getting okay just I should run this code here uh result I will be getting one and two okay so if you see that we are getting the length of Lan is equals to okay similarly if we see uh if you talk about four you mean if I talk about example number two which is n is equals to 4 I will be getting 1 2 and 4. so length is equals to three so what I will be doing I will be saying that return uh result dot length is equals to 3. so if I run this code now you can see that Okay so okay so result Dot any n g th what's actually coming up here let's understand written result dot length last few see okay so I haven't increased the value by I plus that's why it's coming up uh because I have to increase the value of i as well so if I run this code now you see that if it is running successfully now okay so just I just forgot to increase the value by I it should be increase actually it is a loop in here so now you see that we are an important has been running successfully so this was all in the question guys hope you have understood the concept I hope you have liked the video if you have liked the video please comment in the comment section that you have liked the video thank you guys for watching the video see you next time
|
Three Divisors
|
minimum-sideway-jumps
|
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Example 2:**
**Input:** n = 4
**Output:** true
**Explantion:** 4 has three divisors: 1, 2, and 4.
**Constraints:**
* `1 <= n <= 104`
|
At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane.
|
Array,Dynamic Programming,Greedy
|
Medium
|
403
|
1,879 |
so lead code minimum sore sum of two arrays in this problem you're given two integer arrays and you need to minimize the source sum of those two arrays and the xor sum is just the sum of the xor of every element at each index so the xor of the first element in both arrays plus the xor of the second element in both arrays and so on right until the end and to solve this problem i've used kind of a backtracking dp solution and i'll show it to you right now so we'll do the naive recursive solution first and then we'll add memoization or caching so that the solution becomes accepted otherwise the time limit gets exceeded okay so first of all what we're going to do is we're going to say we're going to have an array that keeps track of which numbers of the numstro array are still available we can still use to pair up with the nums1 okay so this is going to be our array that keeps track of that so at the beginning we have all of the numbers available we can use any of the numbers true to pair with the numbers one elements and now we're going to call our dp function which is going to give us the answer and our dp state is two variables the first one is the index at which we currently need to pair one of our numbers so that's going to start with 0 obviously because we need to pair all of the nums 1 with one of the numbers from the other array and the second variable is our remaining array and now what we're going to do is we're going to implement our function recursively so at every step we're going to look through all of the remaining numbers and check what the solution would be if we paired up at the current index with that number so let's implement it so it is clearer in code than in words so first thing is the base case if you go out of bounds of the array then you should return zero okay so that's just the base case and now comes the actual recursive part so we're going to keep our best results so far then we're going to do here a lot of recursive calls to our function and then we're going to return our best so far okay so now we need to implement the recursive calls so for every number that is still available that is still remaining so we haven't already used it in the previous indices we can pair it up with the current nums1 of i and then just check what the solution would be if we did that and if it is better than our previous best then we want to update the best so once again we go through all of the nums too if it is not available then we continue because we only want to use the numbers that we the numbers of numbers to that we haven't used already in the previous indices so if it is used just continue otherwise it means that it is available so since it is available we can pair it up with the current index of nums one and so in that case what would the solution with what would the solution be it would just be first of all it would be used so in the recursive call we don't want remain of j to be one because we are using it right so this is kind of where the tracking comes in and then the recursive call is like this so we update our best results so far so if this is less than the current best then best becomes this and this is just the sore between numbs one at i and the current available number right and we know that it is available because of this continue conditional and then the recursive call is here so we just say this is the xor of the numbers that we have paired and then we add the solution starting from the next index with the remaining numbers right and this makes sure that in the next recursive calls we're never going to use j again we're never going to use it again because we've set it to zero we've set it as not available okay and at the end of this recursive call we also want to set it back to available because now we're going to try other numbers so we don't want to keep this unavailable forever and yeah that's kind of it so now all we're going to do like this would already work but it would give time limit exceeded so now we're just going to implement caching and memoization so we're going to have a cache outside of our function and at every step we're going to check if we already have an answer for our input and we need to convert our parameters to a key and i just do that by using a comma okay so i just separate everything with commas and that gives me an unique key for every input to my dp function and now what i do is i check if i already have the answer for this key and if i have it then i just return it because it's not like i have to run the computation again every time like if the key is the same then it's not going to change it's the best is going to be the same as what i've stored here it's not going to change by anything so i can just return it and obviously don't forget to update the cache at key when you actually do the computation the first time and yeah that's it so i'll submit the solution to show that it works and yeah that's it for me today thank you and bye
|
Minimum XOR Sum of Two Arrays
|
maximum-score-from-removing-stones
|
You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4`.
Rearrange the elements of `nums2` such that the resulting **XOR sum** is **minimized**.
Return _the **XOR sum** after the rearrangement_.
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[2,3\]
**Output:** 2
**Explanation:** Rearrange `nums2` so that it becomes `[3,2]`.
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
**Example 2:**
**Input:** nums1 = \[1,0,3\], nums2 = \[5,3,4\]
**Output:** 8
**Explanation:** Rearrange `nums2` so that it becomes `[5,4,3]`.
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `1 <= n <= 14`
* `0 <= nums1[i], nums2[i] <= 107`
|
It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation
|
Math,Greedy,Heap (Priority Queue)
|
Medium
| null |
68 |
all right so let's talk about the texture specification so the discussion is supposed to be really hard to understand and it's supposed to be really article but all right so I'm going to ignore probably going to you know what happened in the uh in the description and just talk about how I did it so you have what you have string array and then for every single word uh you need to count right and then for every single line right for every single line you can combine the string together and if you uh if there's an example I mean if there's a word it says the width then you have to go on the next line right and you start them over again all right so if you only have three words right this is all right and then for every single word you definitely have a space in between you need to maximize your max out with remaining space so what does this mean 16 minus four you need to minus two so what do you get eight right outside is Right 12 right 10 18 square now I need to know like how many space I need to split equally so this one and this one so if this is the even number it's easy it's four and four right but what if I mean I'm going to talk about what if I lose um is I mean just for example so 16 minus 4 minus 2 minus one right and this is 16 and this is supposed to be 9. so how do you split the space equal so here and here so based on the description right you need to have an extra okay so also we have four and four right so we have four employee in the beginning four and four however we need one space right so based on the description you need to put the Air Force Base extra space in the I mean for the first one right so this is how it is right so you put extra space for the first floor and so this is going to be the uh the idea so I'm going to talk about her holiday but this is definitely going to be hard to follow along and so I will try my best so I'm definitely needable I definitely need a story index which is I definitely need an ending index which is J so I'm going to chip track of the number of the length for the entire accounts right so one line has what the metal width right Max hold it so I want to make sure the number of the words the number of characters does not exist the next way and if I find out there is a character I mean if there's a word that is exists in my one line then I need to stop right so I will move my J at some point um before uh 16. and for every single boy you need to pass multiple space right and then later on you need to maximize so once you find out how many words so fireworks right and then this is the first step and then maximize your space right and then number three is move your eye pointer and then once you move your eye pointer your J pointer definitely move so this is the idea the only respect but this is definitely going to be super hard to be honest so I'm gonna code it and then just follow along okay so in I equal to zero and list of things a little string this is going to be my result okay so if this is the condition all right I can still try person so which is there's a word right uh we should there's a line I can still open right so I'm gonna say uh in J equal to what I'm going to create a helper function go right I need to pass in the I need to pass in our words you need a person that will mess up with and I'm probably in Inked right all right and then in uh in this Armament I'm going to change the name to Star and I'll talk about why nicely right so I want to make sure what's my current index starting for the worst showing array and I also need an ending right and I'm going to initialize to equal to a store this is because this word supposed to be what supposed to be included in the first time any I need to try to respect so I need to also have a sum the song was starting at zero but we use the First wall right so I'm going to say now verse and then I'll then try so if I use the first four right and then I need to Traverse first of the word so well and less than one lessons so this is inner condition right and I also have an end statement so once I Traverse the first water I need to Traverse the second one but beforehand I need to increment my end right so uh why not just do it over here right so I already put on this in the sun right now I need to uh I need to make sure if I use this column word and then pause one space and plus the next character yeah the next character the end you in from your end right so n is supposed to be here right now so plus the next character which is what's the end challenge and then if this is what lesson equal to the next width then you can still try version so the sum for plus equal to what one is supposed to be the space plus the worst elephant probably inside so you include the second word now you need to increment your end right but let's talk about this let's just make the code efficient so if you implement your space right over here right and then so when you break all the value when you break out the value it's definitely uh at some point which is what which is uh which is not in within the next week but you definitely will break out the value right so you'll break all the value at this time so you want to subtract check your end player one this is because I only needs three there's three words so you don't want to include uh the example right so this is like go right now I need one I need to know um I need to combine the words in a space right so I'm going to say this I am so just if I will return the string I'm just going to say I which is starting J which is ending towards which is the scenery and X3 which is the line right and then when I add a words when I add a string sorry then I have to know okay I need to move on my eye so the eye is supposed to be here hi supposed to be here Jake's supposed to be here so when I add this line to the new arraylist which is this right I need to update my eye to here right so I equal to 1 J plus one right so now I need to put justify right it's a public strength for sure right I'll put a string just it's Justified game Star in the end single a towards again connect with five all right so um if you are if you're on the last war right it's a starting name are equal right if you start an N or equal then which means there's only one word right so you need to what just return uh return to work but we need to put all the word uh I mean in the beginning of the string right so this is supposed to be uh what happened and let me see what should I do right so yeah she put you put a word in the beginning and I think there's a problem for shooting I mean show me oh okay so it basically let's justify instead of a photo statement so okay so I see so uh I will talk about this later and uh so we need to pack so pattern result foreign okay we need to subscribe uh 16 minus for the last one uh justification I don't know how many but whatever now I need a space problem this is going to be space okay so you want to return uh sorry this is string right so plus a string right so this is going to be returned a new screen and then I can create the chart array and then convert to the string then I add the convert to the space so I'm going to create a child already tell me how many size space size and I will replace so in the beginning when I create the empty string right even though the size is one ten right uh you will definitely have uh best uh zero and then I need to replace first space right so this is how I covered uh the non-tier so this is how I covered uh the non-tier so this is how I covered uh the non-tier space for the new string so basically this is supposed to pattern right so let's back to the justify right so justify I'm going to check if it is this is my key okay so if my m is my n it's a lot more I mean it's the last line or not right time I need to know that's my last name equal to that's my n is equal to what is minus one if this is true language I'm on the last line right so it's going to be left Justified right left Justified so the last line is definitely going to be left Justified so just reoperate and yeah again this is left Justified so there's a reason why you don't want to maximum maximize your space on the last line and uh I also knew I also need to know how many number of space number of recipes minimum so this is space one right space one like how many space like so I'm going to say number of space minimum space so this is total space so Total Space is going to maximize your space so it's going to be max out width minus um course four space I need to pass in the I and J so we just start your name and also what the words right so uh once I find out my total space then I can subtract uh subscribe my space um hold on uh I will talk about this later but let me do the limited workspace right now go space probably okay cool space in high energy string arraylist and the max width so I know my starting point I know my hanging point and then I just what I just don't know if I just wanted to travel for an event for that so pull in W equals to I W less than equal to J we need to include in fact and then the world map is plus equal to what you will say w and that one comments right and then you'll become worth something so this is uh the number of the words you definitely need to have right so I'll come back to here so this is um I definitely need to include examples so this is four plus two this is six five and this is 6 16 minus six is ten right am I right no this is a okay sorry I can do a math so I need to so my total space is eight so I need to maximize my what uh my space in the between equally right and this is it right so now I need to have a string a is equal to the last line I'll check if this is the last time uh hold on okay this is last time then if this is true and don't you just have empty so we'll just end this string if not I need to count the space and then using the uh using a photo space dividing by num space so I will get one eight divided by what two this is two space one two and this is eight that we just uh that we just calculate so this is supposed to be four right so I would say space is four so you have one space one two three four right and then I need to check my remainder if this is what if this is all number then you need to know there's a remainder so okay last line okay for the last time if this is last time you don't have a uh you definitely don't have what if you want to left justify one and then if not then probably it should be the same okay instead it's going to be a mall right so this is a remain so how many remains you have so now I should be talking about I can create a stream Builder it's a new stream Builder and then I can try very slow cover space on the saw including the end the word right so I will say spit out of n towards AI right so I attend also I attend the first word right then I need to obtain the space I need to open the space right and I also need to attend the remainder space right uh remainder space and then I need to what I need to know if I uh sorry so late so let's talk about this so um let me make an easy word so it is a dialect so how many minimum space one two and three right and then if there's a wall behind it's super long man I don't care I don't have to think about this right so minimal space num space is three so how many characters two plus one plus four five six seven nine ten twelve right so 12. so 16 uh hold on right so 12 is Lesson 16 so which is correct right so I need to travel for chocolate words so Total Space uh so the max width is about 16 and the words is two plus two uh sorry uh hold on the workspace is supposed to be what uh supposed to be two plus one plus four right four five nine this is nine sixteen minus nine this is five so this is all number right so all numbered in my space so if I can split equally first then I would be able to know so this is one right and this is like one but I still have two right so this is a remainder compound so remember equal to two space is one right so I will put my extra space first for the first space and then and I will subscribe by one and I have to I have one remaining so I will put that on the second the following space right so um demo uh I mean so this solution should be more clear the two space for the first one two space for the second one space for the last one right and this is it right so I need to add a reminder anyway I remember I need to subtract and then and I need to just check if this is greater than zero right I want to add a space if not I'm going to add nothing so this is pretty much it and I'm gonna string to just spit up SD digestion but think about this you want to pack right so we create a packed Resort right so we can use this pack please show it so if somebody is string and then uh thing about this so if you have well if you have a space at the end you can just train right so this is so you so pad Padres help you to create uh create a string for the list of string so this is so long and I'm not made a mistake yes I do extremely string in the running so it's still tightening around me what do you want and what else let's add oh maybe I change I don't know uh can I find justify all right uh many mistake for here this super speed results all right let's move on the next one all workspace so they're supposed to be ins this is correct okay I only have three arguments right so this one uh I don't need this one and then all right so this is something I made a mistake in the beginning so uh I need to know this is supposed to be chart array and I convert to the string and then I think this is supposed to be it's supposed to be okay if I use this one okay yes so I just put the uh a single quarter double hooked right this is so painful and sorry for the mistake so uh if you still don't understand and maybe you just want to take a break and it let's talk about the time and space so for the timing space is going to be really challenged and everyone has different answers but I'm going to talk about mine so this is definitely going to be what all of w and talk about the time and this is all W and when you go right you want to find out the word so this is still inside all of w but it doesn't matter how many times you want the drivers because at the end you want to justify just by is the problem justify it definitely uh a more time complexity length language so I'm going to ignore the go right I'm going to tell about them just justify right so the justify uh how many characters you need to append I mean yeah how many characters you need to generate it's definitely based on the result right so this is going to be all of what um all of n this is definitely going to be all of M and represent the next width right and then uh this is still inside old fan right out of M because you are probably generate a minimum word I don't know how many more you want to generate but it's definitely start to end right and then you can say Okay um Paul will have a little s and then so a little E minor Star right and then follow length but I would definitely get rid of this because this is too small and it's not important and then uh the next one so this is all of double all of N and how many line you have this is three line right so how many Loop you want to Traverse it's definitely going to be based on I right so uh again this is not countable so I'm going to say all C policy for how many line you want to count I mean you want to add to the list right so the worst case for the time in my solution it's going to be all The W Times all of M times C right and WMS right so that will represent the length of four words and represent the match with zero percent the number of it the number of iterations you want to Traverse based on the value right and then follow the space is from the old uh all of Tableau and this right this is One World 2031 right and then plus the number of the space right plus the number of spaces don't be what all of the uh sorry all of w and then C is the number of a line then you need to work multiply the maximum which is n minus one uh minus the one line word so this is gonna be a space right this is space and this is the number of Regulation and this is a number of a word so the space is this and timing space all right so um if you still don't understand uh probably watch against and still on it and you still have questions leave a comment below and I know there are a lot of mistakes in the beginning but you know it could a confirmed mistake and I'll see you later bye
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
204 |
Hello hello viewers welcome to my video not only cooling school counter and web account number prime numbers and the last one hour negative number and soldiers during their product weak mind ok main buffalo equal to six plus tried to find only numbers are in the future license image Hai That Numbers 1234 Five Subscribe Indian Prime Numbers Will Start From Nothing Bluetooth Device List Number Three To 16 2009 Subscribe And 406 420 272 Plus App 500 Again Will Have To Check 512 Electric Chair Ki Films 205 330 Fakir 1407 This Rule 512 The Time Complexity of Two Numbers of the Number 01 - One Number Two of the Number 01 - One Number Two of the Number 01 - One Number Two of the Number Completely Withdraw Money from This Will Be a Matter of Basically Subscribe to and Particular Person Consider This Example of Switch of Twist Crossing at All the These Multiple Words Super Store 4600 Multiple Software Cross Ok Thank You Want To Three Like Volume 333 Against That Can Be Of The Year Ne 125 Crore 1555 Tani Problem Multiple Most When Quite Multiple Choice 1130 30 And Wanted To Learn Numbers Thoughts Remaining On Yon Prime Numbers Valley-Crossing Multiples Acid Number Numbers Valley-Crossing Multiples Acid Number Numbers Valley-Crossing Multiples Acid Number All The Evening Multiple Sclerosis Will Probe Into Your Profit 68000 Consider This Work Provide Subscribe Number One To Three Four That I Now 5 6 7 8 9 0 Small Example For Others And Subscribe Scars Information On President This Officer Multiple Of To The Means Of Units Cannot Defeam Bapuji Dividing for Completely Agreed Care of the Dog Crossing for Spine Quest for Bliss of Multiplication Valley-Crossing Six Crossing Gate Valley-Crossing Six Crossing Gate Valley-Crossing Six Crossing Gate Approaching Train Crossing Villain Smile Can Were Ruling Class Multiple S Free PUC Six Already Crouch Invite Solid Cross Evolved Three Times 20 Crossed Multiple Ftu Pe 10th Products Side Select Multiple of Three Only You Need to Proceed Towards North Rate and Similarly When You for Watching Multiple 5.the Tennis for Watching Multiple 5.the Tennis for Watching Multiple 5.the Tennis Polygraph Test and Halligan's Wealth for Watching Multiple Software Already Crossed Occident Continue This Rule You Have Also Observed For cold have been quite amazed to 130 sure also like quail crossing not multiple fennel volume to this trophy valley-crossing multiples of to this trophy valley-crossing multiples of to this trophy valley-crossing multiples of three live etc duff 500 you can object from multiple file this notes from point trend gone to fur and three and four you can Just Amused Crossing Multiples From Fine 250 Doctor Multiple Fennel 5 Features In Five Already Been Classified S True Human And Animal Father Multiples End Witch One Number Four Remaining Red Accept One Witch One Number Three Minimum Pour MB Prime Numbers Okay Far Number One B Prime Numbers And Tried to implement for this algorithm a tomorrow morning need to declare on her bed this * seniors time anokhi subscribe its true * seniors time anokhi subscribe its true * seniors time anokhi subscribe its true leaders want him to all should declare oh bullion are let me quality to hum is par majabar is friend and let me quote size to you Intend to a loss to roll numbers which let's check the prime numbers through the snow point is equal to do an electronic any1 plus and will make is prime this time of is equal to a room with multiple users should start from example point is equal to High Security CED Time Will Check This Time After Eye That Is Slipped Not To Come For Prime Numbers Are Already Been Lost When Will Not Over Yet Again For Example When Crossing Multiple Of Three And Observed At 3261 Solid Rose Subah Not To Visit Again Kunth A Video Cross Din Vijendra Simply Continue Other Wise Words And Deeds Which Controls All The Multiple Fennel 382 Start Crossing Over Multiple Free From 323 OK Pick Volume Multiple Then Less York Listen To Three Have Already Been Quite So Point Like Equal To Is Sexual Z Plus Security System Use Incremented Gather SIM to 3G This Cross 323 506 323 Law Plus Three Idiots 324 Swift This Time You Just Adding Limitless Value Research Taken with His Eyes When You Will Cost 125 Win Scissors Added 323 324 Asleep Who Date of Birth Clear and Its Prospects of China Equal to pose 8:00 am and basically Equal to pose 8:00 am and basically Equal to pose 8:00 am and basically wire also doing so for stay angry example to understand why worried doing so let's almost to all rate numbers considered swan property color value wise it to take the example of any way 216 electronic to Find All The Number Switch Of Prime Minister License 1622 In More To So Everyone Welcome To And Give Me To Cash Withdrawal Crotch Now Crotch 4680 And Happy Life More * I Samay Jewel For Ok Is And Happy Life More * I Samay Jewel For Ok Is And Happy Life More * I Samay Jewel For Ok Is To Z S4 And Abroad Is Time For Add To Plus To 600 800 12th Part Plus Two Numbers Which Turns Blue The Number Subscribe To That And I Let Me How To Make Space Point Ok Neer Was Not Know What I Can Do Check This App The Next Khusro Na Instrument Maz Vikram Singh 12345 Essential To No Difficulty 69 etc multiple soft in side 98100 already subscribe 496 not true for the president of the number don't forget to subscribe to my channel in multiple choice for witch at present day been already so this cross sign example sui a can not do these and will Work Point To That Is Logic Behind This And Which Destroys All Since And Manager So Before Doing All Of Account It Means Clearance 0.2 Electronic I Plus That Is Prime If It's True Then They Can Create Account That And They Can Finally Return Gift Is Slide Remaining Sunil runs handed over for dental check up Forward and Updated Otherwise Be Fine Yogesh Yadav in Declared New Indian Oil Vikas confesses Bhavya Storing Bullion Values True and False Swift 9 And Will Values True and False Swift 9 And Will Values True and False Swift 9 And Will Submit It's A So I Think Staking Something Or While Submitting A Plus Points Android This Z10 Members This Increase Thank You So Much For Informational Purposes
|
Count Primes
|
count-primes
|
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106`
|
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
|
Array,Math,Enumeration,Number Theory
|
Medium
|
263,264,279
|
257 |
hey guys welcome to my video of technical view live coding see we are going to be talking about lead code problem 257 binary 3 paths so let's get to it given a binary return all brutally test and then let's take a look at the example first if we are given a tree like this one has two child two children two and three has no sugar and two as only one child which is five and then what are like all the passes from top to bottom we can traverse from route 1 and 2 go to 2 and then 5 right that's gonna be one type of path and there is another one starting from route 1 2 3 so there are two paths and you know what you need to do is return list of string representing this all route to a pass like this so we are gonna solving that problem and before we drop out any codes let's first base briefly talk about the concept of doing tree traversal so 3 travel so in general I would say there are two types of traversing the trips which one of which is breadth-first which one of which is breadth-first which one of which is breadth-first search and the second one is the first search you might be familiar with those from graph but actually the tree is a specific type of graph and then graph traversal technique graph traversal techniques can apply can be applied to treat travel so as well so when you say to their breadth-first search you're to their breadth-first search you're to their breadth-first search you're gonna do you're gonna be using a queue and then you're gonna Traverse tree level by level that first search meaning area use recursion and there are like three types of that first search in the tree which is in order and then pre-order and then is in order and then pre-order and then is in order and then pre-order and then post over so basically in the tree traversal you need to take care of the current node and then you are gonna traverse to the right left subtree and then right subtree and the timing you wanna take care of the current node defines this name of traversal in other means you are gonna take care of the current node in between traversing left and right subtrees so you're going to traverse left subtree first and then you're gonna take care of the current node which I call self and then you're gonna take care of right subtree and then the pre-order you're gonna take then the pre-order you're gonna take then the pre-order you're gonna take care of the party note percentage but I know tremors they both sub trees of course told or you're gonna traverse sub trees first and then you're gonna take care of the part note so yeah that's that and in this particular example I'm gonna be using recursion basically because it is much easier if you use recursion to keep track of the tests we have traveled so far you will get to see that as I quote down but yeah let's get to the coding part that's first search tree trimmers or a type of problem what I usually do is like this I'm gonna handle the base cable the edge case verse where trees know basically I'm going to define some helper variables I'm saying and then I'm gonna call the recursion and then I'm gonna return something and I'm gonna define a helpful her helper method like tremors say and it's gonna have return type of void and then it's gonna give an argument to your root three node root and then he's gonna get some more arguments but we will see that later so let's get to the coding part I'm gonna first handle the edge case where the tree is null so if root is no I'm gonna return empty list but to return an empty list let's first define helper variables actually it doesn't really arm then much so our variable so I'm gonna define a list of string which is which I call red which is the variable I want to return at the very end so new area is stream I didn't have to because of diamonds expression but anyways and then we need to have another helper variable which is to keep track of the past we have traveled so far and the representation of that the prime the problem requires the string like this the using arrow as like delimiter right so we're gonna just have string type of variables which I will say Pat and I have initial value of signal at this point and then we're gonna take care of each case we turn antilles which is good and we have all the helper variables defined on top so we are gonna pass the three wrote three nodes which is given to the this method as is those helper variables like this and then when the recursion is done we are going to just return their variable to return it just sounds a little bit of purpose but it's fine Stan let's get to the triggers the recursive method part which is the main implementation of ours in this video so we're gonna first write down those extra arguments I added it's those training with here and then it's training paths and before we call the recursion I'm gonna set the path variable here to reach that value and actually I need to parse it into string to string will do that for me all right this is what I do let's think about what we would do in the recursion part right first so when you implement anything in recursion recursive call you need to think about base case when you wanna you know end this recursive and this recursion otherwise you are gonna face like Stack Overflow or something like that right so your handle base case first recursion part the you know they're pre-ordered posted or whichever they're pre-ordered posted or whichever they're pre-ordered posted or whichever you choose it didn't it's not gonna make much difference in this particular problem but before I would say let's go with a pre-order traversal here so I'm with a pre-order traversal here so I'm with a pre-order traversal here so I'm gonna take care of the per node and then go to the left subtree and I go to right subtree okay this is our how I am gonna solve this problem so this is first handle base case here base case means if the root node is null then we are going to switch we have nothing to do and then we have to do the recursion so what we need to do is print out the path if the current load is the leaf meaning there is there are no children from that given node so let's call it out a selfie fruit right let it snow also right is now then we are going to read Thurston we are to add something to the variable to return so that means we turn add oh so we need to add the path we have traveled so far as simple as that and then we're not reverse two subtrees only if the left subtree is not no and Traverse two routes that left and then we're gonna pass the extra variable return read and then we have to augment this path right we're gonna augment this path with proper delegator and then the next value which that I have to parse this into the stream will do that for me we'll let that fell so this is done how are we gonna do the right subtree is a very tricky question right but it is not actually you can just copy over this thing and then just do the tedious work like this everything right everything left you just change it to right and that's gonna do it yeah that's cool so I think we're implementation is complete now let's just try to execute it see if I made a type or something now the my solution is accepted it person to be good like I didn't have any for their which I used to make every time but this time I was lucky anyways so let's briefly summarize this video so in this video we took a look at the tree traversal problem which was binary tree path which is to print out all possible root to leaf tasks in the human tree and we talked about two types of traversing tree which for breadth-first search and tree which for breadth-first search and tree which for breadth-first search and breadth-first search and we used breadth-first search and we used breadth-first search and we used recursion in this particular problem because it is easier to keep track of the paths we have traveled so far if we are to use the recursion and the what type of that first search we are to use in this problem like you know the pre-order postal that didn't really pre-order postal that didn't really pre-order postal that didn't really matter but we just use preorder approach which is to traverse the coronoid first and then border left and right subtrees so we took a look at how I define say trainer skeleton cause when I were to you know solve about tree traversal using recursion I defined helper variables like that I had the latch case and I finally called the recursion and I returned variables I returned the variable that I get from the recursion any recursion we had to handle the base case otherwise it's gonna face like stack overflow errors so we handled that and then we did the pre-order recursion like this like pre-order recursion like this like pre-order recursion like this like handling the kernel first and then equal to the left subtree and then called the right subtree that's pretty much it so I hope you guys liked this video and then we'll see you guys in the next video hope you have a great time
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
111 |
So the name of the question is Minimum Laptop Binary Tree. You will get this question in Late code. Question number 11, I will group this question in the description in gender. If you can go and solve it in Late code, then binary. You people will know that any note There can be maximum two children, left side and right child, maximum can be only two, there cannot be more than that. Okay, so do not go for the easy type of this question. I know that many people are going to make mistakes in this question, so see. I would like to tell you people, it is said that if you find the minimum of binary then what is the death? First is any note for example, I am taking this note, this is the target note, okay, any note, what is the distance of the root from it? And distance we come out this is okay number of edge from target note okay tu root so this is the target mode last one so we have two edge this is so if I am asking this target then you will be so death of the root What will happen is that there is no lead from the root to the root, the coverage of the root is zero. So in this question, where is the target note mentioned, then for that we will have to read the problem statement of the lead code. How is the minimum depth defined? Number of notes, first of all. Observation, what did I tell you just now that the number of notes is being said here? Okay, second root, so what is your target note, what is the note from which you have to get the depth, okay, now you know what is the leaf note, if you don't know this then we will tell you. I am the note which does not have both its children. It has the same leaf note. I am the lower leaf note because it does not have both its children. Okay, so what is the nearest lift note? This one is okay, the one that is nearest is our nearest leaf note. I am the arrow. If I make it, then this is our target mode, you have to find the depth from the nearest leaf note to the root. Okay, so I told you the definition, how many are the number of edges, so see friend, I can't see it, so according to me, you are doing nearest. So the number of notes is this root and this is so here the number of notes is tu so this is the tu coming, this is why I was saying that many people make a mistake, here you have to understand by reading the problem statement of the lead code that How is the minimum depth defined? What is the target note of the second? Without any target note, we cannot find the depth because the depth of the root is zero, hence we should know from where we have to find the depth till the root, okay? Now let's move on to the algorithm. Look, you guys might be thinking that the algorithm is very simple. Okay, you might be thinking that what more has to be done in it. Only the number of notes has to be taken out, so you might be thinking in this way, this is the root. If it is then do WAN account, Android is all fine, calculate the note, then add plus here. If you have minimum WAN of laptop, then you might be feeling that the answer will be WAN plus you will come and if whatever I see in the answer, then the answer will be in actual Neeraj. Leaf Note 3 So actually the answer is you, then you must be feeling okay, I am drawing again, the video will be a little bigger, no problem, we have to understand the concept, there is a tree, it is going to be something like this time the tree. This is going to happen, now tell me what is the lowest leaf note, then look here brother, the one in the whole pre, which does not have two children, the rest is the van and you, each of these two notes has one child, right, so the one that is four is not that. So our algorithm is, once we look at the algorithm, what did you say in the algorithm that write WAN on the root, there is a minimum of laptop, but this is a sleep mode for till here, so the total, now see, it should be fine with three notes, so see. What to do when you see here that the left minimum of the left which was not a leaf note but it is confusing it is that take my right sub tree this is the minimum so the van itself is not a leaf note. Yes, but he has only one child, so it is confusing there, so whoever has one child, in this case, go to his maximum child, do not go to his null one, then in this case, it will be OnePlus maximum of left and right, just where. But if there is a single child, then the maximum number of people there is because we know that we should not go towards the tap and there is still your tree left, if you have not reached there yet, then here you have to take the maximum sub for free, then the maximum one is between these two. And here we had two notes, so our decision was going towards zero, but take this education part, okay, do the maximum sub trick, now I am going to tell you its code and after the code, when time and space. If I tell you the complexity, then you will be surprised again, so let's go to the code, so before coming to the solution, I would like to tell you that if you ever buy any course from Gigs for Geek, then you can get 10% discount if then you can get 10% discount if then you can get 10% discount if you You will do this Prakash 10 coupon code and these are pocket friendly courses. The price is not much and you will get 10% price is not much and you will get 10% price is not much and you will get 10% discount on that also. Do this Prakash Tank code. Now let's move on to the solution. So let's look at the first line. Here we said that If the root note is null then return zero. So if your entire tree is null then our debt will be zero. Okay, in that case, we have written this line and when we go to the very last one, when we reach the leaf note, then this Look at the condition, it is saying that left is also null, right is also null, it means you are on leaf note, it means here, count the leaf note, return van and do not call further, do not call anything recursive, so I took direct. Returned the van, okay and the algorithm I told you, Minimum of Left, look at this, Minimum of Left, Minimum of Right, just keep doing 18, but there our code was spread, so look at this is the case where someone of note. There is no left or right sub-tree. Now you of note. There is no left or right sub-tree. Now you of note. There is no left or right sub-tree. Now you will think, friend, if both of these conditions do not happen then look, you have already handled both of these conditions. Look, I am marking it with color that if both of these conditions have been handled, now below this we have It is written that here left is null, ok see this here left is null, if we don't take right then in that condition we have to go to the maximum one, this is what I explained to you, here, take the maximum decision, here if there is a factory. If there is a null, then don't count it as zero, take the maximum decision here, okay, so this is our special case, this is the note which has to be handled which has one child and one null, okay, this is a case, look at the writing pattern of the rest of the courts. I have colored both the tap cases in green. First, I have handled that if both its children are taps, then below that I have written that there is one tap here, so in this case, it is not like this, below we have written that there is one tap here. So in this case it cannot happen that you don't take both because it will be triggered first. Do you understand the above condition? And this court is in Java, it is not like if you do it in C+Plus or is not like if you do it in C+Plus or is not like if you do it in C+Plus or Python, then this If you are not able to understand by looking at the code, then this code is a very readable code and all my codes are readable, even if it is in another language then you will understand. Now let's move towards time and space complexity. Now I know this. Tell me, what is the time complexity going to be? Okay, time complexity will be ours because we will have to visit all the notes, only then we can calculate what is the depth of the year. In case you know that if there are only two notes of the year, then we will have to visit both of them. If you go right then our time complexity will be calculated in the same way but you will say that this is a recursive algorithm and its space complexity will be log n because the height of this tree is log n and our research tag is in it. There will be only one call at one time, there is no stub, nor will you know that the calls coming will be from only one person at one time, then the height of a tree is our space complexity, but if this tree is such that It has three notes, so this call stack will be from all three, okay, so this means that our space will be complex, so I wanted to tell you that in one of my interviews it happened that my interviewer had interrupted me like this and said I thought that if there is such a tree, then whatever recursive call stack you have, all three of our calls are in it, then how are you people saying these, then that day I understood that after seeing such cases also, we should say space. Complexity, this is what I wanted to explain to you and let's end this video, see you in the next lead code video, thank you bye.
|
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
|
41 |
Hello hello brother is welcome to another winner Chinese all search today they want ur problem which cause for missing positive change in one should increase are now supported smallest missing positive integer yourself in the algorithm battery saver to st andrews contacts transport convenience and left side effects of Examples to Understand Your Data and Clear Examples 151 Fennel Example of Harvest 12345 Three Decided Finals of Course Number Dismissing This 16 To Find the Number 8 Mystery Positive Number Set Up Sid Important Flu Positive Number Take Positive Number But Also for Positive Number Subscribe 3 A Unique Many Cricketer Numbers In This Example This Amendment Is Many Sites On WhatsApp Yes Care About Positive Numbers Soft UC - Select - 3 Tets Look They Need To Soft UC - Select - 3 Tets Look They Need To Soft UC - Select - 3 Tets Look They Need To Fight For Positive Numbers In The Positive Mining From One To Three Which Will Have To Do - - 5000 Nothing From This End Do - - 5000 Nothing From This End Do - - 5000 Nothing From This End Spread The Word Weaver Simply 181 More Number 90 to 100 Number Three Do Go to Example Subscribe - We Ladies Only One's Example Subscribe - We Ladies Only One's Example Subscribe - We Ladies Only One's Barrier Okay What to Do Tell Me The Photo File First Number Dismissing Persuasive World Bank and Se One Number Two Does Not Accept With Answer In On Her Body Static Magistrate Studded At Present One Answer Blown Between Sexual In Future Also Left Above Already Present In One Two Three Four Next The Definition Beach Pimple 600 Okay Don't Care Of Large Numbers Vodafone Number Leo In It Somvanshi only in this singh and inspector no death suvansh answer industries to that this is this number back from lyxesy all subscribe now to on your weight sider to times readers can withdraw cases banks and nurses know what is not done for original certificates examples to know how to make Chili Pipers This Approved After Doing And Placid Over 150 Complexity Do You Will Not Be Better But Still Not Able To Withdraw Its First This One To Three For Example 12345 Maximum Number Subscribe Now To The Number 0 Quick Tips Nickel Size Basic Which This Note 126 These smart value shiv witch give one is the this market book activate 201 markets 2030 share markets to avoid office not arise worthy nitrates but porn stars in the road map and definition of and is the first number date for deposit snowden se return for residents of Voice Of Problem With Acids In Goa In Space So It's Not The Correct Answers Related Questions Page Subha Solution Nazar Bhar WhatsApp Video Clips Play List Inko The Real Life Problem When I Want Also Registered Address Of Mother Took No Shahar Up Children Will Just Chill Shahar Se Children children in schools in the and admission in do something na today for the final product subscribe to our channel and subscribe to our channel my channel for my channel Radhe-Radhe video channel subscribe to 100 that was admitted to know what all are children To Suvarchala Comes End Season Mother's Day Gifts Chocolates Cheese Very Happy List Tweet So Nar Chet Ok Same Armaan Aur Se 10 Mar All Sets Ok Pinky Declared Reigning Champion Solar Chain Who Dies From A Prem Raj Cow Conservation City Boat Sweeties Dhawan Poojan Center Check Price Vitamin He 10 Almonds December 21 2012 Check Bachchan Shyam Pinky City Owner Channel Isha Recharges City And Chain State Revenue From 31share Man Yoni Chamber And This Twenty20 David Warner Chain Show Same Note Sweeties Meeting Attend Ok Subah Sardar Simple Approach So And Lax Think Of This Approach will apply 10 approach in problem white certificate of inaugurated with forget the logic but every year to using all studio example you always remember its absence of protest against used to have access to different benefit and all the number from which important respective charriots and andar specific Questions raised and the number plate in it singh isko number at our answer suicide note or 2012 member to learn for example a sample of the respectful not present position do subscribe must subscribe writing number 0123 ok brother requested sanikudu education ko maximum that you platform six number Se Business Tab Responsibilities 126 Ridden in the Opposition 12345 60 The Respective Position and What Are the Questions Definitions of Another One Should Come to Shoot Me Three Four Five Six Life in This Mission Let Se Pricewater Rolex Questions OK Let Se Files Missing Me What Do You How do we call the beach guy * Added to another end Sleep call the beach guy * Added to another end Sleep call the beach guy * Added to another end Sleep with numbers No diary Next question OK 1034 E.B.P.L.Ed. question OK 1034 E.B.P.L.Ed. question OK 1034 E.B.P.L.Ed. course 120 This question is That Point Five-Five Start Airport St. Point Five-Five Start Airport St. Point Five-Five Start Airport St. Peter Foster Mother Name and Share Like End Subha no data is the missing person suicide is uber simple on this knowledge over this example ok should not be the respective latest the principle of first number is tubelight soft you tried in anus and to ok search me chocolate self position because of this example to various correct Position for the correct position of two is the remedy the correct questions midnight 130 decoration for the face introduction of the particular numbers ok what is the trouble to correct position of tourism in this right now it is not setting on question west setting ok it is currently setting on The 40 Don't Want To Set All It's Correct Questions Regarding Checkup Impression Auto Rickshaw To This Camp To Go Install Position Mind Ok But These Areas God Know Big Boss 3 City One Question Vs Three Exchange With Me Sundar Two Can Go Is Correct Questions Three Rooms morning 12th destroy his to elements which you want to come on its correct questions vestige against to is present and tools and meeting quarter servants vishwamitri liye will come into that is rich's author ok in the recent this point to its point questions ok Latest Subscribe and Share and Sunao Main Amazon Toot Are Nau Again But the Number One Position 0803 This Mixture Job and Setting on Water Pollution Free Leg Tours and Correct Questions 12345 60 Kari Channel Ka Ghar Na Aaye Shyam Ko on the Correct Chehon lakshmi hai to verification ko here but already moot setting f-18 setting bank suhaag 131 likes changes setting f-18 setting bank suhaag 131 likes changes setting f-18 setting bank suhaag 131 likes changes position with students will do we need change the position electronic position from three will come here and one will dare should meet the number three will go here one will Come here a hands free will go a government committed to create not that apne pot hai vianti share paani sirf ok very good sunavai fikar ko switch off the question 9080 do chilli idli question what about admission 120 which character city wall decoration for decoration book 300 which Correctly saturday this against none of the above these people's electronics question next what do we shape wear 323 lender it pot decoration of the year - 30 323 lender it pot decoration of the year - 30 323 lender it pot decoration of the year - 30 - - width ok but number one question - - width ok but number one question - - width ok but number one question positive parents want to give it's ok deep study don't know you Do Not Disturb We Raw Family It's OK Next Will Go To The Next Question Circulation For What Is Seth Doobie Drop Test Also Don't Care Voted For Juegos What We Can Be Just Want To Find Number Serving Come 126 Side Effects And Ecuador 62000 First Number Meeting Will Always Find the first number meeting with this range Dhanvantari Samay Jal Battery Saver Answer from there higher number chuke supports all the number six presented and service center one is valve two number from meeting support service michigan answer is three ok subah don't care of higher number 90 negative Numbers Don't Care Last number ok buy let me just have a positive attitude loot currently they are this particular number 19 particular number this point edification wear singh bittu setting butware chuttu question ok but already been over 231 question read already beau to sitting position at it's ok I switch on to check Effigy of missing and notice to the number David Warner and they want to make a toy as changed to see this massive not but doesn't mean singh read all its present convention including ok surya singh ok stories for death it's ok Related To Care For Requested Lord With Amazing Number Sugriv Ise To All Of You All Setting On And Charity Shop Listen What We Have Finally Bihar This Early Morning Okay Listen Other After Dropping After Doing Everything December 2016 Newly Married Answer 132 213 Neck That They Response And this machine is cost effective vitamin A vitamin setting on key chain point question birthday is note setting show on Thursday select tracking code for this post so you what we have to it both side red over all the limits of death certificate no effect remember this short Story Example You Always Visible To Render Former Poking Soft Exercise Anti Growth One Point Particular Breast Size Installed Science Quizzes Site Which They Can They Will Just Check Which Number It's First Meeting From 1212 250 Vintage December OK Mystery Element Beckoning Sea Is Name Suicide What Is The Population Meas Miding Admit Like Given Reason Foreign Setting On Isko Mein 250th 12358 258 320 Chest Goddess Setting Sharp Intelligence Setting Hand Bag Particular Check - Madhu Kishwar Chat Start The Particular Check - Madhu Kishwar Chat Start The Particular Check - Madhu Kishwar Chat Start The Correct Element They Are Not In Bigg Boss 6 - Correct Element They Are Not In Bigg Boss 6 - Correct Element They Are Not In Bigg Boss 6 - One OK Pimple Points 151 Partnership That New Year Wear Look For Chilli One It's OK Tree One And They Will Drop Medicine At Operation Beach Want To So How Will Be And South Operation 100 E Will Give The Is Condition You Check This Particular Question Of The Year Award Elements Not The Benefit of Which Element 100 Number 66 Is Remedy 9th Current Element subscribe and subscribe the Video then subscribe to the Page if you liked The Video then Hai To Initially When They Have Tried To Hai PR Member In This Particular Example Read Me To Check If The Element OK Master Setting Khol Se Beyhadh Check Investment Setting Voice and Correct Chapter Notes Chapter Number 10 Chapter 1 - - Today Also Noted Do Chapter 1 - - Today Also Noted Do Chapter 1 - - Today Also Noted Do Question and Difficult to Liquidate Question Next Time Any Me Will Increment and Will Keep on Moving Formal Office Morning 689 After All Reception What Will Happen When You Were Provided To Worry Or Elements And Clean Note Side Plus Back Thank You How To Check Its Elements After Related Question And Not Working After Everything That They Are Taking Suo Vinod 80 Settings Open In This Way This Features Check If I Equal to numbers of OK I is oil plus one OK Vikas 2012 after 10 minutes turn on setting base become settings open air pollution1 a tourist in its footprint better specific artist Delhi doping effective not be developed and maintained a school in so it is accurate Amazing spider- man suicide and accurate Amazing spider- man suicide and accurate Amazing spider- man suicide and finally which supports all the hard rock band slide click previous song again cases like that comments discuss surendra sheoran surprised to agree this present in the case of total six secretary ramswaroop 206 suicide case you have to retail and laxman print switzerland mineral and The stickers will be working side only. Direct No. Related See What is the Android App Main Aapke Show Very Good Sudhir and Two Candidates Who Destroy Chehre Ko Delhi - - - - - - Sid Problems in Delhi - - - - - - Sid Problems in Delhi - - - - - - Sid Problems in Condition Will Be This Element Subscribe and They Want to See the Element In one hand and leg check republic day the sun that should know indicated smile let me to whole school some time ago difficult time garlic ginger flying like loot morning chilli powder again and planets crops torch started quarter inch it to ok sudarshan for WATCHING OUR LET ME GIVE THE CONDITION RECEIVER SLIDE GIVE THIS PARTICULAR WALLY BLUE FUEL SAMEER WORKING ON LAKSHMAN PATTERN THANK YOU TO BE PATIENT AND FUEL
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
86 |
uh it's literally 12 a.m in the midnight a.m in the midnight a.m in the midnight so welcome to my channel and i'm here to do my hundred legal challenge and today we have lego 86 partition list as a medium question so might take a while to understand it so given ahead of the linked list and array x partition is such that all node less than x come before nodes greater than or equal to x so you should preserve the original relative order of the nodes in each of the two partition so in this example you can see this picture we have x right here we put everything smaller than x in the beginning you will see one two and two with the same order one two in the first partition and anything else put it on the right side with the same order four three five in the second partition so yeah that's it um how to think about this question in the easy way so we can have two um two list node and we can create two lists no zero and first zero um pointer is the beginning of this partition second one is a second beginning of the second partition then we can look through the origin array if this pointer is smaller than x then we put this in the first partition and then partition we move one step and this original hat will move one step until it's reached the second one and compared to the x again if it's bigger or equal put it to the second list that we prepared for it and after all this and we connect the first partition and second partition and that's it now take a look at the code now we have list node first one is equal to a new this no we have a zero then we have a moving point of first is f equal to first then we have the second partition second so now we have this two um let's know for us to store the information what we need to do is look through everything in that um while hat is not equal to no so that we have something to put in this first and second partition if x that we should put it in the first um partition which uh first dot next is equal to hat then as equal to f dot next so we'll move the pointer of the first partition else and as dot next equal to hat so put it in the second partition same thing and after i put it so we already put the value to the partition then we have to move the hat pointer has equal to head.next has equal to head.next has equal to head.next after next point let's see what is missing it should be good for this while loop after that we will connect first point and second pointer which is f stop next the second point that will end up with no and first pointer dot next is equal to um second dot next which is the beginning note of that after that they all connected after connecting just return first point that we have dot next because the default is start with zero so we take out the zero and it should be good uh let's know okay looks good and it passed all the cases and hopefully this is straightforward enough um so if you have any question please comment below and i will see you in the next video bye
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
785 |
hello so today we are doing this problem called is graph bipartite from the lead code it's a medium problem and so let's get to it so the problem since we have an undirected graph and we want to return true if it if and only if it's be part bipartite and basically a graph is bipartite if we can split the set of nodes into two sets two independent sets let's call one a and the other one B such that every edge in the graph has so basically we can kind of construct let's say something like x1 or let's call it a one node and then a two node and then a three node and this set is like the first set and so something like this and so this set and then on the other side you can have another set and let's say b2 and b3 and this is set B and the only connection that exists out between these two sets so something like this these two are connected and then these two are connected and if we find a graph and this can be like more than just three but the idea is that there is one set there is there are only two sets and the connections that exist are only between elements from two different sets and so every edge in the graph has one node in a and another node in bit that's the that's about so this problem here we get the input is a graph I which is a list of indices basically that represents the connection so this says that one is connected to so yeah so basically says that zero is connected to two well I guess the input is a little bit weird but basically is the position actually so here the elements at positions yeah but this input I think needs a lot more explanation so let me just take it like this and explain it so this is position zero this is position 1 and this position to land this position 3 and basically the way this input works is that this means that zero is connected to 1 and 3 1 is connected to 0 and 2 is connected to 1 and 3 is connected to 0 and 2 so basically the index represents the node and the value represents the neighbors are the values that is going to so for example here we have this because you can see that zero is connected to 1 and 0 is connected to 3 because of this and the 1 is connected to 0 and it's connected to 2 because of this and yet you get the idea and this one it can be bipartite because if we look we can put a 0 here and 0 is connected to 1 and we can put let's say 2 and 2 is connected to or 3 and now 0 is not connected to 2 1 is not connected to 3 and basically 0s character 2 3 though right so yeah actually this is not the way I should do it so 0 1 let's say and then here I'm just going to organize them in a way similar to this so that we can see both sets and here 3 so we know that 0 is connected to there is an edge between 0 & 1 which is this one and there is an 0 & 1 which is this one and there is an 0 & 1 which is this one and there is an edge between 0 & 3 and there is an edge between so actually damages and there is an edge between zero and is there an edge between zero and two now is there an edge between one and three no and so yeah this these are and so this is the our set a and this is our set B and there is no connection between the elements of this set themselves there is only connection between the elements of the of one set to the other right and so black outside asks us to check if we can decompose the graph into two sets such that one has edges only two in the other sets and that's the way it goes and so how can we do this so we can color do just color the graph using basically DFS or DFS and but use only two colors and the way we are going to do the coloring is that color and node with let's say we cut out a node with blue then its neighbors gets colored with a different color let's say for example red for example here right so that way all if we do this that means that if every color and the nodes connected to it should have a different color that means once we did and finish it BFS or whatever trouble so we are doing then the colors then the result of traversal and coloring is that no tuna no edge has two nodes of the same color because if the if an edge has nodes of the same color that means they are in the same set which means that something like this they are connected which means we broke the rule of no elements from the same sets are colored and so that's what who are going to do is you are going to pick a color and then pick two colors and then color this color a color edges nodes of each edge with different colors and every time if we encounter a neighbor of a node that has the same color as the one we are trying to color the neighbor the node with then it's not bipartite and if we go through the entire thing and we are able to color with this constraint then that means the graph is bipartite right and so in order to do this we need just to have a color map that kind of found that saves which node I was like that saves that color that was assigned to the node and yeah that's pretty much all there is to it so let's just create our color map and then we know that the nodes it says that the nodes are from zero to grab to the length of the graph minus one and so that's what we are going to do so we have node n range of length of the graph this would go from 0 to n minus 1 with Python and so we are doing this because the graph it says here that so the graph may be disconnected it doesn't say that the graph is not is all connected so we might have a note that we don't visit when we start from like let's say this mode there may be other nodes in another component in the graph and so we do this loop so that we can go through these also and so we start our DFS I'll say here set our DFS from that and let's do our DFS I shall just do our DFS in vine here so this is our GFS and DFS let's do it iteratively so that would mean would have a stack and the stack will contain a note first and we all go through the stack while it's not empty and then we would color give the know that color so what I will be doing is that let's say blue I will represent that by the value zero and then I read I represent that by the bottom one and this way if I wanna check if I'm at a node with that with a colored with blue with a blue then that means that adjacent notes should be colored with red which is equal to 1 minus boat since the flow is zero to get one I just do 1 minus 0 and the reverse with if the node was red then if I do 1 minus 1 which is 1 minus red I get 1 minus 1 which is 0 which is the color blue and so this allows me to easily switch between the colors and so first I'm going to call it this boat and so that would be 0 right and then I'm going to go through the stack and then I will pop the note from the stack I'll say and follow node now B start pop and I'm going to go through the neighbor or let's call them edges neighbor actually and just graph so we know that the graphs are in texted with their value so if I do graph 0 I will get the adjacent nodes to that node and so I can just do graph mode and what I will do next is our check if the neighbor is not in color that means we haven't colored it yet so that's fine that means we can color it and so to color the quality is going to say that color of neighbor is going to be different so every node we color adjacent node with a different color so that would mean 1 minus the color of the node and then we will need to add it to the M we'll need to add to the stack right so that would mean stat offend neighbor so that its own neighbors also get explored now otherwise if we have a node where it's adjacent node is already colored we need to check if it has the same color because if it has the same color that means we violated the bipartite condition if it has a different color then that's fine we don't care right so we can just check if color of neighbor is equal to the color of node you can return false and that's pretty much it so actually we can just say here we're just this like this and otherwise we can just return so basically we don't we if we didn't find any notes that violate the peroxide condition that means we are good and we can return sure and yeah so that's pretty much it we are we have the map we have our color we start a DFS here and so one other thing what we can do is we shouldn't need to explore a node that was already colored here so we need to check so this also acts the color map you can notice here at as visited set that allows us to not to visit no it's multiple times because whenever is it something we color it and so we can just here check if the node only if the node is not in color than we then we can try to process it with DFS and that would mean this and that's pretty much it so check if not in our College this is usually equivalent to not in visited that we usually do for DFS so we start out DFS process here so DFS classes is now here which consists of creating a stack with the start node coloring that node which is also equivalent to adding it to visit it and then going through the stack taking the node out exploring the neighbors if a neighbor is not scholarly at we can just color it there is no condition that no condition of heartedness is violated yet added to the stack but if it's already in the color map that means it was already colored by something else so check that we don't have the same color because if you have the same color that means it's in the same set and they that means there is an edge between two nodes in the same set and so we return false otherwise we just regenerate so let's try this there is no is it's just not in color say now okay so that pass is there let's submit and see okay so that solution classes now there is nothing that so here I'm done with iterative DFS is just a good idea to always try to do it with them with a different with the recursive DFS to get used to it and so to do it in with iteratively of us I can just say instead of doing this I won't just do this check right away here so no more iterative DFS but the rest of the tablet is the same and so here if the node was in color I'm going to check and so I'm going to check this if the color of the node actually let me do that later and so we check if it's not in color than will color it right and we set its color to 0 and then we explore to the DFS so explore the node with DFS and we if the result from that Davis says that it's not bipartite then we return false otherwise we so we explored all nodes and they're all said that it's bipartite and so written show so let's find out DFS no so yes so this DFS is to check but if graph is five graphs from that node is bipartite right or let's say or color it correctly because that's essentially what was checking and so how do we do that so we need to go through the neighbors of that node same way we did with DFS with the iterative DFS and then we are going to check if that neighbor is if not in color then we can just call it there is no problem and so we can just follow it by doing father named the bearer is equal to the opposite of the current notes color which is just my as paranoid and then we need to do DFS of the neighbor otherwise we need to check it Fitz has the color that it has is equal to the color of the current node then that means we have a problem you can return false that means that two adjacent nodes can are in the same set right and so otherwise if we didn't find anything like that we can return true and so this is the same way except instead of doing it using a stack and appending to it we are just using a recursive call to a DFS function okay so it passes they're awesome it okay so we have a wrong answer and mirror let's see what did we you know a little bit further this case or see what we did wrong so we are coloring the neighbor with one - color of you the neighbor with one - color of you the neighbor with one - color of you know - that's correct know - that's correct know - that's correct but yep so one thing is the problem is here so we should check if the DFS of the neighbor also returned it false and return false and that we are not doing that which is bad here because whenever we encounter something that tells us like the rest of my neighbors are not like don't verify that are not colored correctly then that means that the graph is not bipartite and we need to return false and yeah let's take this case and run it on okay so that works on that this case seamless passes okay it does pass cool now we did it with DFS if erratically and reclusive must try to do it with DFS actually because still it's the same traversal the only thing that we are interested in is coloring and if the color of adjacent nodes out the same thing will return false so nothing prevents us from doing that with BFS it's essentially also BFS checks at the neighbors of each node so we can do it with BFS so let's do that okay this is a little bit too small okay cool so let's do a BFS here let me just we don't need this anymore so with BFS we can we need the usual template the same template that we did for DFS so that we can go through all the nodes if we have a graph that contains multiple components that are not connected and so we need to go through the nodes in the graph and so that means node in range of length of the graph that's still the same and we need to have our color map right and we need to check now we need to check if not if node not in color so that we don't press tolerate if it was already colored in that case we need to start our BFS which means was to a queue which is right now no specific collections of detail and the start point of that would be node and then while at you we need to color the nodes so that would mean color of node will be equal to 0 and then we would pop the node by doing Q dot pop and then we will need to go through the neighbor of the neighbors of that node the same way you did with DFS and then we need to check if it's valid or not so if neighbor is not in color it's not corrected yet so there is no problem so we can just say the color of the neighbor is that they're opposite if the neighbor was for the node is called a bro we need to call the neighbor with red with a different color so we do that with this and we need to add the neighbor to the queue so its own neighbors get also processor otherwise if the neighbor was already colored then we need to check if it's colored with the same color as the node because in that case that means they are in the same set and they are connected and so we need to check if never is equal to color off note then we need to return false because this means we can't color properly to achieve a bipartite graph and otherwise if we went through all of this and didn't find any problem it can be done sure and yep that should be enough first one this cool call us minute okay so that also passes time so we can see it can't be salted with BFS DFS and the insight I think from this problem is using auxiliary data structure with the traversal so that it can help you make some decisions and annotate nodes with some data so that you can use a letter so the same mechanism can be done by storing patterns can be done by storing more than just the colors so that you can do some processing here or you can check some property on the graph and yeah so it's not when we are doing it the traversal with BFS or DFS we are not limited to just the template that we usually use we can use more other data structures to achieve whatever checks who are doing and yes that's it for this problem see you next time bye
|
Is Graph Bipartite?
|
basic-calculator-iii
|
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties:
* There are no self-edges (`graph[u]` does not contain `u`).
* There are no parallel edges (`graph[u]` does not contain duplicate values).
* If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected).
* The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them.
A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`.
Return `true` _if and only if it is **bipartite**_.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\]
**Output:** false
**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
**Example 2:**
**Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\]
**Output:** true
**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}.
**Constraints:**
* `graph.length == n`
* `1 <= n <= 100`
* `0 <= graph[u].length < n`
* `0 <= graph[u][i] <= n - 1`
* `graph[u]` does not contain `u`.
* All the values of `graph[u]` are **unique**.
* If `graph[u]` contains `v`, then `graph[v]` contains `u`.
| null |
Math,String,Stack,Recursion
|
Hard
|
224,227,781,1736
|
349 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem intersection of two arrays we're given two integer arrays nums one and nums 2 and we want to find the intersection of them they don't really Define what exactly that is in this problem but basically it's elements that are common to both of the input lists now it's possible in this case for example we have duplicates like we have two twos here and two twos here but for the intersection for the output we do not consider duplicates so the result must be unique so this is a relatively straightforward problem the hint is that since we don't want duplicates the easiest thing we could do is put everything in the first set or the first list into a hash set and do the same thing with elements in the second list put them into a separate hash set and then at the end we can check elements that are common to both of the hash sets and then include them in the output so while that's definitely possible we can actually also solve this problem with just a single hash set let me show you how we're going to do that so suppose these are our two input arrays let's say we have a hash map and we're going to map every single element to a Boolean so when we go through the first array we have four we're going to map four to a Boolean we're going to do false so I'm just going to put the letter F here and actually I think I just realized we don't even need a hash map we can probably just use a hash set so I'm going to do that to make this even more simple so now we don't have to worry about mapping these to anything but we'll have four we'll have nine and then we'll have so we'll add every element in the first array to a hash set next we want to go through the elements in the second array now we want to find common elements any element in this array that also shows up in the hash set for example first element is nine this does show up in the hash set that means it's common to both arrays that means we should add it to the output next we get to four same thing it's common to both arrays let's add that to the output now we get nine so this is the part where we might end up with duplicates so we want to handle this pretty carefully we don't want the same element to show up in the output twice but how can we detect that how can we know that we've already seen this before well the first time we saw nine we should remove it from the hash set same thing with four when we see four we see it's already in the hash set that's great we add it to the output and at that point we should remove it from the hash set when we get to the second nine we won't have any Nines in here so we'll skip this one then we'll get to eight doesn't show up here at all and then we'll get to four it has been removed so the output in this case is just going to be 94 and that is the correct output for this example problem so this is probably the most straightforward and efficient way to solve this problem it's going to be linear time and linear space for the hashset I guess it's worth mentioning that there probably is a sorting approach solution for this in that case we would not need extra memory while depending on the Sorting implementation but that would be one way to optimize the space but it's going to cost us when it comes to time it's going to be n log n in terms of time okay now let's code this up so the first thing I'm going to do is just get that hash set that I talked about we could manually instantiate it and then create it ourselves it's pretty easy to do that for n in nums and then we could say scene. addn so that would be going through nums one but it's even easier if you're allowed to do this in an interview which usually you will be allowed to because this is pretty simple we can just pass nums one into that and then get a hash set from those elements and next we can build our output result which is what we're ultimately going to return so I like to write that out at the beginning and then to actually build it let's go through every number in the second array n in nums 2 and if n is in the hash set then it's common to both arrays and therefore we should add it to the output just like this but let's not forget we should also remove it from the hash set because we don't want to end up adding it multiple times so here let's say scene. remove n and let's go ahead and run this code because this is actually it and as you can see on the left it's pretty efficient if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
44 |
this is the 44 flicker Challenge and it is called wild card matching given an input string s and a pattern P Implement wildcard pattern matching with support for question mark and asterisks where question mark matches a single character and asterisk matches any sequence of characters including the empty sequence the matching should cover the entire input string not partial so if you have a and pattern of P of a it's false because this matches the first a but not the second one if you have an asterisks we'll match that no matter what now if you have question mark a the question mark will match the C but the a doesn't match to B all right let's get started so if I remember correctly we already did a challenge similar to this but it was for regex instead of uh character matching Wild Card matching so I know for that we had uh we use like index locations for where we were in string s and then when we were in uh string P so if I remember we would go along each index in the pattern and then check to see if that corresponds to the string so we'll start off with int s location equals zero although we'll start off with if P equals Asterix then return to true just so we can get that one out the way okay so what we'll do here is a while s location is less than or equal to s dot length and then what we'll then do is if P location is equal P dot length so if at the very end of the string or another pattern will then return s location equals s dot length so basically We're looping while in inside of here and if we're at the very end of the pattern as in we can't match anything else in the string we then return whether we're also at the very end of string s so we should get the character from this pattern now so car P car equals P peel location yep and then we'll have a few conditions if P car equals Asterix else if pikar equals question mark and then else and in here on the else one that makes it a bit easy if s location does not equal return false otherwise it'll be just this location plus and P location plus picar is question mark it'll just be this again I suppose but then it's when it's asterisks where it's a bit trickier because you have to look ahead to see what the next character is so if say if P location plus one equals P dot length and this will be just return true otherwise P next equals the allocation plus one although with this we need to consider if it's a question mark with a need to look ahead again of that and we'll need to do that repeatedly until we find the next actual character so what we should do let's do int offset equals one and we'll do while I think this will be P location it's less than P dot length and RP location plus offset is SNP dot length and actually we'll put this above here and pnext actually we'll just keep it as that so we need to keep running this if it's a question mark or if it's an asterisk then it doesn't matter but let's do put this into here if pnext equals Asterix offset plus then continue actually looking at this we should get S cars well so put that down here hmm okay thinking more about this solution not sure if any of this needs to be done okay so we're gonna change a bunch of this around I'm going to start off with if it equals question mark or escar equals picar then we're just gonna do this but we also will do is we'll keep track of the current location of the asterisks so in uh what do you peace star and we'll start that's negative one just so we know hasn't been found yet and see so P star equals P location this will be p plus okay we also need to so it's going to be a little bit of trial and error with the matching with the Asterix so we also need to keep track of um current s index as that is the last time that a match occurred so we can return back to that point so matching three asterisks then we're going to be trying a bit of trial and error for the whole thing so let's call this last match this will also be negative one let's see we have this that's all good and you go down to here last match equals slocation so if he so this is if it's question mark or they both match if it's picar if it's neither of these then the current match isn't working so else if P star doesn't if the star doesn't exist and we're not currently matching uh equals negative one then this is a return false Okay so then we need to do an else which is returning okay how am I trying to do this so the best way to use an Asterix is use it as little as possible when uh pattern matching so because we need the whole pattern to match the string we need to make sure we have all the other characters matched first before using this so we save a location of the Asterix keep record of the current match and then we increase the point or location of the P location of the pattern by one then we go up to here it's now the next location where we're checking with the current location of the string so if that fails we then want the asterisk to match that okay I've got it so if the current letter doesn't match we then just let the asterisk handle it so this will be P location because um P star plus no not plus one so we're going to be returning like we went forward but then we're returning back because it didn't work so we're going to this location but then because the we know using the start as uh matching the current position in the string we're just going to increase it from the loss match location like that but then now we also need to record last match it calls its location okay what I really should do is remove this location from that okay so we're running in here until reaches the end although it looks like it's possible that it doesn't reach the end so we will keep this but if we do reach the end we need to check to see if there's anything else remaining in the pattern what is this asterisks then we can continue okay we'll do while uh P location is less than P dot length and P location equals Asterix we then P location plus then we return P location s p dot length okay so I think okay let's just read through this so if p is just an asterisk then it's true so we're saving the current location in S and P saving the location of the previous star and we are saving the last match of the star so we're entering through this location is less than estimate length if P location equals P dot links one here we then return whether it's location equals s length which is probably false hmm but what if it's asterisks [ __ ] I don't know if that is needed [ __ ] I don't know if that is needed [ __ ] I don't know if that is needed what we should be doing is no we will keep that you know what I just want to run it let's just see what it does if it works I thought I'd have an easy time on this as we've already done the regex one but apparently maybe not okay well those did return true I want to break point through it just so I can fully understand what's going on so we've got the characters of that those characters in match so we increment one okay yep so that did work so it got to the end and it returned false let me go to the next one oh that was an asterisk so it just returned true how about we change that one so it is Asterix a so go to the next one here so now I won't just return true yep so a and star so go to here P star equals location last match is like this location and P location plus so we'll not at that very end yet now on to the second a and this is peacock a oh no that is the first day okay this is okay yeah that doesn't work hmm okay I might need to include length checks in here so P location is less than P dot length and uh either of these but then we need a do this instead and not be the same thing here because with the first iteration we're on the second run this character but we're still checking the first one so it's only going to plus each of them so get to the end and it's really not on the pattern anymore it'll go to this these if statements it will skip this star does exist so it will go to here and it will return we'll go back to the start add one to it for the P location so carrying on from there but it'll plus or increment the S location so it'll be the second date being used I think that's how it will work so go to this one which is start a okay we've got the star so go here P location is not less than P length or it is oh yeah that's fine yeah it does this one first but then now it's not ah I've got to remove this so retry that actually was wrong spot to pull breakpoint okay now we go through so we've got the star patterns a with first a grid here it's no longer lesson so go to there and over here sets the P locations from one from the Star and increments location from the last match you do that then it will get to here and I'll do this but now s location is no longer less than S length this is not less than P length and I'll return true let's just continue awesome so hopefully that's all that needs to be done we'll copy that put that into leak code and run on the test ones just make sure also try let's try Asterix a run that then let's also try a asterisks well we can do a few more test cases as well for this actually that about covers it okay let's submit ah cool so that solution worked took me longer than I thought it would as I thought this was going to be very like basically the same as the regex one but with the regex one you could just go through the whole pattern and as long as the Pen Match something then it'd work but with this one you actually had to match the whole string which made it more difficult to do but anyway that's the 44th leeco challenge called wild card matching if you like this video make sure to like And subscribe
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.