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 |
---|---|---|---|---|---|---|---|---|
80 |
hello everyone welcome to my channel let's solve the problem remove duplicates from sorted array 2. so given a sorted array nums remove the duplicates in place such that duplicates appeared at most twice and returned the new length do not allocate extra space for another array you must do this by modifying the input array in place with one extra memory so we have to solve this problem in place now for this example if you can see we have three one consecutively so what we will do we will take can take at most two so two is in our output array so we have to update this array and then we have two so we will take two and one three so final this will be the output in our original array and then the length of our output array will become 5. so we have to written 5. so how we will solve this problem so let's see if we have two element initially in our array then we do not have to do anything we will just return as it is if there are two elements so these two element can be a same or different so 0 or any number like 0 or 1. so if it is then it is satisfying the constraint of our problem we will just written and the length of after that what we will do we start two pointers one is both of them from the index this which is at index 2 s and let's say slow pointer s and fast pointer f so this fast pointer we will loop through until reach to the length of our array which is still the less than n now at every point at fast pointer what we will do we are building the array and we will keep the result array till the s will be representing the last element of our array so what we will do we will compare what is the element and the current if nums of f the fast pointer is not equals to if it is not equals to nums at as the slow pointer is pointing the our created array minus 2 if it is not equals to this then what we will do we will update our nums of slow pointer by one and assign this new element at that point f plus if it is equal then we just keep update f so that's the only two condition this is one condition and two condition if it is equal we will update by this if it is not so in the end we will get the s will represent our out index where the our output array till the all the elements without the duplication after removing all the multiple duplicates so let's see how we will solve run this up so s is here and f is also over here so initially we will compare what is the is this equals to this is not equal so what we will keep we will update both the pointer now is pointing here and f is also pointing here again we will compare this is not equal then both will update s will be here and f will be here again now we compare this with this is equal so we just increase f and y s will be here then we will again compare this with this is equal so we will update f only not as now this is not equal to this we copy this 2 to this place and replace this 1 by 2 so this will become 2 now same we will keep repeating it and we will get answer like three so let us implement the code so for the code what we need to do let us first find the length of our array num length now if n is less than three then we just return this itself and otherwise what we will do we will use the two pointers slow start from two and fast start from two now we will run this loop while the fast is less than the number of element in our array now we will check if nums at first element is not equals to num set slow element minus 2 in that case we just update sy1 and assign the value of whatever value at f and in all case we need to update our fast pointer and in the end the s will represent the length of our output array so we will return s so let us compile the code and see the code is getting compiled and we are getting correct answer so let us submit the code so it is accepted so the time complexity of the solution as you can see we are running the fast pointer till the length of the array so bit is o of n is the time complex solution and the space complexity we are just using the ah constant and it is constant so another approach we can also you solve this using the for loop so we just take the output like merge this with this so for in fast is equals to from the start from the s and then fast less than the n and fast plus and here we will assign again nums if the nums of fast not equals to nums of slow minus two then we will update this nums of slope plus y nums of r that's it and in the end again we return same slow pointer so the cup why we are comparing with the s minus 2 because we can keep two element as max same so that is the reason so if you like this solution hit the like button and subscribe to my channel thanks for watching and this is accepted
|
Remove Duplicates from Sorted Array II
|
remove-duplicates-from-sorted-array-ii
|
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`.
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\]
**Output:** 5, nums = \[1,1,2,2,3,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,1,2,3,3\]
**Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\]
**Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
| null |
Array,Two Pointers
|
Medium
|
26
|
868 |
all right let's talk about the binary gap so you are given positive integer and you have to finally return the longest distance between any two adjacent one in a binary representation of n so if there are no two edges on one return you right so this question is just a little bit challenge so let me just quickly draw a diagram so this is pretty much the idea so you have to convert into binary bits so this in this case gonna be one zero and for every single time you're going to end by one to check if the current bit is actually um one or zero if this is equal to one i know this b is actually one right so i can making sure um to compare the distance between the first and second one bit right so in this case it's going to be what it's going to be zero right so to do so i know it's zero right i need to skip right so how do i skip i'm gonna shift the entire bit right by one and this will become one zero one right and i'm still going to end my bit by one and if this is one right i'm going to check uh for my last position i have a lost position right so if my last position is actually not initialized so i will set my last position inside by negative 1 first so if my last position is actually equal to negative 1 so this is actually meant this is my first one in my uh in my integer right so i will just making sure i put a record on it in this case i'm going to put a zero one so this is uh the index one right in this case so last position go to one and i will move on right so i'm i'll shift the entire string right back one so in this case uh it's gonna be what one zero one right and i'm gonna end one again so i will get one right so in this case i know my last position is already not equal to one so it's i can actually compare this index which is two the term position should be two the two minus last position should be one so i get one and uh so my resource my return result should be one in this case but i still have remaining bits to go on so i just keep going so this is actually zero so i'm not doing anything and i'm going to just keep shifting i'll shift my entire end to earn right by one so i will get one and i know my last position was actually able to two right so in this case it was the last fraction equal to two in this case and my current position is what uh zero one two three four so four minus two equal to two so i uh at the end i'll just return two so i have to return the longest distance so this is a little bit uh not easy to do let me just stop holding so okay i'm not gonna do this so here is the solution so i'm going to say in 0 equal to 0 right and last person is equal to negative 1 by d4 current position is equal to 0 so while and it's not equal to view right and then i later on will return result by just making sure i don't forget so if and one it's actually equal to one right i will do something and if for every single time i will shoot right by one right so this is pretty much it right so for every current position i will just keep increment so this is actually the fundamental stuff so i don't forget and now i just have to deal with the if statement right if and anyone is actually going to run right i need to make sure if last plus uh it's not equal to negative one so which mean i can actually set the max maximum of max uh distance for my reveal right so uh that will be here right so if not then i would just keep updating my last post to my current post right and this is pretty much it right so uh set my max distance so i will say resolution maps that max result and it's going to be current post minus last close right so this is the solution and let me submit all right here we go so let's talk about time in space uh this is going to be space all of uh one constant and for a time uh the time should be the big land of n so it's going to be out of n but it depends on the bit so in this case although five right i mean although five right the bit length is five you traverse what uh probably iteration iterated five times in the uh in right so my quick note for the solution is actually time is all the fun that is the big length of button so space is constant and this is the solution and our 7 is timed by
|
Binary Gap
|
push-dominoes
|
Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.
**Example 1:**
**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is "10110 ".
The first adjacent pair of 1's is "10110 " with a distance of 2.
The second adjacent pair of 1's is "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.
**Example 2:**
**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
**Example 3:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is "101 ".
**Constraints:**
* `1 <= n <= 109`
| null |
Two Pointers,String,Dynamic Programming
|
Medium
| null |
57 |
hey what's up YouTube you know what they say Elite code a day keeps the unemployment away so let's get to it for this problem we're given a list of intervals and we're told to insert a new interval and perform any operations necessary such that the new interval fits within the current intervals without overlapping let's start with the conceptual explanation I've put together a visual that might help us conceptualize the problem on the top I've written the same example list of intervals that we were given in the problem the intervals are spaced apart to represent the scale of each interval within the entire list for better visual reference our goal is to insert a given interval in this case 2 5 in a position where the starting points of the new and existing interval are in order this implies that we need to iterate through the current list of intervals until we find a suitable existing interval for which this is true below we have four possible cases which we can evaluate case one is two five generally speaking it's the case where the lower bound of the new interval can fall within the current interval and the upper bound of the new interval lies outside of the current interval so we begin iterating through the list of intervals and find an interval where the starting point of the new interval is larger than the starting point of the current interval in this case it's at I equals 0 or 1 3. this means that we need to insert 2 5 ahead of one three so if one three is at some ith index then we need to insert two five at the I plus 1 index case two is one two generally speaking it's the case where both bounds of the new interval will fit within the current interval we can apply the same operation as we did in case one to insert the new interval after the current interval case three is zero five generally speaking it's the case where both bound to the new interval fit outside of the current interval or between intervals since for this case the starting point of the new interval is less than the starting point of the current interval we need to insert the new interval at this current index in order to bump the current interval ahead of the new interval hence the insertion at index i instead of I Plus 1. case four our last case is 4 5. it's the case where both bounds of the new interval lie completely above the current integral but if you think about it this case is actually the same as case three if we make a current interval 6 9. so we are making the same insert call at I but in this case I is 1 instead of zero so with all our cases written down we now see that the insert calls for cases one and two and three and four are the same respectively for cases one and two we have the following logic just didn't work so for cases one and two we have the following logic foreign and then for cases three and four we have the following logic we can actually simplify this even more and remove this part because of course the starting point of the new array new interval is less than the ending point of the current interval the next step is to resolve any overlaps that the new inserted interval may have caused I'm going to take the inserted list for case 1 as an example remember that for case one we inserted the new interval 2 5 at the I plus 1 index so this means that the current index is still I which to be exact is still on zero let's just shift our Focus towards intervals one three and two five because that's where the conflict is first we can see that three goes into two five all right so 3 kind of goes into it so what we can do here is update three to the upper bound of the interval that it crosses into so precisely we can update three to five since that is that's five so what we get is one five two five so at this point we do not increment the index I so I is still here so if we modify the current interval we do not increment the index and that makes our current interval 1 5. so next we can resolve the conflict that the current interval has with the next interval in this case we can see that we don't need the next interval at all so one five two five both of these are fives so we don't even need this so we can pop the I plus one interval of the list so this really means that we have uh we have two cases right so if the current interval or so this case if uh is if the current interval is completely above the next interval or the ending number of the current interval is a completely above the next interval so what do we do here we pop this one and then do not increment I else if our current interval uh if the upper bound of the current interval is greater than or equal to next or the lower bound of the next interval then replace the upper bound of the current interval with the upper bound to the next interval do not increment I right and then outside of all this otherwise increment and so that is basically the second part to resolve conflicts now that we understand the concept let's start writing the code I can first check if the intervals is already empty and if it is I just add the new interval and return the intervals so at this point I'm just going to make two variables called new start a new end representing the lower and upper bounds of the new interval right next we can check if the upper bound of the new interval is well uh the upper bound of the next we can check if the lower bound of the new interval is greater than the upper bound of the last interval in the list of intervals and if it is this means that all we need to do is append the new interval and the return the list of intervals so we get the last one get the upper bound and then if new a new start is greater than that append new interval and then return intervals right so now we can start doing what we've been discussing so I'm going to create a pointer just I and initialize that to zero and I'll make sure step one find where to insert new interval based on starting point so while I is less than intervals I'll just say the current interval is it revolves I and then press start occur and you'll interval zero one per start is less than you start and you start end intervals and we just insert the new interval to the I plus one thing X and then break since we found our proper location so else if new start less than current start controls dot insert I new interval we just insert it to the ith position therefore pushing the current interval right to the one uh one to the right and then break and then for the while loop we just have a i plus one and that's it now for step two oops we resolve overlaps that adding the new interval may have const so I actually don't need to initialize I to zero okay because I is already at the position where we've inserted the new interval either at I or I plus 1. so even if we have a while loop uh we are all we are still making a single pass through the list of intervals all right since we need the next interval here I'm gonna just do while I is less than length of intervals minus one per interval right intervals I and then next interval five plus one now if current interval I is greater than or equal to the next interval zero I is next interval one right so this is the case where the current interval is completely above completely Shadows the next interval so what this means well if our current interval completes Shadows the next interval we don't even need the next interval we just pop it out and then make sure that I does not uh that the pointer eye does not get incremented so we can decrement it and then for the while loop we increment it right and else for interval next interval zero and this is the case at the current interval intersects into the next interval I right just like we've said before we've just set the upper bound of the current interval to the upper bound of the next interval and then we just decrement ions to make sure that the pointer does not get a net increase of one for this iteration minus one plus one Net Zero and then all we need to do here is return intervals so let's run it so we're missing something now foreign intervals dot pop Okay so case one and case two are accepted let's submit okay and it is accepted and so this is the current the complete solution so for the time and space complexity the time complexity is O of n because we are going through all intervals in the list of intervals and then I'm going to Define n as the number of intervals we have and remember what I said earlier about there being two while Loops but we're not actually resetting I to zero for the second while loop so this is still a single pass which means this is of n time complexity for space complexity our storing really is the new interval so it's o1 so that was it for leak code number 57 I hope you enjoyed the video I'll see you in the next one
|
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,004 |
hello Engineers welcome back in the previous video we solved a lead code question with a sliding window technique where the window size was fixed in this video we're going to solve another lead code question where the window size is not fixed okay I hope you're ready let's get started so this is the question that we're going to solve today this is called Max consecutive ones and uh let's try to understand the question let's see how we can derive a solution and let's see what is the time and space complexity okay let's get started so this is the question given a binary array nums and an integer K written the maximum number of consecutive ones in the array if you can flip at most K zeros okay at most K zeros so let's try to understand this with an example let's take this to our whiteboard and then we'll take it from there so let's increase the font a little bit okay so this is what they're saying if this is our array 1 0 we can flip at most K zeros flip Max a zeros so this is what it means in this case the K is two so you can flip a maximum of two k what is the meaning of Flip means you can change 0 to 1 okay so if K is zero we can flip a maximum of twos let's say we can choose to flip these two zeros or we can flip this zero and this zero okay and when we do this we will check what is the longest subarray with ones so if we have flipped the last two zeros this zero and this zero we get one and one here and when we see this array this sub array this has a length of six okay and this is the maximum so we can verify this if we would have turned these first two zeros as uh once so this is how the array would look like 0 1 0 and our interest is in the maximum consecutive ones so this is one subarray with consecutive ones and the length is five and this is consecutive ones the length is four so in this case the max one is four if we have flipped the first two zeros now let's consider a case where we have flipped the second two zeros these two let's see how that array looks like 1 0 right so what are the consecutive ones this is one subarray the length is three this is another subar the length is six okay now let's see the third case where we are flipping this zero and this Z so how will that array look like 1 0 1 and then 1 so there are two subarrays again here the first subarray is length three the second subarray is length six so among all this since we have maximum length five here maximum length six here we have found our maximum length and we will return this value okay so we need to find the algorithm which can flip uh two arrays two zeros at a time and then check if the uh consecutive one subarray length is greater than the current Max or something like that and then we will return whatever is the max in the entire array okay so since we are looking at the question with consecutive ones since we our question says consecutive ones we know that we are dealing with subar and when we are dealing with sub arays it is best to use the two pointers and use the sliding window technique okay so let's see how we can approach this so first let's see what trackers we need first is since we are trying to do this with the sliding window Let's see we will need a start of the window let's call it start for easier understanding and we will need an end pointer end of the window this is the end of the window what do we need to keep track of length of the window for checking if we have found a new length which is greater so we need to keep track of current length which is zero and we also need to check if this is the maximum value so we need to keep track of a maximum length so we will need a max length Okay so these are our trackers so let's put them aside so that we can do a dry run start and current length and max length and currently they are all zeros okay now how do we uh build the window so we have the start pointer end pointer we will simply use the end pointer to Traverse all the way to the right and that will be the uh part where we are expanding the window so that is simple we have seen this in our Theory lecture so this is the logic right while n is less than uh nums do length nums here is the array name or the vector name sorry this is not length this is ns. size okay as long as this is in play we can do n++ and we are traversing through can do n++ and we are traversing through can do n++ and we are traversing through the array okay so this is our expanding logic what will be our shrinking logic so let's understand the intuition behind this what do we need the question says flip a maximum of K zeros so when we are traversing through the array let's take this array to this side 1 0 and we have a start pointer here and endp pointer here and when we are traversing through this array we will encounter a zero and as we move along we will encounter multiple zeros right we are allowed to change maximum of K zeros right so K is 2 here so in this Vector I can flip a maximum of two zeros so as soon as I hit the third zero when I'm at when I'm my end pointer is here I found my first zero when I'm here I found my second zero and I'm allowed to play with this window this is okay I will flip this 0 to 1 I will flip this 0 one and this is a valid subar but as soon as I found the third zero we have reached a case where this condition is no longer valid this is the condition where we will start to shrink the window we will move the start po of forward because we have reached a point where the condition is no longer valid so our start pointer will keep moving forward until we are back to this condition okay so we will need a track to see how many zeros have we reached so far so let's create that so let's call it zero count so as long as zero count is less than or equal to K we are okay but when it crosses K we start shrinking the window okay so zero count is here so let's track zero count as well now let's write the shrinking logic so what is the shrinking logic first we need to know when to increment it so when will we increment this zero count whenever we find a zero in the vector so if nums of n equal to 0 then we simply say 0 count Plus+ okay so this is how we check this Plus+ okay so this is how we check this Plus+ okay so this is how we check this is how increment now how do we check if 0 count is greater than K okay if Z count is greater than K we need to do something what do we need to start shrinking the window so how do we do that so we can use a while loop while Z count is greater than K so we need to keep moving the start po of forward we need to keep moving the start point forward until this condition is no longer valid right that's what we spoke about just now so we will do start Plus+ about just now so we will do start Plus+ about just now so we will do start Plus+ until zero count is back to our normal uh accepted range so how will we do this we will keep moving the start point forward and whenever we find a zero now we are moving the start pointer forward here whenever start pointer is seeing a zero which means we have found a zero and we can reduce the zero count because we will move it away from our window we will reduce the zero count so if nums of start equal to Z if we have found a zero then we simply do 0 count - count - count - we will reduce the zero count okay so we are reducing the zero count so we have built a logic where we have expanded the window and now we have found the logic where we will string the window so this is our condition now the last remaining piece is to check the window length and see uh if we can find a max length right so let's do that so in this case right since we already have a while which is which takes a conditional statement we don't need if again okay while itself will not get executed if the condition is not met so we don't need if again so we can just remove this now we will build something for our length so how do we do that we will simply calculate the length at each stage so what is the current length equal to how do we length current length equal to how do we get the current length of any window so if my start pointer is here and end pointer is here so what is the difference between these two so if my start pointer is here 0 1 2 3 4 and end pointer is at five and pointer is at five what is the length of this 1 2 3 4 5 6 so length should be six so how do we get this we simply do end minus start 5 - 0 and we do + one and we get - 0 and we do + one and we get - 0 and we do + one and we get six okay so that is how we check the window logic so we do end minus start because this is a zero index Vector we will do plus one okay that's our number and we simply need to add the last piece which is check if there is a new if check if there is a new maximum so how do we do that after we do all these calculations we do a check if max length is less than current length so which means that we have found the new window which is more than the current Max so we will simply update it max length equal to current L okay and that's it we will just simply return the max length so you should notice how we have built the algorithm step by step so we did not start by saying we will do all this together we started by thinking that it is a sliding window question and then we started to build how to expand the window first and then we saw how to shrink the window and then we built upon uh what to do with zero count what to do with current length max length so this is an step by step process don't try to find the entire solution in one go so this is called the first principles thinking so where you break down the problem into smaller sets and you start with the smallest sub problem and then you build on top of it so that's what we did here okay let's do a fresh dry run so that it is more clear on how this is working so let's see let's put our trackers here we have start we have end we have zero count we have current length and then we have max length right now initially they are all at zero no problem so let's get our example Vector once again so that we can track it so we are here 11 1 0 okay and these are the indexes 0 1 2 3 4 5 6 7 8 9 and 10 okay and both our start and end pointer are here fine so let's move along so what we do initially we expand the window so we move the end pointer forward so before we move we are at here the start and end pointer are here let's see uh if we are still in play so this is the Y Loop that gets started so we are still in play and we are checking current length there is one thing we need to do this current length check we need to move it down here because in between we are changing the window size right this Loop will change the window size so we will need to recalculate the length after shrinking basically so then we will check if it's valid against the max length Okay so that is one change we will do and let's see so we are here end pointer is at zero and when end pointer is at zero first line is if nums out n equal to Z we are checking if there is any zero here there is no zero so nothing else to do inside the loop we will simply do n++ will simply do n++ will simply do n++ okay so this is zero uh 0o count is zero but we can update the current length right 0 con to zero but we can update the current length is now one and Ma X length is this is greater than zero so we will update it to one now our end pointer can move forward this is the dry run now end pointer is here now again we are checking if there is any zero there is no zero but our window has expanded so our max length also expanded end pointer will keep moving forward zero count is now still zero our end pointer is here still zero end pointer is here and our current length has increased max length also increased now when we are at three now our endp pointer is here and here we have a zero so our zero count will increase and current length will also increase max length will also increase next our zero pointer our start pointer is here end pointer will move forward to 2 4 now we have found our second zero 0 count is 2 and current length will become five and max length also becomes five end pointer is still moving forward now our zero count is three when we have reached the zero count of three when our end pointer is here we have reached three now this violates our condition that uh maximum zeros allowed to flip are k now the K is two here so we are allowed to flip a maximum of only two so when we have reached the third zero we need to start string the window okay so we will do that so we will move our start pointer forward endp pointer will remain in its place and while the start pointer is moving forward if there is any zero we will uh reduce the zero count that's what we wrote here this inner loop is now working we are here Zer count is greater than k okay because now 0 count is three and if we find a zero we will reduce the zero count and keep moving the start poter forward okay we'll shrink the window so at this point when the start pointer is at one no start pointer is here so there is no zero so zero count Remains the Same and start pointer will keep moving forward until we reach a zero so we are here we move to two and then we move to three we are here and start pointer has found a zero so when we find a zero we will reduce the zero count so now zero count will become two and start pointer will keep moving forward and end pointer is now at five and here we are back to a condition where our zero count is reduced to two now our start pointer is here so we are back in the condition where we are seeing only two zeros which is in the allowed range and we are coming out of this while loop right so we are out of this Val Loop now we will continue the outer loop so max length now we can check the max length so what is the current window length is 0 current window length is 5 - 4 1 + 1 2 so there are is 5 - 4 1 + 1 2 so there are is 5 - 4 1 + 1 2 so there are only two elements in our window so our start pointer is here end pointer is here so this is our new window and the length is two okay since this is not greater than the current max length this max length will remain the same now our end pointer can move forward so start pointer will remain here end pointer will keep moving forward until it finds a third zero thir pointer is here end pointer is moving forward it will keep moving forward until it finds the third zero and where is the third zero it is at index step we can see here now end pointer is moving forward there are no zeros along the way and when we are at index 10 we found our new zero now again our zero count will become three this is against the violation of our window uh condition so again we will start shrinking the window we will move our start point of forward and as we move our CH point forward we encountered a zero here so what we do we reduce the zero length our end pointer is at 10 now we are back in our range so we have eliminated this zero our start pointer has moved forward and we have eliminated this zero and currently our window is this one this is our start pointer this is our end pointer we are here okay and now we are out of the inner value because we have we are back in our allowed range so again we will check the current length so what is the current length 10 - 5 is so what is the current length 10 - 5 is so what is the current length 10 - 5 is 5 + 1 is 6 now we have six 6 is 5 + 1 is 6 now we have six 6 is 5 + 1 is 6 now we have six 6 is greater than five so we will update our max length to six so at this point we have reached the final uh index and our outer while loop is also completed and we will return the max length Okay so this is our dry run our code is working fine according to this Theory let's code it in vs code sorry on lead code so let's go to lead code we are here now let's start implementing let's get all our trackers in place we need a start we need a end we need a zero counter we need a current window length and we need a max length so these are my trackers let's write the logic to expand our window while end is less than nums do size we will keep moving the end pointer so this is our expand logic so how do we do the shrinking we will do while Z count greater than K we will do start ++ this is K we will do start ++ this is K we will do start ++ this is our shrinking logic and if we encounter any zeros in this shrinking we will reduce the zero code but first how did we increment the zero count we will increment the zero count when the end pointer C is a zero so this will take care of increment this inner value will take care of decrement and the last piece current length equal to end minus start + one this is the to end minus start + one this is the to end minus start + one this is the window size and we will check if current length is greater than max length then we will update the max length and that's it so writing the code is very simple after we know the usion behind our algorithm we will simply return max length let's quickly verify if we have done everything right we have our start trackers our Loop will continue all the way till end pointer reaches the end of the vector and if we are seeing a zero we will increment it if the zero count is crossing the allowed limit we will decrement it and shrink the window and we will check if this window size is greater than max length we will update it and we will return okay I think that is good let's run it and see we forgot to semicolon typing mistake sorry about that okay our test cases are accepted we can submit it so this is done so we have solved our question so what will be the time complexity of this uh function so if we can see we are iterating over the array only once so this end pointer is going forward all the way till the end and we are never returning to the first place so this inner loop is there but it is always moving forward it is never going back again to restart the Loop or restart the entire traversal of the vector so that way there are only maximum of n operations in this so our time complexity is n okay so in this question if you have any questions or if you are doubtful in the approach or if there is any doubt in the sliding window technique you can definitely ask me and uh that's it for this video guys thank you so much for watching please leave a like if you have uh found this solution helpful and uh please don't forget to subscribe to the channel if you haven't done already if you have already done thank you for your support and I will see you in the next one thank you so much cheers
|
Max Consecutive Ones III
|
least-operators-to-express-number
|
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length`
| null |
Math,Dynamic Programming
|
Hard
| null |
92 |
hey everyone how's it going welcome back to another video today we'll be looking at this problem that is called reversing a sublist in a linked list and this is a pretty important problem so let's get right into it so this problem tells you that you're given a linked list and you need to reverse a portion of that linked list you need to reverse a sub list in that given linked list so for instance we've been given a list here which is this original list it starts off at 1 and each of these elements are labeled with some number so each of these elements has a value to them for example the first element has the value 1 then we have 2 3 4 5 and then in the end we have 6 and after 6 we have a null pointer which denotes the ending of the linked list right so what we are told here is that we're given a start and an end position and we need to reverse all the nodes that up that are present between the start and the end positions in that given linked list right so for instance I've highlighted the nodes here which occur between the start and the end positions so for instance in this linked list in the first given linked list we have 3 4 & 5 that occur in the in have 3 4 & 5 that occur in the in have 3 4 & 5 that occur in the in between the start and the end pointers and what we're supposed to do is we're supposed to reverse that nodes that are present between these two positions so what we end up with is this reversed sub list where these highlighted nodes are present in the reversed order so 3 4 5 ends up as 5 4 3 so how will we do this is like a three pointer approach you need to keep track of three pointers and then you need to iterate through this entire sub list so how do we do that let's get right into it alright so how does this approach work all you really need to understand here is that the logic in itself is pretty simple it's just the implementation part that's a little bit tricky so the logic is very simple all you need to do is simply start off at the second element of the linked list and just pick that up extract that out and place it in the front then go to the next element and do the same thing with that extract that element and place at the front of that car in sublist I have written all these three nodes of the sub list separately from the rest of the linked list so that I can demonstrate that a little better so we see that we have the elements 3 4 & 5 in see that we have the elements 3 4 & 5 in see that we have the elements 3 4 & 5 in the sub list we need to reverse this we start off at the second element what we do is we take this element we cut it out of the sub list and we paste it in the front so let's say I pick this element out and I place it in the front and what these sub lists becomes is something like this it becomes 4 3 & 5 now once like this it becomes 4 3 & 5 now once like this it becomes 4 3 & 5 now once I've removed that fourth element I move on to the next element in line which is element number 5 what I do is I pick this element up again in the same manner that I picked up for I cut it out I simply cut this element out and I place it in the front of the list and I get something like this so this is what the reversed sub list looks like and that's all we really need to do in this entire program and you can actually extend this to any number of elements and that's a pretty trivial task all you need to do is start off at the element after the first element of the sub list and just keep picking each of these elements up one by one extract them and add it to the front oh that's all you really need to do but it's a little bit tricky to implement this using linked lists so let's understand how we'll do that so what we see here is that we always need a way to access the front of the reversed sub list because we'll be reversing the sub list we always need access to the front of the list because that is where we will be adding new elements so for instance will always need access to this pointer which will point to the front of the sub list at that particular moment when we are extracting an element and adding it to the front so we need a pointer to always point to the front of the list so let's call that node before reversed sub list right secondly we always need to have access to a working point of the working pointer is basically which will help us to iterate through the though it is the actual pointer that we'll be iterating through the list so we'll be starting off at the first element D working pointer we'll start off at the first element of your sub list so it will be present somewhere here right so it starts off at the first element next we need access to the element that we need to extract from the list the part of the list that we need to cut from the current sub list and paste in the front so we need access to the current element to be extracted so we'll name that node to be extracted so the node to be extracted in this case will be this node number four right this one this node is the one that we'll start off with extracting in the first part of our algorithm and we'll paste it in the front so we need access to this is essentially the next pointer of the working pointer is the next it's the next node of the working pointer so we lacs s this using working pointer dot next or the arrow next depending on which language you're using right so we need access to this element as well and we'll call this node to be extracted right and now we'll start off with the actual algorithm all we just have to do is first off get the node to be extracted how will we get that we will simply write node to be extracted equal to working pointer next because the next pointer of the working pointer will always be pointing to the node to be extracted after that we need to cut it out of the sub list right we need to remove it from the sub list so how we will do that is simply make this working pointer we need to make this working pointer skip this element and draw the point to the next element in line so that it essentially gets cut off from this sub list so what we'll do is we'll make the next pointer of the working pointer point to the next element of the node to be extracted so we'll essentially make it skip this node and point to the node after the node to be a tracted so it will become something like this right now what we need to do is that we need to make we need to perform this in code so what we'll do is we write something like this we will write working pointer next and that will point to the next element of node to be extracted now we need to cut this node out properly we need to unlink it from pointing to the next element too rather pointing to the front of the sub list right because you need to place this in the front so what we'll do is we'll make the next point of this node to be extracted point to the first element of the sub list so how do we point that point to that we already kept track of this node before the sub list so wherever the node before the sub list points the next element is always the front of the sub list so what we need to do is we need to make the node to be extracted point to the next element of node before the sub list because it points to before the sub list so we need to make the next pointer of node to be extracted point to the next pointer of note before sub list which will essentially be the first element in the current list so what will write this as is you like this something like this right so this one just means that the next pointer of the node to be extracted this pointer essentially will now point to the first element of the sub list which will look something like this so we will extract that pointer out and we'll make it point to this first element and we'll essentially just remove the older pointer because we would have replaced it with the new connection which will be this blue arrow that you see on the screen right so if I write this in a more simpler manner what I'll do is I'll just place the fourth node before the third one I'll do that in the bit because before we do that we need to update the next pointer of the node before sub list as well so that it can put a point to the new starting of the current working sub list will do that is that we need to make this point at the next pointer point to four right so that we can actually finish off this extraction and pasting procedure so what that would look like in code is something like this so it will say something like node before sub list next equal to node to be extracted and that will make this pointer point to this fourth element and it will look something like this I'll redraw this and make it look a little bit neater so this in the next illustration that you see this pointer this next point of the node before sub list will be pointing to the node to be extracted and will look something like this so this is what the sub list will look like after all these instructions have been executed and what the result would be that a node to be extracted is now at the front of the sub list and the node before the sub list points to this new front right now you finished one iteration of this entire of these four instructions right and now we need to continue on with this until start is smaller than n now if you run another iteration the first instruction says that the node to be extracted equal to the next pointer of the working pointer so now this node to be extracted will be updated to point to the fifth element which will look something like this after that we see that the next pointer of the working pointer will be made to point to the node to be extracted next which will essentially be the sixth element right it will be outside the current sub list which will kind of denote that will be finishing off with this procedure soon so what will happen is this pointer will now point to six and the older pointer will be replaced with the new connection right similarly the next sintra instruction says that the node to be extracted next equal to note before sub list next which essentially means that will connect the next pointer of the node to be extracted with the front of the sub list which will be element number four or the element with value for right here and how do we access it with the next pointer of node before the sub list right so what this will kind of mean is that this pointer will now point to the first element of the sub list essentially replacing the older connection making it look something like this right so if we move on to the next instruction it says note before sub list next equal to node to be extracted which essentially means that we need to update the next pointer of the node before sub list and make it point to the new first element of the list which will be the node to be extracted and that will complete the extraction and the pasting procedure right so what this will do is this will essentially replace this pointer and make it point to the node to be extracted so this looks kind of messy so I'll just redraw this to make it look a little better so this is what it actually looks like when we just redraw this entire circuit right so this is what it will look like and we see that we reach the end of the sub list and this is when we will stop right so this is basically how this algorithm will work and we'll just continue this on until we've iterated through the entire sub list right so let's see how we'll write this up in code all right so here we are in lead code and let's begin coding the solution out the first thing that I'll do is rename these parameters from these horrible names which are which is M and n which is not all clear so I'll name them start and end so that it's a little bit clearer what we're trying to do the person that I'll do is simply check if we have any null conditions that is if the head is null or if the start of the end pointers are actually equal in which case we don't have to do anything and simply return back the actual head itself so if the head is null or if the start is equal to the end in both these conditions we just have to return back the head pointer now we need to define a dummy head so that we always know where the actual head of the list is so that when we've done all the cout and cutting and pasting we don't actually lose track of the actual head of the list then you need to return it back at the end of the algorithm so just to keep track of the head I'll just defined list node called dummy Eilish like that with a random value at say zero and the next part of the dummy will point to the actual head of the list like so now we need to define the node before sub list pointer that will point to the node before the actual subject that you need to reverse so I will just name that as list node star because it's a pointer node before sub list equal to dummy because it will start off at the dummy pointer itself and this is a pointer so we'll have to start off with the actual address of the dummy pointer so we used the ampersand sign now we need to move it until it reaches the node before the sub list so for that I'll define another variable which will define its position so I'll call that pause and initialize that one now while pause is smaller than start why this is true I'll keep incrementing the node before sub list to the next node in line so I'll just write so node before sub list equal to note before sub list next which will simply just move it to the next pointer right and after that I'll just increment pause and this will just go on until it hits the start element and then we vote incremented any further because we want to stop just before the actual sub list that we need to reverse starts now we need to define the working pointer which will simply be the next point of this node before sub list because that will essentially be the starting of the list so we'll just write Auto working PTR equal to note before sub list next right so now it points to the next element of the node before sub list which is essentially the start of the actual sub list now we start off with the actual algorithm so this algorithm will run until start is smaller than n because once it becomes equal to n we just have to stop and you don't really do performance reversing everything how we need to write the now we need to get the node to be extracted then no to be extracted as we so in the vibrant explanation earlier is simply the next node of the working point of so we'll just try Auto node to be extracted equal to working p TR next i just use auto because it's a lot easier than writing node as list node less not every time right so once you've done that we need to reconnect the next point of the working pointer to the next element of the node to be extracted as we saw in the explanation earlier right and I know these variable names are little long but it really helps with the explanation that's what I believe right so I'll just keep these names as X as explanatory as possible okay and once you've done that we need to move this node to be extract to the front of the list so we'll make the next point of the node to be extracted point to the first element in that sub list and now we need to reconnect the node before sub list to this new head or the to this new front of the list and once you've done that we just need to increment the start pointer so that we can actually donate this condition when it becomes equal to N and once we have done that we just need to return the next pointer of the dummy because that will point to the actual head of that list at that point and once you've done that let's see if this runs and it does so let's submit this and it runs in zero milliseconds faster than hundred percent of the cpp submissions and we have a great memory usage as well so this is how you solve this problem and if you learn something new be sure to smash that like button down below and subscribe to the channel for more future content and if you have any other questions just put them down below in the comments and as always the code will be in the description so check that as well and I will see you in the next video you
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
529 |
hello friends today less of the minesweeper carbon that's first in a statement we are given to teach our metrics representing the game board M represents an revealed my it represents an unrevealed empty square B represents a revealed blank square that has no agent above below left-right agent above below left-right agent above below left-right and o4 diagonals mines digit 1 to 8 represents how many mines are agent to this revealed square and finally X represents a revealed mind now given the next click position role in : indices among other unreviewed in : indices among other unreviewed in : indices among other unreviewed squares M or e return the board after buildings is positioned according to the following rules if a my m is reviewed there's a Gammy's over changes to X if an empty square e with no agents miles is reviewed then change it to reveal the blank B and all load its agent and review the square should be revealed recursively I think this sentence is very important because it actually indicates that we can use their first search to solve this problem if an empty square with no agent miles wish to do the same thing the update Boetticher all its agent I'll review the squares so there should we use that for search if an empty square with at least one agent to my is revealed then change it to our digit one to eight representing a number of agent mouse then finally return the border when no more squares will be revealed so let's see first we need to understand the different meaning of different or chars M which is our revealed my II unrevealed empty square B which is the revealed blanket square then it has no agent miles and this means eight directions above below left right to diagnose and there is a digit or to indicate how many miles are agent to choose this revealed the square and X is a revealed mine so this problem actually gives us a bolder and give us a click which the coordinate of this block we need to click so we need to sync different cases the first case is that if the block is a mine which means it is either unrevealed all are reviewed which means is M or X and it reads mine we just a return but do not forget to change this place to X if it's unrevealed okay this is one simple case if there are mines agent to this block which means there is some mines in it is a two directions we need to update the number which indicates the number of agency agent 2 miles so how do we get to the number actually we just search checks as the eight directions see whether it is all mine ok so if there is mine we just return which angel updated the numbers and we return the third case is that if there is no mines agent through this block will either to change this e to be and we needed to that first search for the other agent Iran revealed empty squares so there's this algorithm okay let's see the example if this is a given board and we needed to click this Row 3 column 1 as which first check is eight directions actually only in these three directions are valid and there is no mice so we just change it to be and then we keep up till a boulder to these three directions actually do death for search okay then this is our current place and we need to click it and we see it's eight directions there is no mind so we do the same thing we update this e to be and the Doozer depth-first search the Doozer depth-first search the Doozer depth-first search - oh it's eight directions actually - oh it's eight directions actually - oh it's eight directions actually there this direction are not valid so we just keep a do DFS then also there is no mines so we just sorted it to be the same thing there we go right until here we find there is a mind so we write a 1 here because there is only one mines in his 8 direction and we return so we do not touch this place because this we change it to 1 and the we return then we return here and we go right we also find a one mind so we write a 1 here in return we write we find the wrong Mike so we update it to 1 and we return and then we keep a co-write return and then we keep a co-write return and then we keep a co-write be BBB and we go up there will be VPP and then we go left you know there is a 1 my in its 8 direction so we updated here to 1 and then we return so in both direction we do not touch this place sorry till the end they or it just still e which means unrevealed empty square and then we return and we go left update it here to 1 and we return and we call left updated here to 1 and return and a go here update it you want in return so finally we get this final boat is here is still e so how about this example if we are given this boat and we need to click the Row 1 and column 2 because this is a mine here so just to change it to X in the return the boat okay so the Elgar is very clear now let's write the code refers to right in the directions array you should be very familiar about of these directions okay that means the same row but the column increment by one so its own right oh it's right and that means go left that means go up then go down and minus one nice one well what in the world negative one and negative one well okay this eight directions so we first get to the row index which we will be click zero and the colonists will be click one also gets the M which is the rows in the boat um it's the columns in the boat okay so if the bolder row : okay so if the bolder row : okay so if the bolder row : you call chooser which means it is a mine so M or boat row : is a X we change mine so M or boat row : is a X we change mine so M or boat row : is a X we change this place to X in case it is M so then we return the board okay then we need to calculate is a direction see whether there is mines so at first is 0 then for every direction directions the new row will be directions 0 plus row and new : will be directions 0 plus row and new : will be directions 0 plus row and new : will beat the Russian 1 plus column so at first these four directions should be valid and the new Roshan less than the M and new college should acquit or cuisine zero and the new called listen and the this boulder new Rome is a mine new colon is a mine that's a number increment by one so in the end if the number of greater than zero we just update to the boat row index to this digit the we return is both if there is no - we just update the polder row color no - we just update the polder row color no - we just update the polder row color chooser be right this is blank changing it to be okay I made a mistake here we know this is a char boat so we need a convert that which are the plus is zero change each other according to the ASCII code change which are okay therefore it's eight directions we see if this place equal to e unrevealed we keep up update this boat there will purse update both parties both in their mu there will be new row new column the finally we return this boat okay so that's it okay thank you for watching see you next time
|
Minesweeper
|
minesweeper
|
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
* `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
* digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and
* `'X'` represents a revealed mine.
You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`).
Return _the board after revealing this position according to the following rules_:
1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`.
2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively.
3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines.
4. Return the board when no more squares will be revealed.
**Example 1:**
**Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Example 2:**
**Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 50`
* `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`.
* `click.length == 2`
* `0 <= clickr < m`
* `0 <= clickc < n`
* `board[clickr][clickc]` is either `'M'` or `'E'`.
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
|
2206
|
489 |
okay so uh lead code practice problem uh robot group cleaner so two goals in this video the first one is to find the solution and do some coding the second one is to see how we are going to do in a real interview so let's get started um so remember the first step is always to try to understand the problem if there's anything unclear please bring up the question to the interviewer to ask the interviewer to clarify and also at the same time think about some match cases that we need to take special care load so given the robot cleaner in the room modeled as great and each cell integrate can be empty or blocked the robot cleaner with horror given apis can move forward turn left and turn right each turn it mate is 90 degrees when it tries to move into block its bumper sensor detects the obstacle and stays on the current cell and design algorithm to clean the entire room using only the four given apis below so we have move turn left and right and clean okay so clean means you clean the current cell turn left and right so means we'll stay on the same cell after calling turn left and turn right each turn will be 90 degrees okay and the returns true for the move if next cell is open robot moves into the cell and returns false if the next cell is obstacle and the robot stays on the current cell um okay so i think it's okay i think i kind of understand the api okay so um so for example input is like this then i'll grade it in the room and mark that's zero one so zero means the room is blocked one means the cell is accessible the robot initially starts at the position one three from the top left corner's position is while below in the three columns right okay so let's see some notes it says the first of all the input is only given to initialize the room in the robot's position internally you must solve the problem blindfolded in other words you must only control the robot using the full api's mission without knowing the room layout and initial robot's position and the robot's initial position will always be in an accessible cell three the initial direction of the robot will be facing up four all accessible cells are connected which means that all the cells marked as one will be accessible by the robot five assuming all four edges of the grade are all surrounded by wall uh cool yeah i think people pretty much understand the problem i don't think there is any ash cases at this time because based on the notes the robot star says something for sure uh a place accessible and uh yeah so i think that's yeah i think that's pretty much it all right so let's think about the solution so it's amazed question but what is what makes it special and makes it different from common misquestion is that you can only access the four apis and we don't know the layout of the maze so i don't think yeah i think um i think we since we don't know the layout um it's still pretty much just that we yeah i think the best way we could do is you use recursion plus backtracking and also we can record the cell we have already visited so that we don't need to visit it next time so i think that's pretty much about the solution um and the runtime for this uh for this would be all of n and is the number of the grade uh we need to clean like the number of the accessible grade the number of the ones so that's the total runtime okay so let's do some coding part so the thing that makes it special is how we because it's a robot and we need to make sure that the control of the robot online with which direction we are trying to move so that makes that's pretty much like a maze a common maze question plus like the operation on the robot move all right so let's see for this one let's define first of all let's define a set that contains um the position we have already cleaned then we are going to define a recursive function let's call it clean room again to just overload it so we call robot and we start at zero because we don't know which position is at we just have the current position at zero then uh clean and also we may need to have another uh parameter which is which direction the robot is facing because um at one time the robot can only have one facing direction so i'll say the robot there are three status one is the row it is at the column it is at and the third one is um which direction it is facing so this is the direction it's facing so let's see um private okay prohibit clean void clean room this is the robots row and column and this is the facing direction and also we have the side of the pairs that's integer this is um let's say this is clean all right so the first one we are going to call the robot.clean to call the robot.clean to call the robot.clean to clean the car cell and also we are going to set we are going to uh insert the current cell into the our set and then which is zero and the column so the next thing we are going to do is we are going to go for to the four directions so let's say we are going to go uh clockwise then it is going to be directions as uh so first one let's define as um go up it means minus one zero and then counter clockwise sorry clockwise is going to be a face moving right which is zero and one and then down bottom is one zero and then left is going to be zero and minus one all right so that's all the four directions and we're going to try to go through the four directions so in i is equal to zero and smaller than four plus i so the interesting part is uh we need to consider the four directions as well as the direction we are facing so let's say currently we are facing at left then it means facing currently facing if it is facing up then the next try is going to be up if it is facing left we should start from the last thing so let's say um let's say this is the directions let's say the direction the next step it is moving is direction as uh in direction as directions um let's say this is facing plus i and divided by sorry um modular four mod four so this is the direction it is moving i would say if uh the next position let's say a pair next house is equal to new pair um row plus the direction zero and the column plus direction one all right so this is an exposition if clean doesn't contain the next position and we are okay to move there then we are just going to call the clean room uh robots row plus direction zero cop plus direction one and the first thing is uh facing plus i uh divided by four and then uh they cleaned thing yeah so that's it and um yeah and after going through this branch we also need to go back tracking because if we don't go backtracking the robot may just duck suppose it's some graph like this and the suppose the robot go all the way like this way to the bottom left corner and since all the things has been have been visited then it cannot go back so the drawback gets done so we need to use we need to have it to go back so private void back so you're going to call the robot so how to go back we are going to so we are going to turn it clockwise okay so we are going to call robot.turn robot.turn robot.turn right and then turn right so and then we call robot move and we want to have it facing the same direction as before so we are going to turn call another two turn right all right so that's the back and then if uh and after we have tried to go to the next position it's time for us to just um uh try the next direction for example the first try is to move up then the next rise to move right so because we also need to control the robot at the same time so we need to call this one all right so let's check this one so there are four directions so suppose it is the initial facing is this uh and then the next direction is moving is actually we get the next direction we are going to move and the next potential position if the clean already contains if it doesn't contain the next position and the robot has already moved into it let me just call here or a facing plus one divided by four sorry mod by four this is the new facing this is the next facing yes um okay so i think we should be good let's give it a try so testing i don't really so testing usually means that you need to go through some example test case explaining how this piece of code is going to work do some standards check and then try to increase different tax coverage but for this one thing regarding tax coverage i think this is pretty much enough uh i don't really want to spend that time with your time uh listening me to explain so i said let's just use this platform too is to explore it so the next okay let's fix the typos we have currently so the back is robot okay all right so yeah so i think that's it's cleaned our room let's do a submission for it okay so it's good now yeah so as i said it's amazed question plus operating on the robot which makes it a harder if it doesn't have the robot manipulation maybe it's a medium question yeah so that's it for this coding question if you have any uh question about this solution please leave some comments below if you like this video please subscribe to this channel and i'll see you next time thanks for watching
|
Robot Room Cleaner
|
kth-smallest-instructions
|
You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API `Robot`.
You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is `90` degrees.
When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.
Design an algorithm to clean the entire room using the following APIs:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
**Note** that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.
**Custom testing:**
The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded ". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.
**Example 1:**
**Input:** room = \[\[1,1,1,1,1,0,1,1\],\[1,1,1,1,1,0,1,1\],\[1,0,1,1,1,1,1,1\],\[0,0,0,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\]\], row = 1, col = 3
**Output:** Robot cleaned all rooms.
**Explanation:** All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
**Example 2:**
**Input:** room = \[\[1\]\], row = 0, col = 0
**Output:** Robot cleaned all rooms.
**Constraints:**
* `m == room.length`
* `n == room[i].length`
* `1 <= m <= 100`
* `1 <= n <= 200`
* `room[i][j]` is either `0` or `1`.
* `0 <= row < m`
* `0 <= col < n`
* `room[row][col] == 1`
* All the empty cells can be visited from the starting position.
|
There are nCr(row + column, row) possible instructions to reach (row, column). Try building the instructions one step at a time. How many instructions start with "H", and how does this compare with k?
|
Array,Math,Dynamic Programming,Combinatorics
|
Hard
| null |
1,802 |
hi guys good morning welcome back to the new videos of firstly if you have been watching us for last one month or more for sure you should be able to through this question at least the logic okay what's going to be applied how gonna be applied because it is mixed of two concepts and both of them we have studied separately in detail so for sure you should be able to read but yeah if not then no worries because there's a high attack days are many times that you won't be able to think and maybe if it doesn't strike to you no worries if it is the case we will actually see the problem very deeply again so that next step it won't happen cool uh maximum value at a given index in a bounded array you are given three positive integers n index and maximum sum cool you want to construct an array called as nums okay I have to construct an array called as nums and it should follow the following conditions okay the length should be actually n okay cool uh numbers all the numbers inside this R should be positive which means from one up till some number um absolute difference between two consecutive numbers should be less than equal to one which means that if the number is let's say x the other number it can be X Plus 1 or x minus 1 or it can be X only in these three conditions the absolute difference between the tone between the conjugate numbers can be one so it can be X it can be x minus 1 it can be X plus one that is the three condition that the okay the adjacent numbers how they will be defined cool uh and also said that the sum of all the elements of nums which means sum of all these elements should not exceed maximum sum which means the sum it should be less than equal to maximum sum and that is how okay we have to make this particular array called off size n cool and also the condition the prime condition it says what okay after we can add it but what is the condition is that okay numbers of index is maximized as the index is given so it will just point to one index that index numbs it should be as Max as possible considering the fact that all the above conditions are also satisfied cool and we have to return okay what is this maximum number which we can put in at this index after constructing this array cool let's quickly look at the examples here n equal to 6 index equal to 1 maximum sum equal to 10 although while I was making this example I forgot that I have made it as zero indexed and I have just put it as one extra so let's imagine as n equal to seven but no worries at all anyway we are just imagining what we have to do and by just imagining what we have to do we can actually build in how we have to do it is how you actually you should actually approach your question I will never say okay it's of XYZ algorithm it is applying like this no just start to build the problem Itself by building the problem you will get to know okay what is being applied how it is say Okay n equal to let's say when I have to make an array of a size seven at index one I can put in any number I want to put in the number as maximum as possible okay I will just protract I had to put in any number let's say x I try to put in but then other condition it was saying that the sum of all the elements of this particular array should be less than equal to maximum sum so if I just put in X Plus other number also it should be less than equal to maximum sum which is 10 so for sure X which I'll put in right now initially it will also should be less than equal to X less than equal to this maximum sum so I know one thing for sure that the number which I will put in it can never exceed maximum sum right cool it will never exceed my maximum so very good now I know one thing okay I can put in a number I put in this number 10 because I know it can never see maximum now I need to fill in my entire array how should I fill in I have to put in these elements now if you remember I want the sum of this entire array to be less than equal to maximum sum so I will try to put in as a small number as possible because I would want okay the number to put in should be maximum possible and also the sum the entire sum of this array should be as minimal as minimum as possible because it will just make this less than equal to my maximum sum okay so I will just try okay and if I just place it on the place in number 10 what number I can place next to it I can place I 11 I can place a 10 I can play some 9. what you should what you guess what should I put in should I place an 11 but then if I have three options what will you choose for sure you will try to choose a nine because you want to minimize this particular sum so that because see if you put in there if you put in a number 10 you will try to put in another number such that the sum of this entire is actually less than equal to maximum sum because if you just try to put in 11 so maybe it can exceed maximum sum but I'll just try to put in as low number as possible so that the sum should actually be less than equal to my maximum so I will try to put in a line if I try to put a 9 what next number I can put in here I can put a 10 I can put a 11 I can put a 8 so I can put a 10 I can put a 9 I can put 8 again I'll try to put in 8. so I'm trying to actually put in as minimum number as possible put an eight put in a seven six five and here also parallel nine so it is okay I just initially choose what number to place at my initial index because for sure I want to maximize this number at index so I will just primarily focus on this number right here and then this numbers help I am trying to make my entire array good my entire array is made but I have to try for what okay it is I tried for number 10 but maybe the sum is still I try to minimize the sum I try to minimize this sum but still it can be possible that the sum is more than my maximum so next time I will try to put in at this index I try to put in the maximum number which is 10 but it is not necessary that all right I can put in any number from 1 to maximum sum so I'll try to put in the next number let's say 9. again I'll try to make the entire array I'll put in the next number eight again I'll put an entire array seven entirely six entire array five entire array four entire array three entire array two entire array and one entire array I try to put in every number and will try to build in the entire array and see okay if this sum is actually less than the maximum sum but as I tried as I wanted to maximize this particular number so I would firstly check with this maximum number okay why putting 10 is the sum is less than equal to my maximum sum no okay pool number is let's try for nine if it is still okay cool no okay then try for it still no try for seven then find the sum if it is still more than maximum sum try for six triple five try for four try for three oh now the sum is actually less than my maximum sum oh now you can easily say hey the maximum number you can place at this particular index one is actually three by placing a three the entire array which will be made will have a sum less than equal to my maximum but are in logic sounds clear to me but one thing can I place in every number which means I can drive from maximum sum and can go up till 1. I guess no maximum sum can go up to 199 so you can't go from every number from maximum sum to money nine two one maximum sum which is one in nine it can go up to 99 so One D nine up to one you can't go every number that is one issue I can't go at every of that number which is to find and go from one to that maximum sum so for sure I need to think of something else what I can think maybe I can just say okay I am just trying for every number right why not I just randomly choose a number in between and then say okay is that number sum is if that number sum if it is less than my maximum less than equal to my maximum sum then I can maybe try for a higher value but if it is more than my maximum sum then for sure I will try for the lower value which means all the above numbers can never be tried why because you know for sure if you increase this number every number is gonna increase ultimately so that's some as you are increasing this number thus some entire sum is going to increase so for sure if the sum still is more than my maximum sum so for sure above numbers which means eight nine ten all of them will have a higher sum for sure so just regard just discard that range that is how oh I know that I can't do a linear thing which means I can't do a linear search how about I randomly go and choose a random element and then say okay if I can apply a binary search or not because I want to optimize it I know one thing now to optimize it I can't do a linear search to think of other thing comes okay binary search but for that I'll just go maybe it is happening okay maybe not but for that I just okay I just go and look if I just choose this and it's sum it's more can I discard the entire above range of entire below range if yes then I can apply a band search I just try okay I just went on to this range the sum if it is more I for sure no I can start the entire above range now I can just look for the below range that is how we know okay we can apply the binary search here but foreign search on this number but to decide whether to start a range or not you need to find the sum also for each for that even to build the area also but you know that n is also can up till 199 so for sure you can also not build the array great you cannot build the array which means you have to find the sum of this entire array by yourself and that is again a task okay you know now you apply you need to apply a binary search but you also need to find the sum because to apply a bind search you need to find the sum at this while putting a number as a 7 on my index I need to find okay what and I know how the array will be made array will be nothing much just decreasing on the left on the right side and decreasing on the right hand left side so you know after putting in the number I add so for sure you need to find the sum of this entire array now how to find the sum RN if the number is eight I know the number can be 76543 but it can end up till here only if you had known the sum of any consecutive from one to an n in natural numbers is nothing but n into n plus 1 by 2 right it is nothing but a Max formula sum of N natural numbers is n plus n into L plus 1 by 2 so for sure if I want to find the sum of my this left range I will just go and say okay the sum of the entire range from seven to one it is nothing but 7 into 7 plus 1 by 2 right and also I am only concerned about this range so I have to discard the range right here I know that the range at the left range has a size of 5. and the number itself is of number element is of seven I have to place it from seven five seven six five forty two one so number of remaining elements actually two as you can easily see it is two elements meaning so for sure I have to minus like subtract the sum of these elements also which means now again two one or if the numbers remaining numbers had been three so it's three to one again the sum of N natural numbers but the difference now is that the remaining numbers remaining are element minus MTR is empty in a right earlier were five total numbers I have to place in which means the number I was thinking to place in was a seven so remaining numbers are element minus empty right was 5 which is this elements were actually seven which is this remaining which is element minus empty right is this range I'll just find the sum of this range by saying okay element by satellite which is this particular range which is 2 into 2 plus 1 upon 2 by just getting this formula and it is simply a match formula I highly recommend please remember this sum of N natural numbers is n into n plus 1 by 2 by this n into n plus 1 by 2. okay by this you will just get the sum of this particular range and similarly you can apply the same concept for the left part also but you saw the sum it would applicable for something like this but here you will again see okay Aryan I could see that for sure as the range gets completed the number again starts repeating one oh that is also a case which means four plays in now I place in three to one but the number again starts repeating which means here now at this case my empty range at the right side MTR at the right side it's actually five but the number I can place in our only three because three to one so remaining elements actually two so what will happen I will find the sum of this which is nothing but element into a element plus one by two which is three into three plus one by two and also the remaining are all filled with ones so it is nothing but empty R which means for sure it is 2 MTR minus element which will give me two I will just place it okay I can easily write one into this particular range or easily this also because it will just give me the sum of these two numbers so as to get the range sum in the right side again the same concept will be applied for the left side also and thus I will just easily get the sum in over one time of this entire range and you know for short you will apply the login concept to get okay right that try the mid for sure you know one thing you need to apply from low as one and high as maximum sum and I showed you why maximum sum because you know for short and the in the number at the index it can be at Max maximum sum and minimum it can go to one because for sure the numbers can be needs to be positive so I know the range of my binary search I will keep on applying to find the number at the index by the number at that index I know what should be the range what should be the sum of that particular array which will be made by this simply AP formula on both right side and left side and simply by that I can find the sum and keep on applying the binary search and fill find the answer let's quickly jump onto the code firstly I highly recommend quickly go and do the code because the code the logic was actually easy but the code part might be tricky for a few guys so yeah uh firstly I just find okay if I just place in an element at this index called as index what will be my empty range at the right which means empty right it will be n minus index minus 1 and what would be the empty at the left which will be index itself okay if the index was actually one you saw that empty range in the left was actually one right and the empty range in the right would be nothing but n minus 1. cool um now I know one thing also that my high will be nothing but this maximum sum because I know my number maximum number it can go up to maximum sum itself and low it will be one because all the numbers seems to be positive result will actually show the final result which means the maximum number at that Index this cool I'll now keep on plugging the button search while lowest less than equal to higher now in general there are two binary search Snippets which is while low is less than high you will just go and say okay if is okay then do a ANSI you don't have to mug up this while doing itself you will realize which one to apply it one says okay while is okay low is equals to Mid plus 1 else high is equals to Mid it is one such while other is while low is less than equal to high right if is okay then low is equals to Mid plus 1 result is equals to Mid High else high is equals to Mid minus 1. now when you have to put in the result at some value here you will see that both low and high will be equal and that would be the answer itself but if you want to put in the result at some value called as result then it is recommended that you apply this but anyways you can any of them third okay if I can simply do something like this I simply do it but if I want to store my result in some value and just give out that result I'll apply this particular symbol and there's no change as such just in this range while low is less than equal to High Why here it is low is less than high and also here High because for sure if it is less you will try to put in everything I just reduces it because it is actually less than equal to although I highly recommend you like just remember okay we have two search Snippets it is just for your help to make it faster it is not for you to mark up anything just make sure any way you do binary search you can do any apply you can apply any concept but okay I have just used these two now coming back to okay while low is less than equal to I will find the mid although you can simply go and do L plus h by 2 it is also fine now here I will you will see okay I am finding my write some by simply saying okay if the empty right is less than my element as you saw in this case my empty right was actually less than my element so I have to Simply do a subtraction between these two and I have simply wrote the same stuff down element into an element plus 1 by 2 minus the exceeded part and if it would have been okay the reverse part okay if empty right is actually more than my element which is the case I showed you above uh here if the empty right is actually more than my element I will simply add okay Element 11 plus 1 by 2 plus this particular part which is this extra part of once same I will do it by this particular I will find the empty I will find the right sum and same replica same just do it for the left sum because left sum is exactly also same simply you will see okay left some left sum I am simply element into element plus one by two you see exactly same it's just an empty right it is empty left empty right empty left and exact same it is left sum rather than right sum exactly same part so after finding the left some right sum your actual sum will be left sum plus mid because you place the middle number at that particular index because you are doing a binary search on what on this particular number which you're placing and that is nothing but mid so you will just place a bit and then write some now I will say okay the sum is less than my maximum sum then cool over is my result will be updated by mid I can play submit very easily and I will just try for Mid plus one else if it is not then simply try for Mid minus 1 because mid is not possible ultimately return the result and that would be it and as you saw you're applying the binary search on what on simply maximum sum on simply your maximum somewhere is considering on simply maximum sum you're applying the buy and search so your time capacity will be nothing but o of log n or log of maximum sum both are same exactly cool because you find the sum of this entire engine o of one by using an AP formula of Max does mass does buying such as being a binomous problem that is how it makes this one very beautiful cool spaces of fun and that is how you will simply find the answer that is how you just start from the question itself you just thought okay I need to place in at index which needs to be maximum so I will try to place my maximum value after placing maximum value I need to find the other numbers okay now I realize I place a maximum value I can't go and check for every value so one thing I know I can't go and check for every value so I'll try to apply a binary search to apply binary search I will look and go and actually check okay if I can apply a buyer search or not I went on to that range and I said okay if by anyhow I can find the sum so can I discard one range entirely I realized yeah I can okay for sure now guys I can apply a binary search not to apply a binary search I should know what is the sum of this range now to find the sum of this range I try to find a pattern okay I can make the array something I know okay the array will be decreasing on the right and will be decreasing on the left now I know I can make the array just try to find the sum in O of 1 because I can't do a linear S I can't go and find linearly the sum of this entire array so I try to find the formula which can actually bring in the sounds entire range and that is how you do the problem firstly reading problem getting okay how it is going a linear search then try to optimize it by any search then try to find the sum so that you can actually apply by and search on that is the actual flow you have to think to the interviewer also cool I hope that you guys like this you want to remember to get foreign
|
Maximum Value at a Given Index in a Bounded Array
|
number-of-students-unable-to-eat-lunch
|
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions:
* `nums.length == n`
* `nums[i]` is a **positive** integer where `0 <= i < n`.
* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`.
* The sum of all the elements of `nums` does not exceed `maxSum`.
* `nums[index]` is **maximized**.
Return `nums[index]` _of the constructed array_.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** n = 4, index = 2, maxSum = 6
**Output:** 2
**Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions.
There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\].
**Example 2:**
**Input:** n = 6, index = 1, maxSum = 10
**Output:** 3
**Constraints:**
* `1 <= n <= maxSum <= 109`
* `0 <= index < n`
|
Simulate the given in the statement Calculate those who will eat instead of those who will not.
|
Array,Stack,Queue,Simulation
|
Easy
|
2195
|
1,292 |
hey what's up guys this is john here so and today uh let's take a look at 1292 maximum side length of a square with some less than or equal to threshold um so you're given like an m times i'm by n dimension 2d array here and the integer threshold and it asks you to return the maximum side length of a square with the sum less than or equal to the threshold and the return to zero if there's no such square okay um yeah i mean at pretty obvious right a brutal force way will be uh we try all the possible uh out of possible length okay from zero to the minimum of either the m and n okay and for each one of them we uh we basically we will see this with that length can we find like a square with that lens whose sum is uh means is equal or smaller less than the threshold okay but that would be like uh basically that's gonna be uh what this the length is i mean we can also try that but i think that will be a little bit slow right i mean a better way is by using the binary search so why we can use binary search okay because first it asks us ask us to find the maximum side length okay and another quite uh characteristic i mean for this like uh 2d array is that you know all the elements are are positive i think it's somewhere here yeah here so all the elements all the numbers are all positive numbers so which means while we're increasing the side length okay while we're increasing the side length the sum of the uh the sum of the of each of the square will be coming bigger and bigger okay and so that i mean when we reach the sidelines to uh to a certain length then the next one will be uh then the next one will basically will not satisfy our threshold here that's why we can use the binary search because you know if the uh let's say for example if the uh the numbers the in this like 2d array it's it can be negative or either positive or negative in that case we cannot use binary search so why is that because whenever we increase or we decrease the uh the length of the square we cannot be sure if the answer will go to one way or the other right because if it has like a bigger number uh like a if this has like a negative numbers while we're increasing the length we could even have get like a smaller number because we might include more like negative number so that in that case we cannot use the binary search but for this one i mean since it's like they're all positive number and then we're sure that while we're increasing the side length the sum of this of the square will only getting bigger and bigger okay so yeah basically that's the first thing right and so once we have decided we want to use the binary search the second thing we want to you need to know is that how can you i mean quickly calculate uh the sum of the square right i mean brutal force will always be like with the current side length which loops through everything right we calculate everything within this side within the uh this range of the square with the length of the current length but i think most of you have must have known this right a better way is to do a precalculation a pre-sum of all the do a precalculation a pre-sum of all the do a precalculation a pre-sum of all the uh basically a pre-sum for 2d array basically a pre-sum for 2d array basically a pre-sum for 2d array okay so how do we do a pre-sum of a 2d okay so how do we do a pre-sum of a 2d okay so how do we do a pre-sum of a 2d array i think you guys all know how to do a pre-sum of 1d array right basically for pre-sum of 1d array right basically for pre-sum of 1d array right basically for the 1d array the current pre-summary it's just the current pre-summary it's just the current pre-summary it's just the current number plus the previously pre-sum okay and if it's a 2d array i pre-sum okay and if it's a 2d array i pre-sum okay and if it's a 2d array i for those who don't know how i'll simply draw like uh an example here uh let's say we have three four two and three four two okay so in order let's say we i want to calculate the uh the pre-sum of this one more thing the pre-sum of this one more thing the pre-sum of this one more thing so when we calculate the 2d prisms right we start from the bottom right corner so that we uh at least i think you can do either way but for me i figure out so doing it from bottom right corner is more intuitive and we are we just go backwards so let's say for example if i want to calculate the presump for this one okay this is i and j right so how can we calculate the presump of this basically what we are doing is that we're gonna do a presump right of i plot plus 1 j prism of this one okay equals to presume of the i plus one j plus the prism of the i j plus 1 minus right minus what minus the uh the presume of the i plus 1 and j plus 1 of course we have to add the current number okay right so that's that so why is that because you know the i plus one j is a p is the sum of this part okay and the presump of i j plus 1 is the presump of this part and you guys can have you can see here this part had been added twice that's why we uh we need to remove one set of this part from the uh the equation which is the i plus one j plus one that's how we get the current prism okay cool so i think that's i think from here um we can start coding okay i would i'll explain a little bit more so how can we utilize this 2d sum later on but first uh let's see what do we have here we have a we need to define a few like variables here like right like the m and n here okay and okay so for the uh for the binary search template right so the smallest value basically the lower bound is zero okay and upper bounds uh the upper bound what's upper bound like i said it's going to be the minimum of m and n okay because we need a square that's why uh the biggest square left side left is the minimum value between the iron and then okay and then uh while left smaller than right okay and then middle equals to uh left plus right miners left and then divided by two we do this like to avoid like uh the overflow okay and then uh i'm gonna have like helper functions here right if you guys have seen some of my other binary search videos so basically that's one of the template okay basically if this helper function return us a true right it means that it satisfy our current condition and since for this problem you know it asks us to find the maximum value so remember so whenever every time when you when it asks you to find the maximum numbers we always do a left equals to middle okay and then else we do a right it goes to middle minus one and on the others on the other side if it asks you to find the minimum values then we always do the right equals to middle and the left equals to middle plus 1. so why is that i think it's kind of easy self-explanatory right because easy self-explanatory right because easy self-explanatory right because let's say we're finding the maximum value that satisfy our conditions right i mean if the current middle value are like the uh satisfy the conditions so we are trying to first you know the middle could be our answer right so that's why we cannot discard this middle but meanwhile we have to basically we're trying to move as right as possible that's why we do a left with we i mean beside the middle with the we i mean with the left so that the left can be basically keep moving to the right side until it counts then we know okay the current left is our maximum value and if for the for to get the minimum value right same thing right we're like assigning the middle to the right side because basically this is the right and we're basically we're trying to move the right pointer as to as left as possible and by the time it couldn't move to the left side and then we know we find the minimum value of that okay cool so and then in the end like i said we can we just simply return the left here okay and now the hyper functions right so before doing that let's try to uh do a presump right do a do 2d prism okay so to do a 2d prism uh let's see uh pre sum uh zero okay is the and for in range m okay and since are going to start from the last from the bottom right corners and we are going to do a i plus one j plus one in order to make sure we are not going out of the boundaries i'm going to uh define like a m plus one here and m plus one here so i'm doing this just uh i just as if i'm adding like a zero zeros i'm padding basically i'm padding this 2d array here so that when i calculate this either these two or these two i can so the element i'm using is not going to going out of the boundaries because it will go basically go to the zero here okay then like uh we're going to start from the bottom right corner which is the what which is the m minus one okay yeah and minus one okay so that's the i and j is in the range of the n minus one okay so uh basically pre-sum like inj so uh basically pre-sum like inj so uh basically pre-sum like inj okay equals to what equals to the pre-sum pre-sum pre-sum sorry first one is the current number the match of i and j okay plus three sum uh yeah pre-sum of the i plus one yeah pre-sum of the i plus one yeah pre-sum of the i plus one j plus three sum i j plus one and then we also need to remove one of the we remove the intersection by once okay j plus one okay and see that's why we are going to use uh that's why i pad a padded this array here because when the i plus one reaches out of the boundaries we can we'll simply return the zero here so it won't affect our result okay cool pretty easy right so this is how we pre-calculated to the uh three sums pre-calculated to the uh three sums pre-calculated to the uh three sums now the hyper functions here okay so and when it comes to the helper functions here actually we are trying to like uh exist right we're trying to see okay with the mid with the current like side length equal to middle is equal to the middle here can we find like a sub array sorry can we find like a square whose sum is smaller or equal than the threshold okay so in order to do that we just need to loop through try all the parts through all the squares with the side length equals to the middle and i the moment we find like uh a sum a set who's smarter than the threshold we can simply return true otherwise in the end we simply return false okay so that's going to be the middle and so for i in range what since the length is middle right so the most the biggest i we can go to is like the m minus middle plus one okay because we need to make sure we have enough space for the square right same thing for the j here in range of the n minus middle plus one okay now let's say we have a level four three two and a four three two okay so with this let's say i want to calculate the sum of this range and in this case let's say the middle is like the middle equals to 2. okay so with this prism how can we calculate uh the sum of this part similar as how we calculate the prism at the beginning so what do we uh let's say we have a few other numbers let's see we have one here okay just make it more like readable here so the way we are calculating this part is that we are basically we're getting the prism of this part here we're getting the presump of this one which is the pre-sum of the uh pre-sum of the uh pre-sum of the uh so this one this part is like the i plus middle sorry this one sorry it's not i plus me it's the uh the other way so it's the i j plus middle okay and we minus this we subtract that and we also subtract this part which is what the p is the i plus middle and j okay same thing we subtract this part twice then we just need to add it back p like i plus middle and then j plus meter yeah that's it that's how we uh quickly calculate the square sum by using the pre-sum the square sum by using the pre-sum the square sum by using the pre-sum uh pre-sum result uh pre-sum result uh pre-sum result cool so yeah like i said so gonna be uh if basically so if the uh three sum right the pre-sum i three sum right the pre-sum i three sum right the pre-sum i and j minus 3 sum i j plus middle okay minus 3 sum i plus middle equals to j and plus three sum high plus middle and then j plus middle okay then if this thing is equal smaller than the threshold okay and then we simply return true okay we can simply return here otherwise in the end we return false okay yeah i think that's all i think yeah let's try to run it here oh sorry oh i think one more thing i think one thing i forgot to mention that sorry since we're doing that like since every time you know when i when we use a template where we sign the middle to the left instead of uh doing the these things we have to do a right uh plus one here so that it won't end up in the infinite loop here i think i have explained this one a few times in my other videos but anyway i'll explain it one more time so the reason being is that let's say we have a left equals to three and the right equals to four in this case if we don't have a plus one here the middle will be what the middle will be three here sorry whatever so the middle will be three and once this middle exists is equal to true here we are assigned the middle we assign the middle to the uh to left which means the left will equal will become two three again and then when it come when it comes back the middle will basically will every time it will uh align us sign this left with three and basically it will end up with infinite loop that's why i mean every time we have a left equals to middles we have to do a uh do a plus one here so that when we when this one equals to three here we just uh it will just uh become to instead of three it will become to four okay this is just to avoid uh the middle becomes the left will be the same as the left okay cool uh all right so let's try to run the code here me oh sorry it's a typo here and cool so the test case passed let's try to submit it cool so yeah so it's accepted i mean this one it's a pretty like straight classic or straightforward binary search i mean it's not that hard to come up with a binary search i mean the one thing is that you have to be able to be careful about this left and the plus one and to make sure you're not like and a stack end up in the infinite loop and the second thing is that uh since the uh the m and n is like 300 i don't think that's a big input but still right i mean you want to utilize the pre-sum a 2d prism so that you can the pre-sum a 2d prism so that you can the pre-sum a 2d prism so that you can quickly calculate the sum of the square yeah i think that's it for this problem yeah and thank you so much uh for watching the videos guys turn stay tuned see you guys soon bye
|
Maximum Side Length of a Square with Sum Less than or Equal to Threshold
|
immediate-food-delivery-ii
|
Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_.
**Example 1:**
**Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4
**Output:** 2
**Explanation:** The maximum side length of square with sum less than 4 is 2 as shown.
**Example 2:**
**Input:** mat = \[\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\]\], threshold = 1
**Output:** 0
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 300`
* `0 <= mat[i][j] <= 104`
* `0 <= threshold <= 105`
| null |
Database
|
Medium
| null |
448 |
alright this leaked code question is called find all numbers disappeared in an array it says given an array of integers basically from 1 to n where n is the size of an array some elements occur twice and others appear once find all of the elements of 1 to n inclusive that do not appear in this array could you do it without extra space and in O of n runtime you may assume the returned list does not count as extra space so given this criteria our solution will be without extra space and in O of n runtime so the example they give us has 8 elements in an array so you'd expect to see the numbers 1 through 8 but you don't see the numbers 5 & 6 so that's don't see the numbers 5 & 6 so that's don't see the numbers 5 & 6 so that's what our results will be all right so in a perfect world this is what we would have if we had four elements the array would have the numbers 1 2 3 & 4 does 1 would have the numbers 1 2 3 & 4 does 1 would have the numbers 1 2 3 & 4 does 1 2 3 & 4 look like anything 2 3 & 4 look like anything 2 3 & 4 look like anything what kind of looks like the indices of the array the indices are 0 1 2 & 3 so the array the indices are 0 1 2 & 3 so the array the indices are 0 1 2 & 3 so these numbers are pretty much the same except we would subtract 1 from them to get the index so really the way we can look at it is that every element of the array is really just an index why do we have to subtract 1 well if you think about it let's say we get to the number 4 and we tried to do something at the 4th index of the array it would overflow there is no index 4 so you just take every number and you subtract 1 so if we start with the number 1 what's 1 minus 1 that's 0 that corresponds to this what about the number 4 subtract 1 from that and we get the index 3 that corresponds to this three minus one is two that corresponds to this and two minus one is one that corresponds to this so every number can be thought of as an index so let's do a scenario where a number is missing let's change this 3 to a 2 all right so this array should have the numbers 1 2 3 & 4 but it has the numbers 1 2 3 & 4 but it has the numbers 1 2 3 & 4 but it has the numbers 1 2 & 4 so it's missing a 3 so what we 1 2 & 4 so it's missing a 3 so what we 1 2 & 4 so it's missing a 3 so what we can do is we can somehow match up every element in the array to an index and whatever index doesn't get matched up is the index that's missing I'll show you what I mean what's 1 minus 1 it's 0 so that would be here what's 4 minus 1 that's 3 this is index 3 what's 2 minus 1 that's 1 which will be here and what's 2 minus 1 again still 1 so we don't have to do anything because we already filled that one in so we can tell what number was missing by the index that's not marked but remember how we subtracted 1 from the number to get the index we have to do the opposite if we want to get the number from the index so this is the index of 2 so we add 1 so 2 plus 1 is 3 and that's the missing number from this array so when we're going this way we subtract 1 to get the index and once we find the missing index we add 1 to get the number that was missing all right but how does this actually work let's do a quick example of that so how do we mark that we've already been to an index will make the number a negative so let's begin we start at the first element that's the number 1 what index does that correspond to what's 1 minus 1 0 so we take whatever is at index 0 and we mark it by making it a negative so this would be negative 1 what's the next number it's the number 4 to get the corresponding index we have to subtract 1 4 minus 1 is 3 so we mark the number at the third index by making it negative the third index is this last number too so we make it a negative now we're at the number two what's its corresponding index two minus one is one so we make whatever is at the first index negative so this is negative four and finally we're at the last number which is a negative two but what we're actually doing is finding the absolute value of that so what's the absolute value of two that's two what's two minus 1 that's 1 which is the corresponding index so we make sure the number at index 1 is negative and it is because we just did that with the previous number 2 so then we're done with that step so as you can see we've successfully marked three elements so what's the missing number we loop over each element and see if we've marked it have we marked this one yes have we marked this one no so what index is that its index zero one two and to go from the index to the number we have to add one so two plus one is three now we're at the last number is it negative yes so we're done we know that the only element missing was the number three all right let's get to the code what lead code has given us is a function called find disappeared numbers which accepts an array called nums alright so remember the overall thing we're going to do is we're going to loop over every element in the array and mark every index that corresponds to an element in the array by making it negative 1 and then at the end any index that's not a negative 1 means that number is missing all right so let's start we need a for loop to loop over our array so for that I equals 0 I is less than the ohms dot length I plus so that would put us here all right so now remember we need a reference to the index that's one less than the element we're on so we'll say let J equal math dot apps we have to make it an absolute value of nums I minus 1 so J right now would be 2 minus 1 which is 1 and now we have to go to index 1 and make that a negative number so num Shea equals the absolute value of whatever is at nums J times a negative 1 the number at index 1 is the 5 so that'll be negative I just realized I put the parentheses in the wrong place so let me fix that all right so just to finish off the for loop the next number is 5 what's 5 minus 1 4 so we go to the element at index 4 let me make it negative so this is negative move over again this element is 3 minus 1 is 2 so we make whatever element is at index 2 negative that happens to be the same one we're on move over 1 we're at 1 minus 1 is 0 so we make the element at index 0 negative and finally move over 1 subtract one from the absolute value of this one minus one is zero so we make the element at index zero negative and it's already negative okay so now we need our result array we'll say let results equal an empty array so now we're going to loop over this array and see if any element is positive if it's positive we'll add one to it to get the index and add that to our result array so we'll have another for loop for like I equals zero is less than the length I plus so we check if it's negative if nomes I is positive meaning we haven't seen it before then we need to add it to our result array but remember we always have to add one to it so we push I plus one all right so let's see how that would work it'll be back here is a positive note so we move to the next one it's a positive note we move to the next one is a positive no move to the next one is this positive yes at this stage we're on index three so we need to add one two three in order to get the proper number three plus one is four so at this stage let's say this is our result array you push in the number four then we move over one more element is this positive no it's not so the number missing is only the number four all right so back to the code on the right since we've done all that all we have left to do is to return the result array all right let's run the codes yeah we did I made the same mistake twice parentheses are supposed to be here let's try again all right accepted hit submit all right so our solution was faster than about 83% of other JavaScript submissions as 83% of other JavaScript submissions as 83% of other JavaScript submissions as usual the code and written explanation or link down below if you liked the video give it a like and subscribe to the channel it helps out a lot see you next time
|
Find All Numbers Disappeared in an Array
|
find-all-numbers-disappeared-in-an-array
|
Given an array `nums` of `n` integers where `nums[i]` is in the range `[1, n]`, return _an array of all the integers in the range_ `[1, n]` _that do not appear in_ `nums`.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[5,6\]
**Example 2:**
**Input:** nums = \[1,1\]
**Output:** \[2\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
**Follow up:** Could you do it without extra space and in `O(n)` runtime? You may assume the returned list does not count as extra space.
|
This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?
|
Array,Hash Table
|
Easy
|
41,442,2107,2305
|
403 |
hey what's up guys John here okay so today let's talk about another like dynamic programming problem number 403 frog jump yeah I think I like this problem so I'm gonna keep my own boat here so a frog is crossing a river and there are like bunch of stones right separated across the river and the value on the stone represents the distance basically from the left bank right to the yeah basically this stone has distance one to the left bank and this one has a three this one has five this one has six right so on so forth and a frog always starts from the stone zero and then you will you need to write a program to determine if this frog can jump to the last stone which is 17 mm-hm jump to the last stone which is 17 mm-hm jump to the last stone which is 17 mm-hm and the way the Frog jumps is it can only jump assume you know assuming the last jump was K unit word or the K distance right and the next jump must be either basically that has to be like in the range of K minus 1 to k plus 1 right for example if the last jump is 4 right then the next jump can only jump 3 4 & 5 next jump can only jump 3 4 & 5 next jump can only jump 3 4 & 5 that's the range for its last for the next jump and you need to know you need to write a program to see if this frog can jump to this 17 here right so I think it's obviously a dynamic programming problem but how do we think how do we conduct our solution right and I think one way is that we need to know a lucky for example let's define a DP I here right I still find epi here so the normal way of thinking about dynamic programming we need to deduce this the value of dpi from something DP I minus 1 right word dpi minor so some sort something like that right and if we go that route this problem can be solved so basically this dpi and J right so this I means the dice position of the eyes position of the stones right and then what we do we owe and the keys the stone index and the value what's the value is going to be the key is the stone right and the VAT what's the value is a set of all the possible jump distances that can reach the current stones right set of our jump right for example if there are like three ways that can reach this DP right so they're gonna be have three sets in the interview here like for example three five or seven right and every time moving cease this DPI here right we just loop everything starting from zero to I right and for each of the deep for each of the dpk right in for example of okay here if each of a TP k here we check okay among added for all the case right for other for each like to jump options from this DP k if this thing is in the range of our I minor scale right because if the current i2 conic eight that's the distance of ika right if this I can be jumped from any of this value right if it is and then we know from k2 I we gotta like we have a result right so basically we just add disc from the distant the jump I minus k2 this to this current I here to DPI here and we just loop through all the possibilities from 0 to K alright and in the end we just track okay so if the DPI is a set in the of this DP n minus 1 right DP n minus 1 that's our final result here if this DP and minus 1 if the length if the set right if the length of this because the value of this is it's a sad if the length is greater than 0 then we know we have at least one possible ways of jumping into this the final stone right yeah that can be that I think that can fast but it will be a bit slower because for each K right every time we are we do three duels a loop from old from 0 to I right so basically that would be like I think oh and Owen square no Owen squared times anything Oh n like to the three yeah okay and there is another way of thinking about this problem I think that's the correct solution we are gonna we're gonna base down today we're gonna do it that's the correct solution will be coding on today so okay let me clear that so another way of thinking about that is know the DPI right so still deep dpi okay instead of saving storing the key is still the key in value right in stock instead storing the index of the stone here we store the vital here we store the distance that stone represents in this case that's zero one three five six eight twelve and seventeen so this is gonna be the distance for the stone itself and the value is the same the value are the same as the previous one still the same of the possible jumps so it's a set the possible jumps that can reach this like us this stone and the way we're calculating it we're not going back so when we calculate a DP right when you calculate the d DP i we're not going back to look for the DPI minus 1 I minus 2 instead we will be going forward to deep here something like a deep dpj oh where J is greater than I how right that's because at the current TP right assuming let's say we already have the values of the current DP which is zero right for the current for zero we know the length of the zero is zero right and the jump basically that the first DP the DP 0 it has only one element in the set which is zero basically for DP for the first stone we jump 0 right and then starting from there we can calculate so from zero we know that the next jump has to be 1 right because that's 0 1 and yes 0 and 1 and then how about the second one and then the next round will be a will be 1 or 2 right 0 means nothing we this has to be a jump otherwise doesn't make sense right I also beat you one hand too how about this jump still 1 2 & 3 right so this jump still 1 2 & 3 right so this jump still 1 2 & 3 right so every time when we see this DPI here we already we have the we will have the add all the possible jumps right and then we just get each jump right we get each jump of the current DP and then we just do a small for loop to a K minus 1 to k plus 1 and then we look for we look forward we look in the later units if any J appears right and then we add that jump into this d pj because that's when we know okay we find another possible way to jump into the later stones and then later on when we process this d pj we already have out possible possibility stores in this like set all right and in the end same thing we just check that for the last stone for this last stone how many possible ways we can jump into this basically instead of going looking backwards this time we're looking forward since we already have the since we know how can we jump how come it what are the possible ways we can jump from the current stone right so and okay let's try to code these things here okay same thing here right and let's get the lens off the stones first and then let's create a DP right in this case the DP will be our I'm going to use like a dictionary for this DP instead of a list because a later on we'll be looking for the keys in this dictionary so in that case the dictionaries is faster than the attend the list so and the value of the dictionary will be we can initialize it right because we know the value the key will be added all the distance for this stone right so the value is gonna be stoned right and how about the value is going to be the set right for stone in stones right that's how we initialize this DP first we put all the distance there which there is empty set and then for the DP for DP 0 we know right there will be only one set only one element in the set which is zero right so that's why we add zero because right and then we just loop Thea I in range and right because we'll be starting from zero right because we already have the distance to jump distance for zero and okay so let's see so the next step will be we're at the current stone and we'll be getting all the possible ways all the possible jumps sizes that can jump to this current stone right for out okay and range write DP high right so for each of these jump stones right and if then we have we need to have like a another small loop here right for step from K minus 1 right from in range so with each of the jump distance and we'll be doing this K minus 1 to k plus 1 right so that's why we do a step in a range K minus 1 - okay a step in a range K minus 1 - okay a step in a range K minus 1 - okay o'clock plus 2 right that's what that's the small for loop for each of the into K here and then we do what so like I said the step first the step has to be greater than zero right so if step is greater than 0 or we can see you step and what and let's do a check right week since we only care about the stones here right for all the other distances we don't care and let's say mmm so this is the current yeah if the step that's the step we can jump okay so and k-class stop right jump okay so and k-class stop right jump okay so and k-class stop right because that's the current but that's the other previous jump and that's the next jump we can make based on this K right if this thing is in the DP right so that means okay so the next jump is one of the stones here right so which ad right we just add this thing to that DPS k plus step right since we're since the key is that is the value of that right so we just add that into the earth jump it's the step right yeah because that's the front from the current the distance of the last jump is k2 this step right and the next jump the next step will be one of this right so k plus the step will be the next jump that we can that this term can reach and this the next jump if it's false is one of the stones in the later and we just add this current stab to that stones likes at least right and then in the end we just simply return right if the length of the DPR stone is the yeah so the DP of the value oh that's the stones like - one right the last stones - one right the last stones - one right the last stones right if this DP is greater than 0 if this if the last stone because the key the stone itself so we'll use that to find the last stones are set right if the set the last is greater than 0 then we know we find at this one way of jumping into that last stone right I think that should okay let's say for DP yeah I think here it's not a DP it's not I since we're using the stoma is the key so here should be the stones I write we're using the value of the stone to be the key mmm DP oh sorry it's not yeah it's not range yeah I'm sorry we are looking at the set here so we're simply cut average each element in the set right not the range so just to set its up here and then each element in the set and then which try to get the possible next step from that from the current previous one oh okay sorry so here yeah I'm sorry here it should not be the sorry the previous K here it should be the cornerstones distance right so that's the yep yeah so from the current distance from Constance that's our base basically that's our the base of the distance and that's the jump step here right so we have to use the current stones distance Plus that step and then we can have the crack the next distance yeah sorry about this all this kind of confusion here and like I said so basically let's take a look at the problem here one more time so what the key idea here is that instead of using the index we use the stone distance itself to be the key and the value will be the set right uh-huh what value will be the set right uh-huh what value will be the set right uh-huh what how many other possible jump-jump like how many other possible jump-jump like how many other possible jump-jump like distances that can be jumped into the current currently stone and the one every time we only see a new stone we get all the possible jumps right possible jumps to the current stone right for each possible jump we know which that possible is that jump distance we have three possibilities to jump to the next position right that's why we loop from K minus 1 to k plus 2 so for each jump possibilities we get the new jump you know we can next jump start right jump distance and we can do this I think so the next jump distance will be a will be the current position right so since we have I we know the current distance right I say for example four right we know two four and the next jump step right here right so the current song four plus whatever the jump step is will be the next place we can it can jump to and we check so first if this jump the jump step has to be greater than zero otherwise it doesn't it didn't jump right and the second we check if this next jump distance is one of the stones right then we just simply add this jump step right to this step distance it could be duplicated but since we have a set here so keep adding the same if we add a duplicate step here it doesn't really matter right yeah every time we see a possible we see another stones in our predefined the DP dictionary we just add this possible step to this like DP element in the end which is child we check all for the last stone do we have any possible jump waist jumps that can be jumped it that can be jumped to this final stone right yeah I think that's pretty much for this problem the only this little trickier to remember here is the instead of looking back like the normal DP problem this DP problem is looking forward right that's the only difference cool thank you so much for watching the video guys are we are seeing you guys soon bye
|
Frog Jump
|
frog-jump
|
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.
If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.
**Example 1:**
**Input:** stones = \[0,1,3,5,6,8,12,17\]
**Output:** true
**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
**Example 2:**
**Input:** stones = \[0,1,2,3,4,8,9,11\]
**Output:** false
**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
**Constraints:**
* `2 <= stones.length <= 2000`
* `0 <= stones[i] <= 231 - 1`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order.
| null |
Array,Dynamic Programming
|
Hard
|
1952,2262
|
1,648 |
okay so lead code practice question uh in this video we will go through this uh problem which is called cell diminishing valued colored balls and we will explain what the solution is and we will explain the procedure we should follow within a real interview so let's go through this problem so remember the first step in a real interview is always try to understand the problem and think about the ash cases ask some proper questions etc so let's go through this uh description you have an inventory of different colored balls and there is a customer that wants others balls of any color so the colors so the customer weirdly values the colored balls each colored ball's value is a number of the balls of that color you currently have in your inventory so for example if you own six of the yellow balls the customer will pay six for the first yellow ball and after the transaction there are only five yellow balls so that the next yellow ball is then valued at five so and so forth and you're given an array of inventory where inventory i represents the number of the balls and the ice color so you are also giving teacher others which represents the total number of the balls that the customer wants so return the maximum total value that you can attain after selling others colored balls as the answer may be too large you will do modular uh one billion plus seven so let's see about this so we have two co two colors and the first color has two balls second color has five balls and you the other is four so of course you're going to first sell the uh the color uh that has five balls and then after you sell it you have four of the balls of that color and then after then you sell it you have three of the color and then after that you have you for each color you have two of them and then you can sell any of them to make the fourth transaction so the total maximum gain we could get is 14 in total so that's pretty uh straightforward i think um so i mean the question is pretty straightforward but let's see the constraints so even three dollars is between one to uh 100 100k so the inventory is not going to be empty and also the other will not overflow the maximum number of the balls we currently have so uh let's go through the solution so the solution is more about a greedy uh it's a greedy solution so it's essentially every time you pick uh the max the ball that ha the color of the ball that has a maximum count so for example we have two uh colors and the first color has two balls and second color has five balls so we are going to do it in a greedy way we are going to sell it sell the color that has a maximum count which is five so we gain five and then the next time we have two and four in the array so we are going to sell the color that has four balls so on and so forth so every time we choose uh the ball that the color of the ball that has the maximum count to sell to achieve the maximum gain and that's that and so on so far as we just repeat it so essentially this is more like a um so after you understand the problem it's more like a mathematical formula you're going to write down uh to calculate the final number so let's go through this piece of code so first of all i define a helper function to sort the event tray array which is the integer array in this should be decent the other i think so this is in descending other uh let me submit it again yeah so first of all we sort the array in descending order from the largest to the smallest this is the helper function and then we set the total to be zero and well the other routers is larger than 0 then we are going to go through the logic within this while loop and finally after this while loop uh the others is going to be smaller or equal to 0 we just going to return the total gain we could achieve so the max is of course the first uh thing in the inventory right because uh we have already sorted in this any other so the next is let's say the next is equal to zero so next means uh the index within the inventory that doesn't have the value as max and the count is essentially how many uh of the items within the inventory array that has the value as max so this will loop tells us uh how many of the colors that has the count as max and this uh so if the count is small the count if after the well loop we not we are not going uh we are not out of the range of the inventory array then it means uh then we still have some ball that has some color of the ball that has a total number like they had the count smaller than max so we are going to set the next to be uh the next uh the second i would say the color of the ball that has a second larger inventory and then we compute the total so we are going to uh do a cell on the color of the box that has count as max and within the after this order we will have uh the maximum of the maximum count of all the colors to be equal to next so this is essential this helper function essentially tells us um uh to achieve this kind of other uh how many dollars we could gain from this kind of order and we compute the total and then we uh minus the other um because we have how many transactions we have count times max minus next and then we set uh all the inventories um so we reset the uh the balls we have sold to be next because we have so for each of the let's say we have uh let's see the array is something like five four three so we let's say it is five three so we are going to sell the first two ball two colors and then after the transaction it will be something like three so you're going to sell uh two of the first color and two of the second color to make sure that after the transaction this is going to be the number of the balls of the first two color is going to be changed to be the same value as the next maximum so that's essentially what the transaction is and within this helper function it is how many dollars we are going to achieve for this kind of transaction uh so it is more like a mathematical calculation about that so that's pretty much it about uh this kind of solution so if you have any question about the solution or about the code so 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
|
Sell Diminishing-Valued Colored Balls
|
minimum-insertions-to-balance-a-parentheses-string
|
You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the `ith` color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**.
Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** inventory = \[2,5\], orders = 4
**Output:** 14
**Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
**Example 2:**
**Input:** inventory = \[3,5\], orders = 6
**Output:** 19
**Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
**Constraints:**
* `1 <= inventory.length <= 105`
* `1 <= inventory[i] <= 109`
* `1 <= orders <= min(sum(inventory[i]), 109)`
|
Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer.
|
String,Stack,Greedy
|
Medium
|
2095
|
337 |
Everyone, so today we are going to solve the question which is a tree structure immediate children cannot commit robbery. If he commits robbery then the police will be alerted. Okay, so now what we have to do is tell us how to take the maximum amount. It is possible that by doing a job in a house, if we look at this example, he got 3 amount from the root house, then if he does it in the root house, then he cannot do it in the immediate children, so he got the amount in the house which is on his left and which is on the right. There is a house in which Robin met Kari Waso and the first note was three root note to the right of him in the house from where he got the van, from here our value is 7 and 7 is the answer, similarly if we look at the example then either we are free If we will do robbery in 1 and after that we cannot do it in four and five, then in this case we will not do it in 3 because from here we will get the maximum amount, so let me simplify the question a bit, I will ask this question once the message is cleared, then ok. If we are in one house then we will have two conditions, that means there will not be 2 conditions, if we are in any house then we will have two conditions, so the condition that I have is either I can rob or I cannot rob, so if I am in this If I commit robbery, what can I reduce? If I commit the amount, I will get it. Similarly, I cannot do it in entry because it is running direct, so I am not doing n6, so what can I do ? Then or else I do not include N2 itself, this is ? Then or else I do not include N2 itself, this is ? Then or else I do not include N2 itself, this is a sample concept, if pick and no pick becomes an option then how will it be Suppose I am also on n1 then what will I do one second this train and if I call on whom will I call left side left of n1 Right, if I write left plus n1, what will I get? I will consider that as my final answer. Write it in a little code. If Star Road, ok if our road, now I have two options. Here I Should I include it or not? I will enter the value of the root inside it. Now I will call its left side, right side and right side. But before calling, I will check whether it has a left side or not. No because the left side will be no will give you an error A plus equal tu it will be small in this I don't know if the road adjusts to the right then what will I do I will simply solve I will call the right of the route one more time I will definitely call the bar on the left of the right and the right of the root is written right in front of the base. Look, I will erase it. I hope you understand. Look, if I call n1, what is the option for n1? Once Now if we don't include, we are calling N2 and n3. Okay, now we will call N2 Clay and Takle, what will happen if we include once, if we do n't include, then the value of that plus those which are not direct children, okay if I don't include. If we make our call, then we will repeatedly call for note with parameters, then our time complexity will be more, like we can create a data structure, inside it we can load and keep a value. Ok now what will be the value? I would assume that if we are at n1, if I am taking n1, I am not taking n1. After including these two cases, whichever answer gives the maximum value to me, I will return the value of that one here. Took the value and took my interview, I will be saved from Noida here, so one, we have to make a global map, now we have to make it global and we just have to write here MP Road equal, you are ok and again this is ours. There are functions which are given in the question, I have taken a global map as the reload and brick value, I cleared it and placed a function call. If you look inside the call, if it does not take the value of the root, then we will return zero. That one. The value will come when we are including the particular node and I have placed it in the map. The note that we are calling now is something that we have never encountered before. If we have not encountered it then the value will be present inside the map. Will return from there and if what to do on the left of the route, we have included it a little ahead. Here we have written the value of A+ route and what was the other option, I should not include the note on the road. If I do not include it, then it will be its immediate child. So I can include left of sub root and right of root and I made it a data, this is the code, I submit it and it is accepted.
|
House Robber III
|
house-robber-iii
|
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Medium
|
198,213
|
1,877 |
hey everyone uh today i'll be doing leap code 1877 minimize max pair sum in an array this is one of those ones that is medium simply because the description in my opinion is really easy so really all it's asking i'm going to get this list and explain it gives you a list of numbers and it wants you to pair them up in a way that you minimize the maximum pair sum now that sounds confusing but basically you get all the pairs you sum them up and you take the max of those sums now naively you might think oh the smallest pair is the two smallest numbers which is 2 plus five and that's five or two plus three and that's five um the problem is with this is since we took that as a pair we have to pair up all the other numbers so what if five and six get matched and that's eleven is bigger than five so that would actually be our answer if we did it this way and we can actually see we can get it smaller if we look at this example here we actually can get it to 8 so it's impossible to make 8 as the answer if we do it this way so what we really want to do is we want to uh sort this and if we sort it's two three four five and six uh so we sort it ascending and we basically take the smallest and biggest and we keep doing that and in this case it would be two plus six three plus five four plus four all of them are eight uh so the max is eight now this is always going to be the smallest uh because it's evenly spread out and we're not taking the two smallest and have to pair up the two biggest this is always going to give us the smallest maximum that's like my half-assed way of proving this but half-assed way of proving this but half-assed way of proving this but basically let's have a result let's return our result let's go ahead and sort the numbers as i said we'll just do it that way and let's go up till half of the array now i'll explain why i'm doing it this way okay now we want to get the first and the last so let's call this pair sum just to make it more readable and the first is easy and let's add it to the last which is just numbs length minus one minus i now it's done this way because it's actually i from the back of the array so at the zero width uh we want the zero width from the back so it's just the last element uh at the want index we actually want the nums dot length minus two so the second from the back so this is the pair sum and because we have to take the maxes we really go res equals math.max really go res equals math.max really go res equals math.max uh whatever is currently at res and parasol now this is basically just going to run through and set the new maxes for results so whatever the current max is with parasum it'll take the max of them so let's go ahead and run this and uh it'll be accepted uh so let's go ahead and submit that and the reason yeah this just works because it's evened out and this is actually very slow solution probably because we are sorting this but you know let's go over the time and space complexity behind this so right away this loop doesn't matter at all because we're sorting and sorting is m log n and this loop right here is m so n log n is greater than n so the time is actually going to be uh n log n and the space uh we're not using any extra space we just have this integer array and we have some result which is just a variable so space is actually just uh so yeah this is pretty simple i hope it makes sense enjoy
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
86 |
hey everyone welcome back and let's write some more neat code today so today let's solve partition list or partition a linked list because we are given the head of a linked list and a particular value x and we want to partition the list such that every single value that's less than x is on the left side like over here and every single value greater than or equal to x is on the right side of the list like over here so you see in this case this was our input linked list and the value that we were looking at was three so we took every single node less than or rather just less than three right and there were three nodes and then we put them on the left side and we took every value greater than or equal to three so four three and five and put them on the right side of the linked list and there was one last thing we had to do with that we had to preserve the original order so there were three elements that were less than three and we had to put them in the new list in the particular order that they were given right so we had to do it in order similarly for the values greater than or equal to three we also had to preserve the original order so it's four three five so let me show you how to solve this problem in o of n time and constant space so here's what i'm gonna do i'm just gonna iterate through every single element in the input list if you know in this case our x equals three if a value is less than three i'm going to go ahead and add it to the left list i'm gonna create two different sub lists if a value like 4 is greater than or equal to 3 then i'm gonna add it to the right list and at the end we'll have all our less than values and the left list will have all our greater or equal to values here and then at the end what i'm going to do is i'm going to take our left list and then connect it to the beginning of the right list so this way we will have a new list that we partitioned and will preserve the original order of elements the way we want to and we'll be able to connect these two sub-lists left and right sub-lists left and right sub-lists left and right so first value one is less than three so i'm going to add it to the left list and now the next value we add to the left list is going to be over here so next we look at four that's greater than or equal to three so add it to the right sub list we have three itself which is greater than or equal to three so we're going to add it to the right list the left list only has values that are strictly less than three next we have a two so i'm going to add that two to the left list now we have a five the five is greater than three greater than or equal to three so now i'm going to add it to the right list and lastly we have a 2 so i'm going to take that 2 and add it to the end of our left list now in reality since the 2 was the last list in the node we know that it had an extra pointer that was pointing at null and we didn't update it so technically this list is ending in a null and we know we're gonna end up connecting it to the beginning over here but what about this five what's the next pointer of the five pointing out well it was originally pointing at this two right so technically right now we have a list like this right so keep that in mind so in reality i'm gonna take this null right instead of pointing at null i want this node to point at the beginning of the right list so this is a little more clean so it's pointing at the right list so now left is the start of our total list right so we start at left we go here then we end up going all the way to this four right and then we go to three and then we go to five and look at this five the five is technically still pointing at the 2 so this kind of creates an infinite loop for us even though the picture is getting a little bit messy now but so what i'm basically saying is since we know this 5 is going to be the last element in our list we're going to take its next pointer and end up setting it to so now if you just want to quickly look at what the actual list looks like so this is the start this is the end so we have a 1 the 1 goes to a 2 that goes to a 2 this 2 ends up going to this 4 which goes to the 3 which goes to the 5 and the 5 you can see points at null over here so this is the end of our list and this is going to be our output list so this algorithm is actually not super complicated now let me show you how to code it up so as with pretty much every single linked list problem i'm going to need some dummy nodes because i just like doing dummy nodes they're never really a requirement but i think they make the code a little bit shorter and easier so i'm going to have our left and right lists initially initialized at dummy nodes basically just empty nodes that we create but we're not actually going to include these in our resulting linked list i'm also going to have tail variables so left tail and right tail which are always going to be pointing at the last node in our left and right list so we can easily add an element to the end of each of these lists and basically i'm just going to iterate through the entire input list so while the head is not null i'm going to check is that head value less than x right because that's what we're really looking for that's how we're partitioning this list so if the head value is less than x then we're going to be adding that head to the tail so tail dot next of the left list is going to have head inserted and we also have to update the tail now so the tail is going to be tail dot next because we're just incrementing it one spot so the next iteration of the loop we can add the next node in the correct position we're going to do the exact same thing except now the else condition is if the value is greater than or equal to x which we know then we're gonna add it to the right sub list so right tail dot next is now going to contain head and then we have to also update the tail and regardless of what either of these conditions which one executes it doesn't matter either way we're going to have to shift our head pointer so head dot next is going to be head now so by the end of it we will have gone through every element partitioned them into left and right sub list now one thing we have to do is connect the list so the left tail dot next is going to be the first is going to point at the first node in the right list so right dot next we do right dot next because right itself is a dummy node so right.next is going to be the first right.next is going to be the first right.next is going to be the first real node in the right list and we also have to terminate our list meaning the last node has a point at null so we know the last node in the list is right tail so right tail dot next is going to be set to null and now we will have our perfect partitioned linked list and we can return it which is going to be left dot next because left itself is a dummy node left dot next will be the first node in our list so there you go you see it's a pretty efficient solution not a lot of code but it's a definitely a solid linked list problem to get under your belt and i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
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
|
1 |
today i'm going to show you how to solve this problem very easily so there are actually two ways of approaching this problem the first one is the brute force that actually starts from here so we're going to check one and six one and five so what's this problem all about so we are trying to find two numbers from here that if you add them together it's gonna give us a target obtained so if you take one plus six it doesn't work because it gives us a target of seven let's take one plus five it gives us six so it doesn't work well we take for instance we take um let's say four here and six here and that gives us four plus six is going to give us a target of 10 so what i did now is the brute force material so you're going to start from one and check one plus six one plus five one plus three one plus nine okay now we go down go next to six we're gonna check six plus five six plus three and so on so if you do that what's gonna happen is that you're gonna have two loops so a for loop and another for loop so one loop is going from the first one the second loop is going from here and then are going to compare what is here uh with what is in this index so let's write it first this is a brute force method and let's see and then we see how we can actually improve on it i'm going to be using java uh for this exercise so let's see how it plays out so the first thing i'm going to do here i'm going to uh start a loop so i'm going to say for um let's say for and i is equal to zero i is less than uh norms dot lens and i'm going to say i plus i'm then i'm gonna move on to the next loop so i'm gonna say points j is equal to zero j is less than now j is actually gonna start from i plus one right so it's going to start from the next index following i says it's gonna be i plus one now let's say j is like the num stop length and let's say j plus so at this point what actually do we want to do in here what we want to do is we are going to check the item at index i and the item of index j one when we add them together is it gonna give us targets so i'm gonna say if the norms are norms index i as the item index i plus items index j norms j is it gonna give us is it equal to the target because we are told that this has to be equal to the target for you to return uh for e2 and then provide the indices of those items if that is the case then we are going to return a new array containing these two indexes only two elements in the array so i'm going to return new int array that's going to be made up of items uh items i and j okay so at the end of the day nothing works it doesn't return there and it doesn't find anything maybe we can just return null but i think they are guaranteed that uh is going to be in there however if it doesn't for any reason it doesn't find interest rates on all i'm going to run this code right now and let me just check and check i didn't make any mistake okay so i'm going to run the code now and let's see what we have and it says uh in the girl startup expression so how this is j plus here that's my mistake so i'm going to run one more time and let's see cannot find symbol norms dot length i think it's actually gth instead of t ht gta so it's different from height i think height should be ght both length gth all right so this works if i submit it now let's see uh the time it takes to actually execute it takes 48 milliseconds i think that's pretty little time but when you have an array made up of like millions of or hundreds of thousands of values and this time is pretty much so how do we reduce this time okay so to do that we're going to use a hash map what does it mean so let me just go back to my whiteboard and explain it to you so in this case what we are going to be looking for as we make this iteration we are going to be looking for complements of a of the items in the map so if we come to one we are going to check our map let's say we have a map here so i cannot actually draw so well let's say we have a map here that has the index and the value so here we have one we have we put it in the map uh we have one and put the value in there to be one actually this index zero contains one index one contains six and so on so once it gets to index take for instance index 4 we are going to check for target minus 4. that's what we are going to be checking in the map so this we call it complement we're going to be checking for this in the month so once we get to 4 regular check oh target minus 4 10 minus 4 6 is 6 in the map yes then we're going to return the index of that item understand the current index let's see how this plays out in code um so the first thing we want to do here is to create a map so create a map we're going to just say map of integer uh let me call it mark is a ball to new hash map i don't remember this is como case i think it should be like this yeah and i'm going to simply initialize empty okay so i'm going to start just a single for loop now so i'm going to save for ant i is equal to zero i is less than norms of length gth and i plus now here is the thing now the first thing i want to check now is that if the complement of this item is in the map so i'm going to calculate the complement first so complement is going to be target minus the current item which is norms i right good so this actually should be a minus sign here and we are now going to check if map dot contains key so we're going to check map that contains key and the key we are checking for let me put brackets here and the key we are checking for in this case is a complement so actually the keys are the complement while the values are the indexes so sorry about that okay so while it contains com if the map contains complements we are going to actually return it so we are going to return new uh new integer array and the content of this is going to be the map dot gate i think that should be it and i'm going to get the index of the complement of that complement we found and then i'm going to use the current index as the next item in the array we're gonna return and by chance it doesn't find nothing we are simply going to return put in the right place we are simply going to return null okay so let me just cross check to make sure everything's fine complement is target minus numbers i if model contains key complement return new int model get complement and i okay else i forget this so else if it's not found we are simply going to put a map approach and we're going to put the we are going to put that item in the map norms i and i think this should be it so this is a complex this item and this is the index is going to be the value so they have a key and the value so now take note that the original for loop uh um nested folder that brute force method are used for eight milliseconds let's now see how long it's going to take this one using hash mark to execute so first let me run it just to make sure i don't have any errors i think i should have errors because i'm missing a semicolon here so i'm going to run one more time and let's see um cannot find symbol compliments i'm just going to display sometimes i'm mixing up python with java um and we have to make uh wait for one or two seconds before we run again so let's see okay so let me try one more time run okay and now cannot find symbol map why so actually noms not norm so wrong called and this time it works and let's see exactly how long it's gonna take uh compared to existing 48 milliseconds and this one takes one millisecond just thinking about it from 48 milliseconds down to one millisecond that is great so that's the advantage of being able to optimize and make your code a little more faster in this case we are using order of end time so all of aim we're having both and using the hash mark o of a or using the next for loop we have of entropy however this one actually also uses base of uh of a as well all right so i'm going to stop here i would like to thank you for viewing please remember to subscribe to my channel and if you have some challenges you like me to crack for you please leave it for me in the comment box below i remain times on the tech pro and i'm always there for you
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
417 |
welcome back to algojs today's question is leak code 417 pacific atlantic water flow so you have an m by m rectangular island that borders both the pacific ocean and atlantic ocean the pacific ocean touches the left and top edges and the atlantic ocean touches the right and bottom edges so the island is petitioned into a group of square cells you're given an m by m integer matrix height where height rc represents the height above sea level the island receives a lot of rain and the rain water can flow two neighboring cells directly north south east and west so up down right and left if the neighboring cell's height is less than or equal to current cells height return a 2d list of grid coordinates result where result rc denotes that rain water can flow from cell rc to both the pacific and atlantic ocean okay great so we have a 2d board right here and the left side is bordering the pacific the top side is bordering the pacific the right side is bordering atlantic and the bottom side is bordering atlantic so we need to work out which of these cells can reach both the pacific and atlantic based on the constraints that water can only flow from higher values to lower values or higher values to values that equal to those values and we can only move up right down and left so this is a standard graph problem we'll probably be utilizing bfs or dfs in the solution so as you can see in this example all of these values in yellow can reach both the pacific and atlantic ocean okay so firstly let's quickly discuss how this water flows so say we take five here water can flow in four directions it can flow up down left and right and it can flow from higher values to lesser values or values that are equal to each other so we need to make sure that we reach the pacific and atlantic from this position if we can't then it's not a valid point within this grid so let's have a look so five can flow to four can flow to two is touch in pacific five can flow to three can flow to one is bordering the atlantic so this is true so how would we go about solving this well as i mentioned we can use bfs or dfs it makes more intuitive sense to utilize bfs in this solution because it's essentially the shortest path so we can forget about dfs now within this bfs we are going to have to do two breakfast search so we're gonna have to do one for the pacific and one for the atlantic because we need to find whether a value can reach the pacific and the atlantic and then we need to do some additional logic to state whether a value in the board can reach both the pacific and the atlantic but as with any bfs we have a queue so we're going to have a specific queue and we're also going to have an atlantic queue and what we're going to push into this is going to be the position of each value within the board and what we're going to push into say this specific queue is all the values within this board that are neighboring the pacific okay so all of these values and all of these values are going to be going into the pacific so the positions in this grid will populate the specific queue so let's write a few out so we've got zero one and one zero i'm not going to populate the entire queue otherwise this would take all day so that's specific we'd also do the same with atlantic so all the positions in the board that's the touch in the atlantic so all of these values and all of these values all of their positions are going to be added into atlantic so we've got five here five four and four five so we're just going to do the same for atlantic with bfs as you probably know we're just going to take from the top of the queue and we're going to look at this value we're going to check all of its neighbors and carry out breakfast search on them now as you can see the left side and the above arrow are out of bounds so we need to take that into consideration and we need to create some kind of is valid function to check whether it's inbound so if we're outside of the board in any other direction so if i is less than zero j is less than zero i is greater than heights dot length minus one j is greater than height zero dot length minus one all of these are out of bounds so we just forget about those and we continue through the bfs on the other values so can we go to three and can we go to two well as stated in the question water flows from higher values to lower values but that's getting to the pacific and the atlantic so in this case we are looking for greater values right because 2 can then flow to 1 3 can then flow to 1. so we check to see whether this value is greater than this value if it is then we can go down and bfs that value and the same with 2 here so we can go here and we can go here so we push those values into the queue so zero one and one zero so here we have an issue right we've already got these within the queue so if we push them into the queue so 0 1 0 we're going to have to visit those again so we need to keep track of where we visited so we're going to have to populate another array so we're going to be creating a 2d rate of the same size as this board and we're going to initialize it with false in every position so as soon as we take the value off the queue to visit it we add or we update this visited array to true so the position is set to true so this has now been seen so if we pop off the same value again we can look into this visited array and see that it's already been seen so we can continue so we can check two can be visited we'd look at its different directions two can go to two and it can go here because they're equal values can't go here so we push these positions into q and bfs on those so i'm not going to go through the entire board on this i'm just going to update this array as to what the values are supposed to be and then we can move on to the atlantic it's pretty much the same process so i'll speed up this play okay so we have shifted off of queue all the positions we've set our visited array to true on all those positions that we've checked and we've made sure that all of these positions can reach the pacific ocean so they can reach these positions here so these are all the values within the board that can reach those positions okay now it's very much the same process for the atlantic so we shift off q we look at this position we go to all of its neighbors and we carry out bfs on all of those as long as those values are greater than or equal to the current value we're on and we do that for all of the positions and if they are a valid position then we push that into q and then we shift off push into q shift off you get the idea so what we're going to have at the end is a visited array for the atlantic as well and all of these values which have been changed to true can reach the atlantic ocean so as you can see we have two arrays two visited arrays one for the pacific ocean one for atlantic ocean now we have some additional logic to carry out in order to work out which positions in the board can reach both the pacific and atlantic and because these boards are both the same size we can carry out a nested for loop passing in the board's width and height as parameters and we can check whether the position we're on say this position for example is true for both this array and this array if it is then we can create a results array and we can add into the results array that position so that'd be five zero and we do this throughout the entire board and what we're going to get is all the positions in the board that are both true for reaching the pacific and atlantic ocean so that's the main idea of how you'd calculate the solution right how you build out this algorithm so time complexity for this one is going to be o of m times n where m is the number of rows and n is the number of columns and then space is also going to be of m times n where n is again the number of rows and n is the number of columns okay so firstly let's extract out the rows length and the columns length we're going to need two queues so we're going to have specific q which is going to be equal to an array and atlantic q which is also going to be equal to an array now we're going to loop through the entire board and push into the specific queue if the current value is touching the pacific and push into the atlantic queue if the current value is touching the atlantic so if i is equal to zero or j is equal to zero then we're bordering the pacific so we can push into the specific queue that position if i is equal to m minus one or j is equal to n minus one we're bordering the atlantic so we can push into that the position so now we need to carry out the bulk of the algorithm which is the bfs so we're going to create a function for this because we need to reuse it we're going to pass in q we need to state whether the value we're on is valid or we need to make that check so we're going to pass in x and y so the coordinates so if x is greater than or equal to zero and y is greater than or equal to zero and x is less than m and y is less than n therefore the position we're on is valid we're going to have directions or deltas in order to move to the next position so const directions and this is going to be equal to all the directions we can take and then we need to create our visited array which is going to be a 2d array where all values are initialized to false now we can start the breakfast search so while q dot length is available we can extract out x and y so we'll just do q dot shift we'll set that position in visited to true and then we need to loop through the directions right so let of directions so the directions array we created above is going to make sure we go up down left and right in our next positions so firstly we need to extract the next x which is going to be current x plus directions at zero so the zeroth position we need to extract out next y which is going to be y plus d at position one and then we need to check if that position is valid so next x next y and we also need to check if it's already within visited so if it's either invalid or it's being visited we can just continue and before we push the next positions into the queue for checking for bfs we need to check whether the height at the next position is greater than or equal to the height at the current position so f heights at next x next y is greater than or equal to height x y then we can push into q next x next y and then we need to return visited so visited is going to be the array that we created it's going to have all the true values for all the values that's a border in the pacific and it's also going to be another rate for all the values that's a border in the atlantic so let's extract those so pacific is equal to bfs we're going to pass in the pacific cue atlantic it's going to be bfs atlantic and then finally we need to populate a results array that match up the true values for both the pacific and atlantic so let x equal zero x is less than m so if specific at x y and atlantic at x y are both true and we've found a match we've found a position that can reach both the pacific and atlantic so we can push that into our results array and then we can just return result let's give that a go submit it and there you go
|
Pacific Atlantic Water Flow
|
pacific-atlantic-water-flow
|
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105`
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
| null |
153 |
hello to Ajay, yes, make pakodas from this mixture, want to try surgical strike in this respect net question, whose name is point minimum in rooted, sorted in chick, then in this question she will ask for free, if you know the search, then sodium, then in one lot, you will get this target. I know how to pause the element. Used oil sir. Okay, that will keep the time aside because by using it very sparingly, we are pushing the minimum limit of our rotator. Okay, so basically you should do it. I would like to tell you about my rhodium emolument and of course because it is a little more special in this channel, this sweater has been rotated a bit so we will not put lace on it, because of that we will get more time of Kamakhya, we will get time of oven while it is also very useful in logging in. If this can be done easily then we will be doing it while logged in. We will search for our element which should be done jointly. Let us try to catch that so basically this is your smallest element. Now look carefully how we can do it. If you see, I want to margin my gesture into 2 parts, this text, mind, this is basically what it was, so it was something like this and then a rotation of five was applied on it, due to which the people near the back got up and moved forward, right, it is strange. Now, if you cut the part coming in this state and let the unruly middle ones do Part 2, then what about me because the smallest element is stone, it is this element. You can stop the first part of Part 2 and start your searching like the first element of Part 2. This should be done daily, meaning I should breathe in such a way that it can take me closer to the first element of the parties every time, so that I can get my selection done, then this first element of part two will be the smallest element and the first element of part two will be named Murder. So there is another property which no other element has on this list and that property is that it is the only admin which is smaller than the one on its list and there is no other such element on its left. Look, the gun is small, every element of part one is from the one lying on its left, it will be a big one because Finn is injured, right, this is some part-1, it is Finn is injured, right, this is some part-1, it is Finn is injured, right, this is some part-1, it is sorted among itself and any element of part two is from the one lying on its left, now only for It will be big, only this first I will be left out. Okay, because from here, Part One and Two cigarettes are being made, so apart from the first limit of this Part Two, every person who is smoking in a minute is going to be big. Coincidence, this is just one thing. And that's because from the same butt, there is such a property that hot folds, the last element of part one, the last limited time only element of part one, which is increased by the value lying in its right, that every person has a younger yoga right career than his light one. We will keep these two things in mind whenever we get such an indication. Okay, if you are not in a relationship with your network, then you are the one at the parties. Yes, I am saying the right thing. Try to look carefully when I am approaching my Sachin. So you know, I approached this guy, after coming here, I saw him, tell me how you read, do you have any relation with the network, then I told him, look, I am a head younger than you on the left, so I can understand. That before Part-2, I will before Part-2, I will before Part-2, I will also Amazon you Limit Tum Vimarsh Original Style and in the same way, if I ever really approach this guy and see him, then this way I am fine with the flip guy, the face should have been bigger, but I am. I saw the relationship with the person on my right. When I saw this, I came to know that this person will have a relationship with the right person only. If he increases with his right, then whoever increases with the right is the last element of part one, so at this moment also you should see your part. The first element of two has been found, it is not here, this makes it a throat, right, because this is the last point of part one, okay and this point above is the starting point, okay, so in this video also you got the shift in your pot and we got our hydration. In Part-2, it is hydration. In Part-2, it is hydration. In Part-2, it is okay to move towards the setting element, so this will remain as it is, just a little bit about how we will be approaching the talent of our readers by doing something for this cotton, so here I have kept it. It is definitely a meat from India, okay, it is fine, so I came to know that first of all, I looked at the admit card to see if this is the first western reader element of Part One, then I am absolutely fine with the one on the left, then the one on the right. Have you decided with Wale that if you are not the last element of Part One or if you are sitting with such a new merit person then I understand that neither is this the youth to which we belong nor is this the last closing of Part One, this reader is the first closing. So we did not get to know anything from this, now we have done it, so no brother, sir, we will have to cut the channel, one partner, police. He thought carefully that I will see because you guys stay small, mid is different from Mirch and heg part is from both of them, the speaker is Dr. And what you are looking for is the last part of part one or the first part of part two, you will not find it in sodium, you will find it somewhere here, where this folded part is understood to be sent because you have to reach this point where part1 part2. Let's melt, you have to reach this point, otherwise you will get it in more diesel, so I said that they were saw, cut the goods, from low to deceased, if you are appointed, then you are not going to get this paste element of yours here, so let's go to the right side. After picking up people, you again expressed your mind on Amazon, your number five will appear on the media, you saw this guy, "Come on, tell me the chili flex you saw this guy, "Come on, tell me the chili flex you saw this guy, "Come on, tell me the chili flex relation" and said to him, "I am relation" and said to him, "I am relation" and said to him, "I am smaller than my next one, I loot means that the first limit of my reader is we." Found some element first limit of my reader is we." Found some element first limit of my reader is we." Found some element and we had hanged it. Okay, so we have to search in it, right now, let's try it once more on the example so that we can fully judge this time and we can write its secret properly. Here and you will get it removed for the first time, I will tell you this, I got it checked by the person on my left, whose lips should be bigger, I am bigger, now I got it checked immediately with my light bill, I said that the person on the right should tell me like this. That I am now bigger than the light one means that this is the last element of part one and if this is the last element of part one then it is the first limit of part two next to Justice, then return it to 100MB and chat with the one on the left too. You are doing it, set night fall, I am on two minutes, so I am doing it with minus one, I used to do it with Mit Laxman too, basically, if you are smaller than the one on the left, then you were at the limit before the parties and What happened here is that if you are bigger in Delhi than your right one, then you are the last element of the partner next to you and in the raw website, the first meaning of Jo Badhna Do Part Two, then like slogans, I saw the reader element and if it is not so. So we will use our Sachin towards the first limit of that part two in shop in short if I was given this from total then I saw that the garlic paste is sorted so here we will not get this prevent point of ours then it After cutting the sweater parts, I picked up the people and kept them on the minimum. Okay, so this is what has to be done, either you will get the element on the minute, work permit element which you are thinking of getting, if you do not get it then cut the parts of the sweater on the people or wear the brother-in-law after cutting the parts of the sweets. Decide wear the brother-in-law after cutting the parts of the sweets. Decide wear the brother-in-law after cutting the parts of the sweets. Decide which is sorted because the vitamin which you have to roast will not be found back in the sorted area, it should be found in the other direction, so once try to convert it into an angle, see if there will be some other tests which I will edit. Should be done then let's do it once okay see so actually apply water on it what will we do first people and make it as usual then blacksmith for yourself reload volume maximum time now till now about us what will we do First of all we will take out the plus bike okay now I will see I do it with I will see that first the limit subscribe for this if I came out bigger than this then first of all I said okay so if anyone in their right elements these bigger than the biggest like What I am talking about here is that if it is not the president's polish, it is the largest because it is the last part of part one, then the management of part one is just teaching it and if it is just about the relationship with the partner then part-2 is the relationship with the partner then part-2 is the relationship with the partner then part-2 is the beginning. The search must be beginning, so on this movement, I have got the first element of part 2 and daughter of butt plus one. Okay, so the makers are on the table on OLX. And if it is not so, then it means left to right, both are together inside in the right relation, then bye. Start Riya and go towards finding the first limit of your partner in another village, then I look at the soft area, whether from Lo to Deceased is appointed, if from No to Deceased 513 then we are not getting anything of ours here. The pluses are that go to the other side, you will get the sugar element. If now nothing is found in 813 disputed area from mitt to half cup, the other direction is coming in the other direction, that is, pick up the hike and keep it. Tweet - One who is on the left side. Tweet - One who is on the left side. Tweet - One who is on the left side. Okay, so this is our basic, we have written it a little thoughtfully, once we see that when you write a form like this, you are not setting submit, share many things, you check, melt minus one, you. Dead Laxman Without Even Setting Do madam minus one and maid to reduce or not? So whenever you fold in this way, you should definitely look at it from different angles, otherwise things get a little complicated. So, once we commit this crime quickly, we will see the arrangements on the pass. Okay, so first of all, this was our side example, let's see the ad on it that we should join hands by doing something else in this, so first of all, we can take only this much support that in your case, There must have been a challenge smallest element, then it is written below because the compiler did not use medicine, did not fill its return, canter from here Marais Ramesh returned when he has no problem, okay, so do a quick search and see, you Vishal Take it or keep it, yes, keep it here and remove the middle, if you change the left side, then it is basically bigger than the left, then there is no problem, and if you share it with your right side, then it is smaller than the left, there is no problem, you can share it with your Jio phone. Support is small, the deceased has been appointed from those people, you people picked it up and placed it on Mit Laxman, again your mind will be taken out on this Amla edit and if I could discuss it with my netizens, then look at this service, I will comment with my next one, my leftovers from me. It is big, it means that the first elements of part two which will return are off but I saw my voice element. Okay, yes, from this we have removed our voice element. Now let's search for an example of this method here and like this. In the example, the opposition respects the volume where there was rotation, but here there is zero rotation, so let's try it once and see that friend, if what I have was not roti at all, then would I have given the correct answer to you, just wait a minute. If we look at this, then assume that the dough is something like this. There is no profession in it at all. It means that it will either rotate from zero or multiple of a good collection of. Because if Shankari goes to the 108 names of reservation, then he saves them from back, right, they should be complete, they should ever see that you have taken it will work properly, I have kept it here, OK ji madam, it has been removed from the match, from the final act, from the side as well. I will decide on sorted English both potters hotels middemil cyber shot friends but because I first wrote this condition but people will be picked up and placed in the middle place ok again you took out the net then we understood that the media is also right and cut through the jungles Let me tell you guys to pick it up, friend, including now, you took it out again, so I came here, you will pick up the apartment till Abhinav Semi, you will keep it and at this time you put it, then you will come here you will take your chakra a little, we will be the others in this matter. After coming here, we will basically check it like if it doesn't work for a few minutes then subscribe, then if it is not needed then why is it difficult to put it and cut it, then I will give it here simply that if it is not looted at all then it means Complete is Total and Complete is Sorted, here you can find out that it is Zinc Vaibhav 5 Day Exam Voted To All, Will not vote for it at all. Okay, so here I also put a comment and write Add Not Protect Dual and if it is related. If it is not given then why not do it is simple, he used to give zero no return, because if Tej is absolutely quoted, then in this case, teach on the sentence in top-3, in this case, teach on the sentence in top-3, in this case, teach on the sentence in top-3, then we have done this condition very easily, so there is no need to be afraid of this. No, you can see a little more, how should we see? Okay, a little more, how should we see, it will always be fine. Okay, so an excuse, basically, let's take something like this, these were the facts, I will write it here for you, let's not take it till now. Yes, we are fine that 514 ESOL protective, so I should keep it like this 2345 That's what it means here, just look at it, the rotation of the whole end and minus one has been done, all the four elements at the back have been done, so in Part-2 only It is closed, if in Part-2 only It is closed, if in Part-2 only It is closed, if you want, in Part-1, it you want, in Part-1, it you want, in Part-1, it is mentioned at many such places, what will be fine, so let's see it quickly, so here, hi, I removed it, okay minute, I thought the rotis from you were in good condition, I cut the dry ginger and police. From Lo to the dead put the password on my lips mint Laxman's again I took out ok day friend I will save on the children like this because see I will bring this element with me off my net, this is not again a candidate relation but the one who But I had an affair with the right one because my right one is smaller than it, that means I am the last element of part one and my white one is the first element of part two, so I got this movement done by Yasmin, this work is so good. If you survive then this is the correct answer. Now just imagine the intensity would have been something like this 51234. What happens in such a situation? Okay, so here this time you took out and here the pain as if it does not go away on its own then you apply it on this or Then in the same way, you need this above because I have always been the right one, okay, if it is not a complete shoulder, computer operator, then I have done the next, there is no sweater of the next company, neither Mittu Laxman will always juice this. If he does it then it's okay then like so what will I do, I will write this condition above and we will settle it, otherwise we will run this case also, just what will I do, let's write this condition above and the condition to be checked mid-mind. above and the condition to be checked mid-mind. above and the condition to be checked mid-mind. Ok, so how will we be able to run our stuck tests with this, no one will be able to hear, ok, that's right, ok, so let's do the final one more time and see this, just like in the example now. Let's run it and see if you do it right then take 51234 here come here my first video chat with left to right element I saw medium in ok condition how to try to deposit then take limit cup There is no hot spot turn but this is a cupboard hotel so the vitamins I need will not be found in dry ginger so without raising the height I took it down to minus one. This time again I will get this element in my medical shop. After coming here I got the most. Hit the first six, compare it with the one on the right, then I will understand that it has increased from its light limit, what does it mean that this is the last element of Mitthu, it means as if it is on its side, it is the first element of Pathak and I have done the first line small ace limit tour, so our co is going well in the distance case. Okay, so now we have covered all our discs, let's do it once quickly and see, let's run it once and see. Okay, so. Let's see this by doing Ram Baran and that's why it is getting correct but let's see by submitting the final score, it's all going well, okay, as we discuss, okay, so the question basically was that if you meet your minimum. If you are standing at the minimum then check and compare it with your left or right side to see if there is any element in which you need to find it. Not only this, but Mother Pathak, the element is not available to you and if it is not found, then cut out one lesson and then part two. To get the first limit, you will have to go towards unfold diesel, then erase it from low or add chilli, it will be cooked, there will be a shot up button, cut the potter part plus, you keep doing that, send it to you, that element of yours should be visible, reader element. Poojana, if you like it then return it. Okay, I hope you would have liked its solution. Next question will be available in net speed. Ok ji bye. Jhal jhal.
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
559 |
hello so today we are doing this problem called maximum depth of an array tree and so the problem says we get in an array tree and we're going to find just the maximum depth so the maximum depth is the number of nodes along the longest path from the root down to the farthest leaf node and so for example in this 3re tree so it's not a binary tree it can be any number of child per node tree so for example here it's three child's at most three children at most per tree per node sorry and so here we should return three right and so let's see how can we solve this problem and so the first thing that we can think of is just like just go recursively and each time the children report their depth to a node we can just take the maximum because that's what we are interested in and so that would be pretty very straightforward so let's see how can we do that so we already have the node here given with the list of children and so what we can do it just into our base case and do our recurrence and then that's it and so what can be our base case so if we don't have a root then can just return 0 right also if we don't have children then we could just say if not so if the node is a leaf then the depth there is just 1 right so we can just return 1 and then after that so these are our base cases after that we need to do the recurrence and our recurrence would be just returned so we know we need to recurse on the depth here and so we know that if we are if we recurse like say on 3 the node 3 here we need to add 1 because that's another level or another level in the depth so you can just return 1 and then take the mass of the head start of the children so we can just go through max depth of children for the no tide right and so the note here is good that's older and yeah so that should be pretty much it and we return plus one so I've taken the max depth of each child and then we are taking the max we and then we are taking the max of all children for a node right so let's on this and see if it passes okay so it passes for that should be good that's right okay so that works and so let's see how can we can make this like a little bit shorter by doing the following and so we can like not have to do this if multiple times and so the way we can do that is just say okay but suppose we already have the logo passed to us and by default it's 1 so that the first call it gets to be 1 because that's one node right and then what we can do is just say okay return the max of basically route and so that if it's false we don't go to the list and then here it would be child still for this but the level since we are going one level deep it would be level plus 1 and then this stays the same and we will need to add the current level that we have that should be it yeah so maybe you are like wondering what is this route here that we are doing so let's just take an example and see what it looks like and so let's take an example here for this so if we say let's say we have a root that is equal to none so an empty thing right and so let's say your root and what right what would happen so you can see res is equal to so this is equal to none right so what if we have root that is like equal to some value or say two now if we do this you can see res is equal to one right so basically what it means is that if root is none then the third thing would be not if root is of some value than words on the list and so that means that here if root is like the node is like well at the end there is no node then we would return the whole thing would be none and so let's see what if when you do none plus three what happens so it says that there is nothing there right and so let's see let's take out root to being on here and then say root and one then the entire thing plus two we'll see what happens so we get none also right and so yeah so you get the idea it gets its returns nothing for the case where the know it's empty so let's try to submit this so yeah so you can see we have a problem here when we put little as the input because this here returns if we look at or its equal like it's equal to UM it's basically if you put this its true its equal to none so our max here doesn't want right and so we need to do something about that so max has this default value that we can say is equal to zero right so it still fills how about we say plots okay so it says that none type is not eatable which means that this none here is it's not it can it because match if you look at max accepts what it accepts an iterable and none is not an iterable and so the way we can fix that is to say so if we have like this and say or zero that means if the entire thing is none then return this right so if we have root here which is equal to none and then we say root or zero that means one root is where root is none it will get zero what if root is of value then in that case we'll get through right and so here to fix our problem here we can say or zero right and that way when I wonder when the notice is none we can return zero right away okay so yeah this is a useful trick to avoid the if and else so we had an if for root is none to return zero but instead we are doing and with the values and if the entire thing is none because root is none then we return to zero which is what you are returning earlier also if the children's are empty then we will get this entire thing is empty right and then when we get this entire thing as empty since we are adding the logo as a list we will get this one we will get the value 1 which is what who are returning earlier in our base case right and so yeah that's our submit this okay so that passes now we can also do another method which is iterative BFS iterative DFS so here we are doing kind of iterate DFS but in a recursive way so let's look into how we can implement it's ready place so of course to implement it rattling just we need a stack and so the first thing we need to delete this and we need our stack forgive us and we need to add our first node so if it's not empty then we can add to our stack root but one thing is we want the depth so we kind of want the value of the depth to be in our stack so that we can pop it and add to it right so what we are going to do is well stack so that first if the node is known from the start will not enter here right and so what will happen is we can do our stack and then we'll pop so we get a depth and then we get the node all right and so now we need to go through all the nodes children right and so if node and then we can say so if node we can have the depth is equal to so yeah so the thing is we need to return like the overall depth which starts out as zero so as for this just the counter and let's at the end what we are interested in is returning the depth and so now we need to check if we have a new better depth so we are going to say max actually depth here and then go in depth right and then we need to go through the children off of node right and we need to add them to the stack and so what is the current depth for this that's the depth of this the current note that who are investigating plus one because we are going from that node to the next level right and then we need to do no actually seat which is what's quality child to make it easier yeah and that will go ahead and go through the while loop again and if we added some values we'll go through it again right so let's run this and see what we get okay let's go to the previous case that we had okay seems like I lost it let's just submit okay so we have a problem with this case here was okay so seems like our depth here is Matt so I've taken the max of this current depth but then we are adding killing depth plus one okay let's just say if root so I'm saying if non root which means if basically I must let me discuss if I say you don't take what to none and then not root what does that return that's true because there it is none so I was going here only if root is none which is not what I want but I want is if root is equals one I want so now Roach is false I don't want that but root is equal to true and so that's actually what I want and so let's change that so if root we go the same thing if with if note here and so that passes actually who probably don't need even that if because we are checking here but plus submit this anyway so that passes now we can also do this solve this with BFS so basically BFS goes level by level and so we can just go all the way to all the bubbles and take the last one that we went at right just keep incrementing and taking the last level that we arrived at and so let's say how can we do that so welcome to have of course a queue but first let's just say if not good which means if our route is empty we need to return zero then we can have queue that starts out with the just with the root and we can say while Q so we can just get the length of the current level so does every time our queue will contain the counter level so for example the first time I told contain just one which is the current level after that it will contain three to four and so we want to get the length of the current level so let's call this length of Q so a little size and then we can go through this so or range zero actually just in range of local size so that we can go through every node in this level and look at the its children and so the way we are going to do that is we are going to take for example three look at that sword run take to look at that's at its children and for a mocha right so the way we are going to do that is what I'm say pop and then that way we will get the current node and then we'll add the charge so that can support shard in current that children we are going to add to the queue so append child and then so actually this is uh let's make this collection that so from collections we can say report so that we can get a cube and say let's do that we can also do like pub zero to imitate the queue but I just prefer using this so let's call this DQ and we can have Q dot append loops and child and then after that we can so since we process it this local one first and then process it this one is each time we process a level we are going to increase our depth by one then at the end where we can't that depth because we go through all the levels until there are no more of us with this whale queue and so at the end we'll have the last level okay yeah forgot to initialize depth so that passes for this one now let's try the node case just to make sure we didn't miss that case up again okay let's open this okay so pop left in order to get the leftmost value the first volume in the queue instead of the last one okay let's see at this case okay awesome aunt okay so that passes you could also use a list but at that point what you need to do is pop zero but that really like goes through the entire list to pub the first two pub there this element and so yeah that's also that also should work fine yeah and that's it for now see you next time bye
|
Maximum Depth of N-ary Tree
|
maximum-depth-of-n-ary-tree
|
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** 3
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** 5
**Constraints:**
* The total number of nodes is in the range `[0, 104]`.
* The depth of the n-ary tree is less than or equal to `1000`.
| null | null |
Easy
| null |
1,632 |
hey what is up guys welcome back to another leak code problem today we're doing polymer 1632 rank transform of a matrix before i begin yeah come on man um thanks hey what is up guys welcome back to another league called problem today we're doing number 1632 ranked transform of a matrix given an n by n matrix return a new matrix answer where answer row column is the rank of matrix row call the rank is an integer that represents how large an element is compared to other elements okay it is calculated using the following rules if an element is the smallest element in this row and column then this rank is one okay so we start our rank at one basically if two elements p and q are in the same row or column then if p is less than q then rank p is less than right q if p is equal to q then rank p is equal to the rank of q if p is greater than q then rank p is greater than rank q basically um if one number is greater than other then its rank is higher if they're equal and they're equal it is guaranteed the answer is unique under the given rules okay so basically uh the problem that we're giving and the rules that we're given the answer should be unique we shouldn't need to worry about that okay now so here we have this example we have a matrix one two three four this the matrix one two three four now the rank we get is basically we find the smallest number in the entire matrix if you notice and the rank over here is one and then uh in this row right let's just look at this row then the next rank a two why because two is greater than one and if p is greater than q and they're in the same row or column and in this case they're in the same row then the rank of um p would be greater than the rank of q if p is greater than q and in this case it is so two negative two is greater than 1 and then we come over here and then you'll see over here 3 is greater than 1 so it's rank is higher and then 4 is greater than 3 so his rank is also higher than 2 so 3 um this would have a rank of three uh because it's greater than uh three over here which already was set to a rank of two okay so we know order somehow matters here we don't want to start at a random number we don't wanna start a random column or row start processing that because we get the wrong answers because let's say we just started looking at a four or let's say we start looking at three and we assign three a value of one for some random reason i don't know why you would do that and then you would come over here and then you look at four and then um you would give for a rank of two but then you would come back to one and then you see you'd have to start at zero because it's less than three which has a rank of one so you would have to start at zero but you can't because you have to start at one okay so how are we going to process this well if you were doing this problem you kind of noticed that you would just somehow start processing smaller numbers first and then larger numbers in ascending order i kind of wrote down over here what i'm going to talk about because it makes my life easier and it helps me explain a little better so that's that we need this tomorrow start from small numbers if you look over here if you look at all the problem examples you'll notice that the smaller numbers are the smallest number always starts with one so negative 47 is one smallest number here is one so you'll see a one over here and then we kind of go up in order right and the larger the number is usually the larger rank it has so like nine is the largest number here it has um the highest rank okay um not usually i guess it always will be so intuitively okay maybe we start sorry processing small numbers first and then large numbers in ascending order okay now how are we going to do that how are we going to start processing the smaller numbers well we can easily group the numbers by iterating through the matrix so we go through the entire matrix and then we use a hash map to add each point to a bucket of that value meaning we go through all these numbers and we can start grouping them and we use a map to do that so all the 20s will be mapped to one bucket or one list in this case we'll map a key to a list pair so um all the 20s will be mapped to one of uh bucket in the hatch map all the fours will map to one although negative twenty one's going out to a one i won't even really see a bucket but i guess one value okay so all the fours will be mapped to one value um so this four and this four will be mapped to the same number four so that's how we can group it's pretty easy to group i'm pretty sure everyone can figure that part out and then the next thing is how are we going to sort it because we know now we want to start processing the smaller numbers and the larger numbers um we can maybe sort the hashmap later down the line or can you just use java as a really nice map class called tree map and what tree map does is it sorts the elements by keys which is exactly what we want to do because keys are our values and we want to sort the elements in val of our values in ascending order so instead we could use a tree map so now what we have so far is we have we've grouped all the elements by their same value and we have them sorted so the next step is this okay we know uh just kind of thinking about we're just going through this okay i'm supposed to smaller numbers then the larger numbers i got them grouped up i got them sorted now what okay now i gotta obviously i gotta start assigning ranks now how do i start assigning a ranks down to five percent great i want nine percent i got some time so i gotta start reciting ranks how do i start sending ranks okay i know i need to start let's look back at the problem definition i know that the smallest one in the row and column will start at one and then i need to go through everything and i need to check if something is in the same order column then i need to start assigning based on that so we started the smallest one a one and then we move up from there depending on whether elements are in the same row or in column and we can start deciding from there okay so the way we're going to approach this is this we're going to go through all the groups of values meaning all these uh all the values in the um tree map we're going to go through all the values in the tree map and for each group we're going to see which of these elements are connected and how are we going to see if they are connected meaning if they have the same row or column okay if they have the same row or column and then we're going to check all this stuff so we're going to check if they're the same actually what am i saying so we're going to check that they're the same row column and why is that's because if they're the same row or column and the numbers and values are equal then they should have the same rank right and that's part of the problem addition definition if they have the same row or column and the numbers are equal then they should all have the same rank so that means we need to find all the groups of same rows and columns that are somehow interconnected okay because you have a row here then a column sticking out from and then from this sorry a column here and then a row here and this row will be connected to another column where just somehow all these ones are connected because they have the same value so once again for each group we're going to see which elements are connected meaning they have the same or column and that's because if they have the same row column and the numbers in the or the values whatever you want to call it are equal then they should based on the problem definition have the same rank that's one thing we need to keep in mind okay so what we're going to do now is we're going to find this group of connected row and columns we're going to use union and find to figure that out and we're going to get that connected set okay so for this connected set of all the numbers that are equal and all the numbers have the same lower column we're going to find this rank right because they will all have the same rank now how do we find the rank of this well we got to think about it like this so we know that if connected set only had one item i just had one element then what's the rank well we have our problem definition well the rank would be um the um based on this right these requirements that we're given is going to either be 1 or is going to be we're going to find the maximum rank in that element's row and that elements column maximum element rank in the elements row and column and we're going to just add one to it and assign the rank there right because look in this example four really basic example four and we're going in order so we already processed the smaller ranks first right we're going in order of ranks so we really process the smaller ranks first and now we're up to three and so one was assigned two was assigned to assign right where processing is number four okay this group four now so um i look over here i look at four's row and i look sorry fourth row i'm going that way and fourth column and i find the maximum rank that was already set for the row and the column all together so i see over here the maximum over here is two and then over here is two as well okay great so my maximum previous one is two and i just add one to it which will make it three okay that means i know my rank here is three so well let's say that connector set just had one element and the rank would be the maximum either one plus the rows already maximum rank or one plus the column's already a maximum rank and we get the maximum of these two right and but if the connector has more than one row column now this is where we need to think about it and we get the maximum of all of these for all the elements okay so it's maximum all the rows and all the columns that this connector set is a part of and that would be plus one that would be the columns rank would be the new uh rank of that point okay and then we just need to keep track of the maximum ranks so we know now because of this we need to keep track of the maximum ranks for each row in each column and we use a hash map to figure that out or just kind of uh another matrix i guess another 2d matrix but in this case i think a hash map is a little easier yeah it's definitely easier so also we can use union find to help build this connected set because what else is union 5 called it's called the destroying set so now let's just go to the problem so um we're going to set the row length column length and our answer and then we're going to create the tree map as we talked about in some of the earlier steps and we're going to go through the matrix and we're going to add elements to the tree map okay we're going to throw all the roles all the columns we're going to grab the element we're going to check if there's uh we're going to get the value and we're going to check if the value element is basically a value if the value is null meaning we don't have an array set over there a value set for that key which is element then we just create one and we add our current point in there this is our current point we just add our current point in there then what we do here is we initialize the next rank for rows and x ranks columns this is basically the maximum that we talked about over here we need to keep checking the maximum ranks for each row and for each column and this would do that remember we're starting at one so what i do is for all the rows i start at one and for the columns i start at one it's basically a mapping of the intege of the for the rows basically i'm mapping up the that row for that um that rows uh maximum sorry that was so for row x next rank for row x is the next rank and for column x next rank for columns at x is the next rank great sorry next one plus one i guess you could say is the next rank well actually no that's not plus one i know we did so um then you can go through now we're gonna go through this and we're gonna um basically do the problem we're gonna start um grouping the values together okay so we're gonna go through all our key set okay and basically we're gonna go through all this tree map and what is a tree map remember each cream map is a group of all the values that are the same okay so all the fours all the ones all the twos all the threes all the sevens whatever you want to call them so we get the list of all equal numbers or the equal points okay i'm gonna say the equal numbers uh points of equal numbers whatever this little this is a list size um i guess you could call this s whatever and here's where we do the union find okay this is a really basic union fine destroying sets um if you don't know about unified destroying sets i highly recommend learning about them before you come to this uh problem because you won't understand this um like i always say go to william facette he has three really good videos i'm joined on destroying sets in union fines one is like explaining what it is one is um the code for and one is like i think it's a path compression for that i'm not even sure but he has really three really good videos if you watch those you'll completely understand it not completely i mean completely but you won't you have excellence in it i mean i don't even have excellence in it but those three videos helped me a lot so we're going to create um the way we do this just really quickly is we have a parent array and we split up um all the elements into their own like components where a component is um first each element is basically an index at that array and each component is basically if you go through all the parents uh really once again you have to go through the unified also make sense but um uh each component is a set of elements in which um each index at that element points continuously back to that parent recursively all the way back to its parent i don't know if that made sense i can't explain it right here but this is union five this is our union find array if you know about universe is basically basic uh each number is its own component so it's parent is itself and now we have to do is we have to start uh making unions we have to start combining uh all these elements to form our disjoint sets or our connected components or disconnected components i'm missing our components we now compare each component with all the others and you need them depending this is a simple 2d array to compare each element with another and then we grab the um the first array the second array and we check if they are the same rower column in this case if they have the same row or if they have the same column then obviously they're part of that same connected set that we talked about all the way up here they're part of that same connected set and if they are part of that same connected set then we where am i want to partner then we um union them and union is really simple if you look over here um if you know about union finance trust me watch those videos this will make sense like this so i won't really go into this right now so we um you can look at it's really simple no watch the videos that you can find i don't know what i'm saying if you don't know my union finds watch the videos this will make sense then you create a union of them then once we have our unions which units group of connected rows columns we're going to place them all together into a list so it's easier to go through and this is what it is this is our hashmap this is our the where we're integer right here where the key is basically the parent of that union um so it represents that union that disjoint set and it pairs it maps to a list of all the elements inside that disjoint set so these are all our unions and what we do here is we go through all um our elements once again hey sorry about that my microphone died so the audio here is going to be bad for the rest of this video but we're almost done so i'm just going to keep going also died so anyways we go through all the elements in the um the set and we find the parent of this union okay meaning that the component is a part of and then what we do is we check if it's null then we just add a new array over here and we go we um add it to the union list okay this way we can group all our elements in the union together so they're easier to just iterate so this now has um all the lists of our unions okay after this line runs and then we go through all the list of our unions okay all the unions that key set this is the union parent and we find that we get the union list the max will basically be the rank we assign to this union list and this is where we're going to do these final few steps okay and what we do now is go through all the elements in this unit and find the maximum rank of the rows and columns hatch for each element as we talked about so with what this is doing is we're getting the rank right this is what this is doing right here so for this unit element zero that's going to give you the row right that's going to give you the row that this up point is at this element is at in this human element in this union is at it'll give you the row and for this row we need to find the maximum rank or the next rank that's going to be there okay the next rank that's going to be remember the next ranks they always start at one because we put over here they always start at one so find the next rank for the row find the next rank for the column and what we do is we grab the maximum of them as we talked about as well as the maximum of the previous um uh point because remember if we have a destroying set of connected rows and columns you know we need to find the maximum row and column considering all the points maximum of all the rows in all the columns that are part of that union set okay and if it was just one then we just do that one row and column but if it's multiple then we have to check and count for all of them and that's what this is doing this will account for all of them if they're multiple emphasis one this loop will just iterate once and i'll just give you the maximum of that row and column so once we get all that then we now we have our answer so now for all these connected components for this entire union right for this all this connected set they'll all have the same rank and that will be the rank basically maximum right so we go through all the elements in the next union list grab the x value grab the y value set answer at that x and add y to the maximum we do that for each of those points and what we do now is we reset the next rank for the rows so the next time this comes around this will be properly set these will be properly set so for this x we for this row i guess for this row the next rank will be the current maximum that we just found plus one and for this y value the next round we found would be this maximum plus one why for why max remember because we just put a point our maximum at this point right now so it affects the maximum at this entire row and this entire column okay and we just keep doing that so that will give you the answer um and then you just finally return it that is solution of this problem thank you guys for watching i'll on this video right now right here and if you guys haven't subscribed if you guys haven't already please subscribe and leave a like if you can thank you so much
|
Rank Transform of a Matrix
|
number-of-good-ways-to-split-a-string
|
Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
* If two elements `p` and `q` are in the **same row or column**, then:
* If `p < q` then `rank(p) < rank(q)`
* If `p == q` then `rank(p) == rank(q)`
* If `p > q` then `rank(p) > rank(q)`
* The **rank** should be as **small** as possible.
The test cases are generated so that `answer` is unique under the given rules.
**Example 1:**
**Input:** matrix = \[\[1,2\],\[3,4\]\]
**Output:** \[\[1,2\],\[2,3\]\]
**Explanation:**
The rank of matrix\[0\]\[0\] is 1 because it is the smallest integer in its row and column.
The rank of matrix\[0\]\[1\] is 2 because matrix\[0\]\[1\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[0\] is 2 because matrix\[1\]\[0\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[1\] is 3 because matrix\[1\]\[1\] > matrix\[0\]\[1\], matrix\[1\]\[1\] > matrix\[1\]\[0\], and both matrix\[0\]\[1\] and matrix\[1\]\[0\] are rank 2.
**Example 2:**
**Input:** matrix = \[\[7,7\],\[7,7\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Example 3:**
**Input:** matrix = \[\[20,-21,14\],\[-19,4,19\],\[22,-47,24\],\[-19,4,19\]\]
**Output:** \[\[4,2,3\],\[1,3,4\],\[5,1,6\],\[1,3,4\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 500`
* `-109 <= matrix[row][col] <= 109`
|
Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index.
|
String,Dynamic Programming,Bit Manipulation
|
Medium
| null |
485 |
what's up everybody elto majin here and welcome back to yet another youtube video in today's video we'll be solving another easy lead code problem number 485 also called as max consecutive ones it is also the first problem of arrays 101 card of explorer fleet code and it has also been asked in amazon microsoft and google so without further ado let's get started the problem states that we are given a binary array nums and we need to return the maximum number of consecutive ones in that array nums so for example if we take a look at the examples that we are given uh we are given first nums and initially we have two consecutive ones and then we have three consecutive ones so maximum of them would be three so we return three similarly in the second example we have one then we have two consecutive ones and then we have one consecutive one so maximum would be two so we return true okay now let's try to understand what is the solution what we are trying to do is we are creating two variables which would first would basically be our answer and i will call it as max once uh and i'll initially set it to be zero because initially we are not sure that or if even if there would be at least one so which is why initially we are setting max one to be zero next we are taking current once uh which would basically be the last consecutive set of ones and what is its size okay that would be the current ones now what i'm trying to do is i'm iterating through the complete nums uh array from zero to nums dot size and at every step what we are doing is if we are checking that particular element of that array is equal to one i am checking it to be one because we need to count conjugative ones okay if that is the case then i'm incrementing the current once that is the last group of ones that we have found and after incrementing that we are moving ahead now the second case is that we do not encounter one we encounter zero okay so once we encounter zero what that means is that we have just ended the streak of one okay now there are no more consecutive funds so we need to refresh and add the manipulations to our max ones okay so that is what we are doing now what we what i'm trying to do is i'm just checking if max once is less than current ones we need to find maximum number of consecutive ones right so if our max ones that is our answer is less than the current ones that means that we have found one more streak or one more group which has more number of ones so that is why i am setting max one to be current one after that after doing checking for the manipulation i am just resetting the last group that is current wants to be zero that's the most of the solution now for this there is one more exit case that we need to consider for example in this when you exit out of this we have at last one okay so we would just be incrementing current once but not checking if that final case is included okay so that is what we are doing we are just checking if current ones is not equal to zero that means we have exited from the last element to be one and then finally we are checking the main condition that is max one is less than current once if that is the case we are just setting it to max ones and we are just returning and that's it that's the solution we are doing one iteration through the complete array so the time complexity would be often and we are not using any extra space we are just using two variables so space complexity would be of one so that's all for this video guys if you like the video hit the thumbs up button uh if you need more such content subscribe to the channel to get up to keep updated for the future videos join the discord server and i'll see you in the next one
|
Max Consecutive Ones
|
max-consecutive-ones
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
|
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
|
Array
|
Easy
|
487,1046,1542,1999
|
1,710 |
hello coders welcome back to my channel of lead code problem 1710 maximum units on a truck here we are assigned to put some amount of boxes on the truck and we are given 2d array like we are given with number of boxes and number of units per box and what we have to do is we have to return the maximum of total units that can be put on the truck okay and we are also given with the truck size like we have the upper limit set here you can see we are given with uh this uh array 2d array and the truck size 4 we have to arrange or we have to load the boxes onto the truck so that it can be the maximum under the limit of four like we can put one boxes uh one box and then second two then third but two one three but we can put only four boxes there so the maximum unit can be one into three two cross two and one cross one that is eight let's see the example and the solution in java is the greedy solution basically we are sorting the array based on the number of units box type based on the number of units because we have to maximize the number of units that can be loaded on the truck with the given truck size then what we have done we have taken the result and we are looping through the box type sorted box array and we are checking like if the truck size is uh we are comparing the box size with the truck size like number of boxes with the truck size and if it is minimum then we are updating the current and we are multiplying with the number of units that can be loaded around that truck then we are decreasing the truck size and we are doing the same for all the box type until the truck side is zero then if it is zero then we are returning the result and that will be the answer let me walk through dry run through the code like what we are given with this array with the number of boxes and the number of units per boxes and we have sorted this based on the index like size of the number of units like 10 9 7 5 then we are looking through the this array and we are checking like if box 0 that is 5 is less than the truck size 10 yes it is there then the current will be 5 then we will multiply 5 with the number of units like 5 into 10 and result will be updated to 50 and truck size we will decrease with the 5 because uh box 0 is 5 then we look through the second time at same condition we will check like box 0 is less than truck size okay then current will be 3 then 3 into 9 will be 27 we will add 50 plus 27 equal to 77 will be the result and truck size will decrease to 2 in the loop 3 now the box 0 that is 4 is greater than truck size so we will take the current equal to the truck size that is 2 and 2 into 7 that is 14 will be added to the result and now to oxide will be zero and the nitrous side is zero we will result the result that is 91 and we will exit through the function this is the complete solution if you like this video please hit the like button subscribe to the channel and press the bell icon thanks
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
657 |
welcome back to Algiers today's question is leak code 657 robot return to origin so there is a robot starting at position zero the origin on a 2d plane given a sequence of its moves judge if the robot ends up at zero after it completes its moves you're given a string moves that represents the move sequence of the robot where moves I represent the if move valid moves are right left up and down return true if the robot Returns the origin after it finishes all of its moves otherwise return false so the way that the robot is facing is irrelevant great so we start off at zero for our moves we can go up down left and right and this is on a 2d plane so here we have a 2d plane our friend starts at zero and we can go up down left right now if we go up on a 2d plane what does that resemble well that resembles going up on the y-axis so that's going to be y plus the y-axis so that's going to be y plus the y-axis so that's going to be y plus going down is going to be going down on the y-axis so it's going to be y down on the y-axis so it's going to be y down on the y-axis so it's going to be y minus left is the x-axis so it's minus left is the x-axis so it's minus left is the x-axis so it's going to be x minus and right is going to be X plus so what does this bit of code right here looks like it looks very similar to a switch statement which is exactly what we're going to use for this solution so we have the starting positions of X and Y which we've mapped to digits yeah we're going to Loop through the move so we have up down left and for each move we have a case so we have case up case down case left case right followed by the operation to carry out if that case is hit then once we've carried out all the moves within the examples we just need to return whether X is equal to zero and Y is equal to zero so let's run through the first example we go up by one so we check our switch statement up means incrementing y by one so our friend moves to here then we go down by one so we look at the switch statement it means the y-axis has to be it means the y-axis has to be it means the y-axis has to be decremented so this goes back to here are we at position zero yes so this is going to return true now let's look at the second example so our friend starts here we have left so we check the switch statement left means decrementing the x value so our friend moved here then we move along we have another left so we decrement X again so we move it across to here now we've covered all move we check if this position is equal to zero well no it's not so we can return false here so this algorithm is going to be running in on time complexity where n is the length of the string moves and then space is going to be constant so let's code this out X is initially set to zero Y is initially set to zero we're going to Loop through move of moves and then we're going to implement the switch statement so switch we're going to pass in move and we're going to have four different cases so we're going to have case U is going to be incrementing the Y then we have to add a break case r is going to be incrementing the x-axis is going to be incrementing the x-axis is going to be incrementing the x-axis right case D is going to be decrementing the Y and case L is going to be decremented the X finally we need to make the check whether X and Y equals 0 and return that so return x equal to zero and y equal to zero let's give this a run submit it and there you go
|
Robot Return to Origin
|
robot-return-to-origin
|
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.
You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its `ith` move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down).
Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_.
**Note**: The way that the robot is "facing " is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
**Example 1:**
**Input:** moves = "UD "
**Output:** true
**Explanation**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
**Example 2:**
**Input:** moves = "LL "
**Output:** false
**Explanation**: The robot moves left twice. It ends up two "moves " to the left of the origin. We return false because it is not at the origin at the end of its moves.
**Constraints:**
* `1 <= moves.length <= 2 * 104`
* `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.
| null |
String,Simulation
|
Easy
|
547,2239
|
191 |
200 Hello friends Blind 75th let's move forward to a new day and today our 4138 is number one white so let's move on to it so the question is quick and for this let me tell you in advance that if you have not seen Defty that is the reverse beat of 175 I have not seen it because I have a belt in it, I have problems etc. Meena, go and see a bus because even though this question is there, you will understand it quickly, so in this question say that the teacher has given you a sign in, tell you how many buses. So there are so many zeros in this and this can happen here, you are seeing this, so let me do it for a few more days. Now look at example 2, here from so many zeros, if I go somewhere and stop one, then the output will be as many as mentioned above and will be broken. Okay, so before there are two ways of doing it, rather they understand about that method, after that they look at the light, there are actually two tricks in it, so now let us discuss the treatment, okay, you like, this is ours from the lift. The key is of 32bit and is unsigned, so what do we have to check to find out the number one of the first toe fall, how many are visible here as free. Okay, if we know how, then for ultimate, we will have to end with one, is n't that why? What was I? The previous video was A Day for Diwali. Okay, so what will we do? You are late to the office. Whatever is the end of these two, we end with zero with anyone. Whatever comes, we will have to deal with the last digit. If it has happened last, then there will be benefit, then it will definitely happen, so ultimately we are ladylike, so what will we do, whatever N is, we will add it to one, then we will know the last date, what will we do after that shift? We will do it, we will keep writing the right side, okay, it is a simple thing, if zero comes, then it will become zero and if we add it, then it will start, it is like Kaladhaan, okay, what is the method of ending, we can message that we have like or 1013 of acid. If we turn it off in other modes, then you know, we create a reminder, if zero comes, then why will the reminder come here, if the reminder is for some part, then what is the reminder for this, then we can know by adding it. Is this a method or not? One method is that as soon as the digit is known, after displaying the digit, we will whiten Malviya's answer plus equal to 2 in the answer and whatever reminder is there, everything comes to the fore, it is just a small amount of work, ultimately if we add Yudhishthir, then It will not make any difference but it is a little difficult to get hold of the country from us because you do not understand, meaning if we say how to know in which way, then the question arises, how do I know that this is the answer, is it correct, then agree. Well, after doing this, we will know that there are so many zeros. Okay, this center will be needed because see, every day we can do something like zero, because what is happening here, let us check this gang everywhere, then this one, every We are having a video chat that we can add that we have to look at the chain, just hold one, so yes, we can do that, so who says get N and minus one added, okay now its - that. What should we okay now its - that. What should we okay now its - that. What should we do and if it is ours then what will be the amendment of zero in the last, now these two will do and get it done that what happened to storm and zero can, zero is gone and this holy will remain holy, this is the right thing, now what will we do from this - this is the right thing, now what will we do from this - this is the right thing, now what will we do from this - Meaning When Ansari is not zero in the last, till then we from which - kar we mean - is we from which - kar we mean - is we from which - kar we mean - is neither one - k n then it has become - their will be now neither one - k n then it has become - their will be now neither one - k n then it has become - their will be now here everything is zero, we will make vegetables, won't we join Abhinandan ? This one is finished with digestive tax and you know ? This one is finished with digestive tax and you know ? This one is finished with digestive tax and you know what is the end of 180. It is going to be 2030. If all the zeros come then how many times did we have to do it. This is twice, isn't this procedure? It was done once here. So this means that our output is done, so this is one and two, this is how it is made, this is how the trick works, one and wearable discus, then look at track one, so I told you what we should have done and models two. If you want to do it then add whatever reminder is there and keep doing night shift, it is okay that TV, I told you in the office Lado when we used to reverse the final, how it is tight, it is on the left, it is of the other one that we What will we do to give them an end, leave from now do and minus one or take chocolate like this, it's a matter, do an end and do it and like this dip Ireland i.e. until God this dip Ireland i.e. until God this dip Ireland i.e. until God happens, all the value of Grand Cherokee is all the answer then this look is over It will be done and our answer will be added in such a way that the answer is equal to one, these are two ways, both are fine, okay, so I have submitted it in front of you and can show it again if anyone wants to see the deficiency etc. No, why not Ajay, so this is our track-2, the answer that came was add so this is our track-2, the answer that came was add so this is our track-2, the answer that came was add ok, if I remove it, please, there is not much difference, a similar, almost just a new way of looking at things, this was the path question and if so, I If you understand and like it then please like it and Gautam Line 65 because you are learning a lot of new things with me, so please support by commenting. In the next video, you will see how that is.
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
1,317 |
hey how's it going today we are going to go over the convert integer to the sum of two non-zero integers question in of two non-zero integers question in of two non-zero integers question in python it's given integer and non-zero python it's given integer and non-zero python it's given integer and non-zero integer is a positive integer which doesn't contain any zero in its decimal representation return list of two integers a b where a and b are non-zero integers a plus b and b are non-zero integers a plus b and b are non-zero integers a plus b equals n is guaranteed that there is at least one valid solution if there are many valid solutions you can return any of them so if your input is 2 the output is 1 um because both 1 and 1 are non zeros if your input is 11 you can output 2 9 you can't you cannot output one time because for 10 there is zero in the number 10 right um and for 10 000 your one of your output can be 100 9 99 because both of these numbers do not contain any zeros and so on so forth well um the question should be fairly straightforward because um basically you can like um for your a's you can um go from one and just to check whether and minus your a is like a zero um integer or non-zero integer and zero um integer or non-zero integer and zero um integer or non-zero integer and if both of them are non-zero integers if both of them are non-zero integers if both of them are non-zero integers you can just return them right so for that we can write a for loop um so for i in range and we are now checking if um it's a zero integer or not oh it's not in um i or not in um m minus i if it's if both of them are non-zero if it's if both of them are non-zero if it's if both of them are non-zero integers we'll just return them as a list
|
Convert Integer to the Sum of Two No-Zero Integers
|
monthly-transactions-i
|
**No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.
**Example 1:**
**Input:** n = 2
**Output:** \[1,1\]
**Explanation:** Let a = 1 and b = 1.
Both a and b are no-zero integers, and a + b = 2 = n.
**Example 2:**
**Input:** n = 11
**Output:** \[2,9\]
**Explanation:** Let a = 2 and b = 9.
Both a and b are no-zero integers, and a + b = 9 = n.
Note that there are other valid answers as \[8, 3\] that can be accepted.
**Constraints:**
* `2 <= n <= 104`
| null |
Database
|
Medium
|
1328
|
328 |
hi everyone I'm here to solve leeco problem number 328 odd even link list let's read the problem given the head of a singly linked list group all the nodes with odd indices together followed by the nodes with even indices and return the reordered list the first node is considered odd and the second node is even and so on note that the relative order inside both the even and odd groups should remain as it was in the input you must solve the problem in O of one extra space complexity in O of n time complexity okay let's take a look at what's going on in this problem so it's it tells you in the problem statement right away that the first node is considered odd and the second node is considered even so all the odd nodes are if R are one three five and the even ones are two four and then once you construct a new linked list all the odd ones are grouped together first followed by the even ones one three five two four let's take a look at this example right the odd nodes are two three six seven and the even ones are one five four so in the end you get two three six seven one five four okay this problem visually speaking understanding the problem is not hard but this can be a little bit intimidating in the beginning once you look at the problem but it's not a hard problem you know basic the basic idea is that you go through the you have a head pointer that points right here you set another head pointer that points to the start of the even nodes and then you use an odd and even pointer to go through the linked list and construct a list with only the odd nodes another list with only the even nodes and then you join the two linked lists together into one and that is the answer so it's not a hard problem let's do it and by the way the algorithm I'm about to demonstrate I want to give credits to Nick white from YouTube um great Channel um this I'm learning from him so this algorithm is mostly due to his genius and his um thought and care so thank you Nick take a look at the constraints the number of nodes in the linked list is in the range 0 to 10 to the fourth so you know that the number of nodes in the linked list that you're given could be as could be nothing or it could be the number of nodes could reach as high as 10 to the fourth right and so because we it's possible that we're given an empty linked list this is a case that we have to treat this special case okay and minus 10 to the sixth is less than or equal to node dot val Which is less than or equal to 10 to the sixth basically the values themselves can range they have a pretty extreme range they can go from anywhere from negative 10 to the six on the low side and on the high side they can be as big as 10 to the six and this constraint is not as important as this one the first one because we really need to treat this special case right here this topic is linked list it's definitely a linkless problem and it's been a very long time since I've done a linked list problem and so this is a good practice problem so let's take a look at the approach treat I think that's how you throw a treat right let me just take a look free yeah that's how you spell tree sorry uh had like a brain malfunction right there so treat the special case where you are given an empty linked list be fine pointers odd even and even head and assign them to the right values so this is what I was talking about we're going to have an odd and an even pointer to do the work and then we already have the head pointer that's pointing to the start of our given linked list so the head pointer automatically is the head of the star of the linked list I will hold the odd all the odd notes and we haven't even had that will point to the start starting node that will chain together all the even nodes in the linked list do a while Loop as long as even and even dot next does not equal none update the nodes in the following order odd dot next odd even.next odd dot next odd even.next odd dot next odd even.next even set join the two join the even the odd and even link lists assign odd dot next to even head right because the odd after you do the while loop the odd.next is going to be pointing to the odd.next is going to be pointing to the odd.next is going to be pointing to the last node in the odd in the linked list that consists of only odd nodes and then you join it to the even head which we set as a placeholder to construct the final linked list that we return head okay let's get started treat this special case right if head equals none return none Define pointers odd even head right so odd equals head even equals head Dot next and then even head equals eve even right okay so then do a while loop has lines even and even dot next is not equal to none while e does not equal none and E dot X does not equal none now you update it in the following order odd dot next odd even dot next even right odd.next equals even dot next odd.next equals even dot next odd.next equals even dot next odd equals odd dot next even dot next equals odd dot next and then even equals even Dot dot next this is beautiful in the sense that you can use the properties of symmetry to figure this out but if you drew a piece of if you have a piece of paper and you drew out these pointers it would make perfect sense uh so the Symmetry is that you first do odd.nex which equals even dot next then odd.nex which equals even dot next then odd.nex which equals even dot next then you do odd equals odd.next right this you do odd equals odd.next right this you do odd equals odd.next right this the second line is set to the value that you defined in the first line and basically on the even side you do the same thing you just flip it even dot next equals odd next even equals even Dot next right so that's beautiful um so then you have do odd dot next equals Eve e head okay actually I'm gonna I did I named them o e o e o dot next equals e dot head and then return head let's take a look okay very good let's try one more and actually before I try one more time of course we know that the TC time complexities o of N and the space complexity is of course all of one right so let me this got a 66.20 this got a 66.20 this got a 66.20 percent in terms of run time and time complexity and 91.61 in terms of memory let's just try 91.61 in terms of memory let's just try 91.61 in terms of memory let's just try one more time this can be a little funky depending on how you run it now it's 76 and now it's 91 whatever but overall this is a good problem it's not hard but it does it can be a bit intimidating when you first read the problem I certainly was but once you understand how it works it's really not hard and so you just have to keep practicing and you get better over time the more you practice so thank you very much and I'll see you at the next one
|
Odd Even Linked List
|
odd-even-linked-list
|
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106`
| null |
Linked List
|
Medium
|
725
|
101 |
in this video we're going to take a look at a lethal problem called symmetric tree so given a binary tree so check whether it's a mirror of itself so symmetric around the center so for example this binary tree we have something like this and then we want to see if it's symmetric what we're going to do is we're going to put a line between here you can see that this is symmetric um you can see that uh all these values are basically um mirror of each other right so in this case they're all symmetric then in this case we're just going to return true right because we're returning boolean so if we have a situation like this you can see that it's not symmetric and if i draw a line here you can see that this is not if this is not a reflection of this right so in this case we can just return false so to solve this problem i think one thing that we can clarify when we if we were to give this question an interview is that if null is symmetric if it is in this case it is um so null is symmetric but there could be also a situation where there's only one node in the tree and that's also symmetric as well so now we know the base case let's talk about how can we solve this problem how can we know if this tree is symmetric well let's say we have given a thing like this okay how do we know if this is symmetric well what we can do is we can compare its children to see if they are equal value right because we know that this is symmetric if we were to only giving if we were only given one node then this one node is symmetric but we don't have to compare the para node because there's nothing no one to compare to right so in this case this is symmetric but what we have to do is we just have to compare the children node child node the left child and the right child see if there is equal value in this case their equal value then um this is symmetric right and if we were to given something like this one two and zero for example this is not symmetric because those two values are not the same so that's one example the other example would be something like this where okay so we have these two the level one level two they're symmetric but what about level three so how can we know this is symmetric what we can do is we can compare the left child so the roots left child's left child with roots right child's right child so in this case we're comparing to see if those two are equal to each other and then we compare to see if the left child dot right child with the right child.left right child with the right child.left right child with the right child.left child to see if they're equal to each other if they're not equal to each other then we can just return false right so let me show you this in code so our uh we're going to do this thing recursively so basically what we're going to do is we're going to say okay if root is null and right away we can just return true right and what's going to happen is we're going to create another method called is symmetric and this method will uh basically um takes in two nodes so we're going to compare the left node dot left and then root dot write node to see if they are symmetric so we're going to create this private method so is a boolean is symmetric and it takes a tree node left and right what we're going to do is we're going to do if so if those two nodes are null because we don't know if it's not right so in this case if the left is null and the right is null then what we're going to do is we're going to return true okay if it's not then there is a metric so and there could also be a situation where the left does not equal null and the right that's not equal to null as well so if that's the case then we're going to do is we're going to compare value first we're going to compare its value so what we're going to do is we're going to say okay if left.value is equal to uh right so write dot value so if those two are true then we can just return true right and what we're also gonna do is we're also gonna see if the um just like i mentioned if we were to compare um its subtract to see if there are some metric what we're going to do is we're going to also see if the left dot left is equal to right dot right and we're also going to check to see if left.left let's start left or right left.left let's start left or right left.left let's start left or right is equal to right dot left okay and we're going to use this symmetric method to check to see if they are their sub trees are symmetric as well so in this case uh left dot left and right dot right and we also have to check to see if um if the left dot right and the right dot left are symmetric as well so this will give us either a true or false okay so if one of the statements false it will give us false right so in this case if nothing works then we're just going to return false because there could be a situation where left does not equal null and the right is null right where they could be a situation where right does not equal in all but the left is equal to null so in this case we can just return false so let's try to run the code and you can see we can have our success yeah so we have our success so this is how we complete the problem using um recursion basically the time complexity is pretty obvious we're traversing the entire tree so this time complexity will be big o of n um the space complexity though is also going to be big o of n but to be more exact is actually going to be the big the height of the tree right so that's it for this video thank you for watching
|
Symmetric Tree
|
symmetric-tree
|
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
**Example 1:**
**Input:** root = \[1,2,2,3,4,4,3\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,null,3,null,3\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Could you solve it both recursively and iteratively?
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
299 |
Hello viewers welcome back to my YouTube channel today I am doing a very interesting one named Bhojan Ka Vaas A Kar Do To To To open this question you will have to go to the constable group on our portal and there will be this link. If you have to open it in English, then that question leaf will be given to you as a physically fit number. Okay, and one number has been given to you, which is salt. Read it for a very long time from time to time. But etc. let me tell you what is the effort, be fast, the question is that we have given you the forejet number, it is okay, we have given you the for number, this is just the visit number, two are the office number, one is your hundredth number which we are looking for, okay. Let's need ABCD from the cart for four digit number ABCD now opposite stop this number is ok short term now looking for this ok and this gas number I gas in this whether it is the total of the shot number or not from the plate It's B C D What it means for us to subscribe to any of these numbers is that this channel subscribe means how many numbers are there which are the president, in the gas number it is at the right place at the right digit like in this Loot D here is the shot number representative Jubilee which The digit represents that shot number of ours but it is not in the right position but it should be here but the letter is right here C E That number is President but it is not in the right position Although DJ is Dip That shot number is also President And even after coming to the right position, he is doing it, so how many passes will we have, one will fry, one pinch, okay, reaching one block level, okay, now how much will be the cos, how much will be the co of this number, it means that he is the president in the shot number. The number means the President is on the wrong index at the school gate. Okay, look, he also went to the present, if he is on the index, then one, he has become It is swollen, it is C President, it is in short number and it is on the wrong index, it is in the wrong position, the result is of the second one, so I will take two of its chords, okay then it is okay, now it is obvious that if you ever go to the gas number on this very day, You put some gases and set your own for food and some day you go and put only ABCD gas which is another number so you will use food in it, worship 40000 Jio in it because every digit in it is at its right position in 9th. The cost is percentage, housing investment has become percentage, common sense is fine and for girls, 90 is fine and issue of shares is zero, what does this mean, the problem is your romance is next, when at the same time in the right index, how can one do on hangouts, then number This number system will be distant and zero can be a percentage, this tells you and what to tell you, look, what will be told to you simply, you will be told, look, by commenting in the post in united, the world number of A is positive, it is ok for you. To tell the gas, to kill so much money, to add their specific number, you have to tell which number it is, like here it said that 1234, see Brahmin, first number, one to three, meaning Ghr, subscribe last, this is what we will do next day or what. Is that our right number or not? Okay, look, he has already hit the number gas, its puja employment, then this one gas has hit him, his puja is careful. Okay, then tell us. Basically, after looking at these gases, what will be the right number, what will be his previous number? We have to inform the gas price of the next guest and we have two-three of them, we informed them that it is enough to and we have two-three of them, we informed them that it is enough to and we have two-three of them, we informed them that it is enough to destroy the short number, the train number with four digits, only single length, it is ok, with this decision, tender for dates and that is ok. That data is not enough print data is ok means we can answer still add if I get some then we can do ok kheerwa mistake in this reply that you will show through this letter Neither can it ever be an answer that there is a contradiction in it, okay, there is a contradiction in it, and really, what is the condition in it, in what way is it incorrect data, okay, but now you think of a solution, okay now. I will tell okay, you think of a solution, okay now. I will tell you now, if you guys, post the sauce video and watch it, okay sister, I will tell you, okay now take the hits, thank you, what will we do for this, we will exploit some things, the question is what things will come, the first thing will be this, see. Friend, we were given audit numbers, we were given office numbers, all the numbers are distance courses, so many possible numbers can be made in which four digits should be distant and four digits should be there, how many possible numbers can be made of limit digits, at least it will be less than 10.5 for November 15 test. Mother is be less than 10.5 for November 15 test. Mother is be less than 10.5 for November 15 test. Mother is so big, we can create a data structure which can set all those numbers, I can do something like this and tempo mirchi will not be available and basically we will cancel this, we will cancel the gas. You will reduce your possible answer set by looking at the gas. Okay, this is a lot of help given to solve this question. Okay, so you turn it on, then they discuss its solution, research its solution, you, this is an observation. Basically the effect of observation on the basis of suggestion is that I have written the solution based on that, see, one thing is sure that if this data is correct, then now younger sister Priyanka has a son, then the next data is correct and this is a son. It is sufficient, we leave the vegetables, if the aggregator is correct, then we know that the right one, the soft number one, our soft number and the childhood, we are looking for that with the police number, if I get all these numbers, all these gases, if I get all these gases. If I reply to him by foot and food, then he will come only one and two from here, which will be the shot number if on power, in this case, I am giving more numbers, okay, what we have finalized from the flat was always known in advance, okay and If I keep this 1234 along with how much is Bigg Boss, then only two will come because it has come, if it has fallen on this occasion, if I with 125, which is our 120th number, then share it with the shot number. And if I make that flat of food, then zero bulls and tucks will come there, this is certain, so I immediately said, this is my mission, I have the answer ready, this will be one of mine, this is my first thing, that I should raise the alarm. That I have the answer first and this is what I have said that if all these numbers are there, if it is credit then when we share it with the shot number and remove Bhushan, then the number of meals given by him in the input will come to us only. Okay, now the second thing that I told in the test, the second thing is that we do not have a politician in the total number of votes, the total is okay, so for this, we have the possibility that we can remove all such producers, basically generate We can do it and our straight tax is on them only, it is okay and take this drama, there is no problem, okay, then you must be understanding it a little, that is why you must be understanding it, I will now tell the CBI and see what they will do. We will generate all such opposite numbers, generate all four digit numbers, if the numbers are ok then it is 0123, this is also one number or so, basically what we have to do is not four digits and we have to keep 0.1 on each digit, we have to keep it emphasis and keep 0.1 on each digit, we have to keep it emphasis and keep 0.1 on each digit, we have to keep it emphasis and Every number should come once, that's it, all the numbers will be kept on the set of the generator, will we simply keep them in one set or will we keep them in a plate, understand, there are a lot of numbers here, okay, these are all 7 numbers of ours. Now we will take gas in the set, we have got this stringer in it and forget this is from his village, so what will we do, now with this set number, we will calculate this, after coming home, we will have food Kaushal Kumar. Every time we will hit chocolate syrup chocolate, this would be our short answer, then according to this, the only item of its food has been given in the input. If you are the only one then it remains in the set and if it is not included then one is removed and you If we give food along with it, now I consider this as a short answer and take out the food along with it, then say the same thing and only the curve should go, if it comes then it will remain, if it doesn't come, it will not remain, or if it comes from the net, it will remain. By doing this, we will consider everyone as our idol, we will consider everyone as our short answer, okay, we will ask for short number and if anyone asks us for more number then it will be a simple matter, how will our three fall in the end, how will three increase when all The first case in everyone's address will be that our list becomes MP, the second case will be that there will be more than one person in our list, the third case will be that in our list there is a file in which only one person is teaching, so now you think how this will happen. Okay, what will we do in these cases, what will we judge about them? Okay, now you will think yourself, what will we do in this? Okay, so let's see, what will we do in English? And pass can read your data and incorrect data. Okay, this is your data, this will make you fool. If we have zero people left, it means that this frill of ours and this printer of ours, we have filtered out everything in it, then it means that the data itself has been found to be incorrect. Okay, its the British, it will be the incorrect data on that now if from one If there are more children, it means that this filter station of ours was not so strong that there is benefit in fitting only one person, okay, so do we need more connections, data, okay, and if there is only one loop left, of course, this one. It is confirmed that when we share all our cases with this person, he will get as many bulls and lies as we found in the report, so this is our final answer that our Kailash Vyas has been printed less by the court. Clear it, let's look at the ticket, okay and let's see and understand on the court how to implement it so that you can see this is the accepted solution. Okay, so once let's move on to this point that I am on the net, I have voice mail. Earlier it had happened because of the function, my dear friend, the applet making function was function DEC, then yes, tell me, it happened, so now let's add it and let's see how to maintain the song. A favor, if you are the first one, then the most First of all, we have made a set, the name of this set is All means all such flat numbers and this flowery function will degenerate all these, okay, it will generate all such ones, so this is the function, it is okay. And about the silent generator, let's see how it is going, let's see, first of all we will create a vegetable to see if the person from One 0 has visited there and will call the moment, send the visit here and here is the answer for is it okay? It means he is using chemistry, ok, let's play, how is he doing, basically a simple function of generating, we have shown in level-1, level-2, how it we have shown in level-1, level-2, how it we have shown in level-1, level-2, how it happens, ok, send a message to all, Pooja, please show me your previous records. Look at that, it is fine for the time being, now here the middle head and string is fine, now see this, I have sent it by reference because I cannot come, if and plus 9 had gone there again, no you, so for this, that visit information will be sent as soon as this. We will sell quickly with gimmicks, as long as our advance is good for us, what will we say, we will attach it, we will add note statement in it, we have used Android that stores elements on the basis of everything and not on the subject of shopping, so its Call time and all that happens, it is clearly open or near leaf, okay people have identity, will they take it now, is n't this one mid, isn't it a visit itself, so make it a mittu, fold it, that's fine and that means Mother Brigade and Will use S Plus High Court, first is interior, then convert to Android second for free, appoint in it and call the moment, if you feel like next, then for this, all our permissions have been generated by the club district of the same. It should come and its meaning OK so it's ok, I have seen it, now I have got the intention done, how many gases have been killed, OK file - - We will do the trick, why will we take it, how does killed, OK file - - We will do the trick, why will we take it, how does killed, OK file - - We will do the trick, why will we take it, how does our Korea speak its form and how much does the goals and calls account, so why also we learned it Get it sealed, okay, now how to is under-38 for scheduled tribes, current set is its use, let's see is under-38 for scheduled tribes, current set is its use, let's see is under-38 for scheduled tribes, current set is its use, let's see when will it happen to you that now we are set, we are calling every person of all and every person of Youths are on fast and his feet are with us, he is sending cess here by mistake on his answer account and why are he sending it here, why which one is closed, which mercury temple is fine on gas, electricity is this one. Our current which is almost extracted like this, it knows that this will be our answer and why is it extracting the essence of boys' mistake, then extracting the essence of boys' mistake, then extracting the essence of boys' mistake, then its taste is the function, this cigarette goes to tobacco, if it is in the right place, Aishwarya and Ko are worthy equals. So if you touch the organizers or if you are nearby but hardly there is any meaning in the scene position then do groups, otherwise the cost is ok, it has the function of inch, it is 4G on Play Store, so it is ₹ 15, meaning there it is 4G on Play Store, so it is ₹ 15, meaning there it is 4G on Play Store, so it is ₹ 15, meaning there is a question, ok then return. Do the paper in the middle and last, send it to the worst position. If you have read the call on obscene mission, then it will consider it as the answer and will remove it from the corresponding elders. Okay brother, okay, you are okay now. Now we have taken out the leg. If the answer is given to the swimming team, then speed first. Forget shrink and speed technical tips e have not equal, it means why the one who had come to us to do its course, was taking it out on Wednesday, whatever I got in the input, we will continue, meaning its John will keep, some will be left, some will be set. Will let it stay in, won't do anything, if it is not so then we will delete it from all, we will delete the section, why not delete it from all, see that if we are hydrating on something in the follow, then it is not ID that you Judge, in this set, you are doing that, basically, make it wide from this stage, inside that milk, delete the number of this member of his, okay, delete any number of any of his member, this will help because you can get into trouble. Well, this is a set of examples. Okay, you guys are following the topic. If you get it deleted, you won't be able to tell the story about it either. You will go to the last, so it is not the last, that's why we are using the current one. And in the last we will do their tax and will do joint, set samples and Ukraine, then take the next input calcium, then after that now let's do style filter and do this. This is an attempt to give a special return gift. We first used our printer. Then we took it, I am making our current [ __ ] hair, okay and making our current [ __ ] hair, okay and making our current [ __ ] hair, okay and we made a mixture of current and what we will do, we will print out everything, fix it and then the one that died, which means as much as we had set, we will give it to cancer cells. We will set the current, reduce the size and always use the other side, okay, let's repeat this step with such earrings till they are finished, now the earrings are finished, those three things which were last purchased either Order size becomes zero, meaning there is nothing left. Incorrect data is fine. You are doing backstreet son. If the order is a greater than one, it means more than one thing. Children, that is our filters in a strong policy. Our gates were reduced at all. Meaning data is not there. And we need Redmi, basically this is our last gasp, no, now it cannot be a cigarette, okay, how else do we need it, after that we can tell whether our last-gasp will be done we can tell whether our last-gasp will be done we can tell whether our last-gasp will be done or not, okay, if only one loop is in reverse size, then it is in mind. Will differentiate the old but the lighter one and will simply say that this is our answer in mortgage rescue asset in English which will be doing 600 to everyone isn't it basically complete our logic of this is ok quite interesting and quite meaningful very briskly very skin testing application ok If yes, then this is our code, then you also submit this question here, okay, thank you, if you don't have it, then definitely ask in the comment section, it's okay, till the moment there is a watching recording of it.
|
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 |
179 |
question 179 largest number given a list of non-negative integer given a list of non-negative integer given a list of non-negative integer norms arrange them so that form the largest number and the return the largest number since the result may be very large you need to retain a string instead of integer so if you look at the list that they give you here is integer but they want you to return a string in the end and you can see that they are we're giving to number 10 it's either combo as 102 or 2 1 0. so obviously 2 1 0 is bigger than 0 1 0 2 right so then we return 2 and 0 in this case and then we look at the nums here if we want to form the biggest number of course the large digit digits needs to be at the beginning of the um the position so that it will make the number big so that's actually nine and five and then 34 and then uh three and then 30 right that's how you sort it and here are some constraints here and here are some company asked this question in the last six months so i feel like this question is that if you know that you know you don't know you really don't know so in python there's actually a comparison function it's called um it's called comp um to key function where you can call the function to compare two numbers basically it's a function to help you to compare these strengths you actually don't need to convert them back and forth multiple times there's totally no need to do it what you need to do is use the comp com2key function to call another function to compare the two strings and if um like the two string is um is one string is one zero two as a string the other one is two one zero as a string and then two one zero is bigger than the one zero two even as a string so then you can return the comparison result and then after that you just sort the entire nums array and using the com2 key function and when you sort it the nums is the array that you need to store and the key is basically equal to the com2 key and calling the function you're going to write to compare these two numbers together and then in the end um another scenario that you want to handle is that if the nums that you were giving is like zero in that case you only want to return zero right so you want to return zero if nums the big the first one is zero um otherwise you're gonna just remove all the uh coma in the string list and then join them together as a whole string that's basically how you can solve the issue i think you will understand this better after i um write this in code so let me show you how to do this in code here so i'm just gonna first i'm gonna map the nums uh from the integer to string so nums that's how you um change them all the numbers will become string because right now they're integer and all you need to do is just i want to sort the nums and i sorted i want to put sorted and then the array that i want to sort is nums and if you want you can use a different name as well i'm just going gonna um sort the nums and i want to say key that's how you call the uh com to key function and then you're gonna uh call uh of basically a function called compare or any name that you wanna uh say and i'm gonna write a function um right now so i'm gonna write a compare function here so basically i'm gonna define a compare function how you're gonna compare is string one with string two right and what it does is if string one plus string two is bigger than string two plus string one so what it does is string one when you pass the function right string one is 10 and string two is two if one no um 102 is bigger than two one zero then you're going to return minus one in this case and if s1 plus s2 is smaller than s2 plus s1 which is this case right the um s1 to 10 uh 1 0 2 is smaller than 2 1 0. so you want to return one in this case and if they are equal to each other you're gonna return zero that's basically what this function does and then you use the com2 key to compare the strings and by calling this function and then once you call the function that you already have all the nums that are sorted as the sequence that you really want in the end the other scenario that we need to handle is all the zero scenario if all the one if there's a zero we need to return zero in this case right the other thing that we need to do is right now although all the numbers are sorted but i haven't joined them together yet because there's still a comma in between that we can use the join function in the python to achieve what we want so what we can do is we want to return zero um let me say zero we want to return zero if nums 0 the num's first number is equals to zero in this case if they equal to zero if the num 0 equals to 0 i'm going to return 0 right because you don't want any number start from 0 and then it can be big at all and then um that's the case otherwise what i'm gonna do otherwise i'm gonna join every single number in this list of here and then remove all the comma in between them and how you do it is that you can join and then say the join function and then you basically just join norms together and then this there's nothing in between that may basically means you replace the remove all the coma in between them and that's how you join all of them together and by doing this you should have the uh the nums already sorted here and you should also have them in the right sequence and you will be able to return the correct number and then that's it for the code and let's run it yep if you think that this is helpful please like on my video and subscribe to my channel and i'll see you soon with more legal questions all right bye
|
Largest Number
|
largest-number
|
Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
**Example 1:**
**Input:** nums = \[10,2\]
**Output:** "210 "
**Example 2:**
**Input:** nums = \[3,30,34,5,9\]
**Output:** "9534330 "
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 109`
| null |
String,Greedy,Sorting
|
Medium
|
2284
|
371 |
hello hi everyone welcome back to the channel so today in this video lecture we'll be solving this problem sum of two integers so we are solving the blind 75 list so blind 75 list covers the most important patterns which are very useful for the interview coding interviews so in this section which is this binary section we'll be solving problem related to bit manipulation so this problem is one of those category of problems so will so you can expect bit manipulation involved in the solutions of these problems in the Optimal Solutions of these problems so this is going to give you an idea before you jump to the final solution try to think of the solution by yourself how you can use the bitwise operators to get to the solution so let's first read the problem statement is simple we given two integers A and B and we have to return the two integers uh sum of two integ integers but without using plus and minus right the range of integers is - minus right the range of integers is - minus right the range of integers is - th000 to plus th000 so let's see how we can do that so we given a and b they are integers we want to add a and b but we cannot use plus and minus so one of the KN thought one of the KN solution which may come to the mind is simply increment a or change a by B times so if B so let's say a is five b is four then what I can do the sum of these two is 5 + 4 that is n but without these two is 5 + 4 that is n but without these two is 5 + 4 that is n but without using plus what I can do is I can increment this five by four times so five incremented by four times becomes six then becomes seven then becomes eight then becomes nine so that will give me my answer fine but let's say since we are given that the range of integers is fromus th000 to the plus th000 so let's say B is -4 and a is five so five has to be is -4 and a is five so five has to be is -4 and a is five so five has to be decremented four times five becomes four then it becomes three then it becomes two then it becomes one so one is the answer when I add a and this B and that's true so I got I get a solution which runs in big of B time complexity where I just have to iterate over a so itate from one till B i++ if B is positive so B i++ if B is positive so B i++ if B is positive so A++ if B is positive otherwise if B is negative then it rate B times again and just decrement a fine so this is the case when B is positive this is the case when B is negative and that's all this is going to give me my answer the complexity is B of V the time complexity while the space complexity is constant but we have to get a solution which is of constant time complexity so to get these type of solutions which are of constant time we can think of bit manipulation fine so we can think of bit manipulation if we have expected time complexity like this so let's see how let's just see how so let's start with the observations let's start with a let's say let's take some two numbers 0 1 0 so this is five and this is 2 so I want to add these if I add these two numbers I get seven so what is the bit bitwise form of this seven it is 0 1 so now try to relate these two numbers with this number so I get a one when I have one and zero I get a one when I have Z and one I get a okay so is it okay one so this is seven this is not seven okay this is seven 0 1 so I get a one when I have 1 zero 0 1 I get one 1 Zer I get a one so this is one 0 I get a 0 Z so this is not there so this is seven fine now observe how we are getting seven when I have opposite bits I get a one you can see that when I have similar bits I get a zero now which operator supports these kind of function fun alties think about zor operator how it works when I have dissimilar bits I'm going to get one 1 zero I'm going to get one when I have similar bits I'm going to get zero 0 I'll get zero is it the case that some of these two integers is just zor of these two integers yes this is the case for this particular example let's say if this solution holds for all other cases let's take one more example 0 1 so this is 6 and this is 5 6 + 5 is 6 and this is 5 6 + 5 is 6 and this is 5 6 + 5 is 11 so I must get 11 if I zor these two numbers zero Z one is one On's or 0o is one On's or one is zero Z's or Z is zero but and this number is three but the answer must be 11 that means there is a problem there's a problem with the observation with the solution this is not a complete solution we have a problem so how this three is different from 11 let's write 11 in its bitwise form so 11 can be written like this 8 0 4 8 4 2 1 okay 8 + 3 is 11 so this is 0 4 8 4 2 1 okay 8 + 3 is 11 so this is 0 4 8 4 2 1 okay 8 + 3 is 11 so this is 11 how this 11 is different from this three this is different at this position we have a zero here we have a one here how it is how so what is what does that mean that means when I have one below one I just cannot put zero as it is I have to do something else what I have to do is I have to pass a carry so when I zor one with one I have to pass a carry to the position just left of it now get a carry so this Carry has to be involved in the resulted number at this position fine because this carry when I zor this carry with the zor of these two numbers like one z z0 I'll get one and that is going to give me my answer this is the observation right so how we'll handle it so let's take an example let's take a more generic examples let's say we have 0 1 0 and here we have 0 1 Z 1 so this is 10 and this is 50 now let's follow the solution let's apply the intuition that we have come up that we have till now Zer or one is one On's or one is zero but I need to pass a carry let's pass a carry to the left position so I have one here so zero Z one is going to give me one and now one Z one is again going to give me zero but since I am zaring one with one I have to pass a carry from here as well so I pass a carry to the left position so here one Z one will give me zero now this zero Z the carry which I'm getting from the right position will give me what it is going to give me one so I'll get one here and here I will have zero okay is it okay yes I got a carry then okay so one or one will give me zero and then I have to pass a carry right I have to pass a carry to the right position to the left position so one Z one is zero and that z one this is the carry which I'm getting from this position is going to give me one so that's why I'm putting one here now I also I'm also passing a carry to the right position that will have z zero z will give me zero but Zer or one which is the carry which I'm getting from the right position is going to give me one so this number is 16 + 8 that number is 16 + 8 that number is 16 + 8 that is 24 + 1 that is 24 + 1 that is 24 + 1 that is 25 and that's my answer fine so you got what we have to do here we have to zor these two numbers so this is the first step so we have a and b there's no doubt we have to zor them so we zor them so when I zor these two numbers what I will get 1 0 but this is not the complete answer I have to change it a little bit I have to handle the carries where I have to Cle the carries here then here so how will I handle these carries when I get one below one I have to pass a carry towards the left position when I get 0 and one or 0 and0 I do not have to pass any carry towards the left position so this is the only case when I have to get a carry as the resultant which bitwise operator can do this job think about it's the end operator because 1 and one is one 1 and 0o is 0o so this is the expected thing this is the thing which we require when I end one with one I'm get I get one that means what does that mean I also have to end these two numbers to get the carries but not only ending will be sufficient but like just ending these two numbers will not be sufficient because the carry has to be passed to the position just left of the position where the carry is generated like the carry was generated here then it has to be passed towards left and the carry generated here has to be passed to the left how we going to do that can be done using left shift operator so let's end these two numbers so when I end these two numbers I get 0 1 0 now the carry generated here has to be passed here that means I must get a one at this position fine okay why because the carry was generated here one 1 or one zero so I get a zero but carry pass here so On's or so Zer or one is one but one so that's why I got a one here but one Z one and one will give me a carry and that has to be passed here and that is possible this thing is Possible only when I simply left shift this number so left shift perform a left shift operation over this number I will get 1 0 1 I get this number so how I can get the final answer using these two numbers so this is the zor of these two numbers a zor b This Is A and B left shifted by one now let's Zord these two numbers so this number and this number let's zor them why we have to Z them because observe that the carry which I passed from here to this position from here to here has to be zor with the resultant number has to be zor with the resultant zor of these two numbers so zero zor one is one and the carry will be zared with this one and that is only possible when I zor these two numbers let's zor them one Z one will give me zero this will give me zero okay so I don't have zero here I have I don't have one here I have zero here so this number left shifted by one is going to give me this number so one Z zero will give me one so let's one Zer or Zer will give me zero On's or one will give me zero this all this will give me zero Zer or one give me one but again I also have to end these two numbers because observe that a carry is again generated here when I zor this one with this one a carry is generated so let's end these two numbers again one and one is one and zero will give me zero one 0 and 0 will give me zero one and one will give me one but one and one will give me one then 0 and 0 will give me 0 and one will give me 0 and 0 will give me 0o 0 and one will give me zero and now left shift this number by one because the carry generated here has to be passed to the left position so when I left shift T perform this entire operation I'm going to get 0 1 0 so now I have this number and this number again repeat the process zor these two numbers one Z 0 1 z 0 Z's or 1's or 0 is 1 now here we can see that will not generate any carry because we do not get any one below one we simply get opposite bits okay so how we find it that we have to stop here since we are not generating any carry we do not handle it since we do not handle any carry we get the final answer so how we find how we figure out figure it out let's find the end of these two numbers one and zero 0 and 1 0 1 and 0 that means the end of A and B is going to give me zero and I have to stop here this is my final answer and we can see that this is in date 25 so I hope you got the process what we have to do we have a and b initially perform A's or B and this is my new a also store A and B left shift one in some other variable let's say C because this is going to be the next second integer when I perform the iteration again finally the B becomes this C why because when I iterate again I will again end this a with B I will again Zol this a with b and I will continue this till this B goes zero fine so that's all that's the solution so let's just code it so let's use this while L while B is not equals to Zer use a temporary variable we will be storing A and B left shift one then a will be a zor b and then B will become this C finally this a will hold the final answer so return a right from the end of this uh function so that's all let's try to submit it okay so it got accepted so we can let's discuss the time complexity for this solution now we can see that this can be continue till all of the numbers till I just uh you know till I get this B to be zero and the worst we can have is we have to iterate 32 times because the integers are of 32 bits you can see that the worst we can do is we shift bits to the left 32 times this is the worst scenario we can have so in that case we have to trade for 32 times but we already know the upper bound a real value that is 32 times we have to we will never go beyond 32 33 like this so in that case the time complexity is constant the iterations the number of iterations will not change as according to the input size so that's all for this video if you like the video then hit the like button and make sure to subscribe to the channel and uh continue in this series will where I will be explaining the solutions to the blind 75 list which are most important problems for interviews
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
515 |
hey everyone today we are going to solve the question find the largest value in each three row okay first of all I think we have two difficulties one is how can you keep a max value at a single level and the second difficulty is how can you keep nodes at next down level so since we have to choose a max value at a single level so seems like a breast was such is easier than this first search so let me explain with the breast first search first okay so let me explain the F difficulty how can you keep max value at a single level simply we need to check all not at the single level so it's good idea to have a simple variable for max value at a single level and compare current max value and a new value we find at the same level and every time we start traving a new level we reset the value but how so look at the constraint in the description and it said like a value range includes a negative numbers so there is a possibility that initializing zero it actually doesn't work um so that's why we should initialize the variable with like a minimum number these are points of the first difficulty so use a simple variable to keep max value at a single level we reset the variable every time we start tring a new level because we don't have to compare values at different levels so node value can be negative so we should initialize the variable with minimum value for example negative Infinity in Python okay so next let me explain the second difficulty how can you keep notes at next to down level so for this question do you have to use two list for current level and the next level so in this case what data structure do you use to manage the current level and the next level at the same time my answer is to use DQ so let me write D because uh we can pop data from beginning and append data to the last with constant time o1 very efficient and easy to manage two levels okay so let me demonstrate how it works to solve the second difficulty so first of I initialize DQ with root node so now DQ has node one here and the max value is negative infinity and the result variable is empty so this is a return variable and uh question is how many times do we have to iterate through at each level that is a number of no right at first level we have one no so iterate once at second level twice and third level four times and uh first of all we pop the most left node from DQ in this case N1 and then compare current value so in this case one passus current max value negative Infinity so one is greater than negative Infinity right so in this case max value is now one and then after that um check current node has child or not in this case um we U this node has left node and right node right in this case we put node two and node three to DQ so let's say N2 and N3 and then um after that um we finish uh iteration at the first level right so current max value is one so that's why we put this one to result variable here and then now we have two no in DQ so they are coming from a second level right so that's why we canate through second level in this case twice right so let me put two here and uh before we iterate through the second level every time we reset the max value to negative Infinity um because we don't have to compare the values at the different level right so that's why um max value is now negative infinity and then start a second level so we do the same thing pop most left node from DQ and then compare max value two versus negative Infinity so now um x value is two right and then check if current node has child so in this case so node two has node four and five so that's why append node four and five to DQ so N4 N5 too small and then um so finish node two and now we finish one iteration so we have one more iteration right for node three so put uh not put pop and most left node from DQ and then compare max value now two versus three right so that's why max value is now three and then uh three has child yes six and seven so six and seven no and then uh we finish iteration at second level so current max value is three so that's why in this case um we put three into the variable and three and then so now zero so number of iteration is now zero so we finish second reel and then we check so actually let me skip the explanation because uh we do the same thing so after that so we check the DQ and the DQ has four no right so that's why we have to iterate through like a one by one again and then we do the same process and in the end I think uh seven is a biggest number right so that's why in the end we put seven here and then uh all we have to do is just return this list 137 this is a point of the second difficulty so use DEQ to manage current level and the next level fent but be careful we have to know in deu because we want to check children at the next down level in the loop but we have to return list of node value instead of node itself so be careful sometimes I got error because of that okay just one note so somebody wondering what if we use normal array instead of DQ I think it's possible and so we append data from the last and then we pop the data from beginning right but if we pop the data from beginning in normal array all data in arrays will move to next places like this so which is a o operation instead of o1 DQ operation so DQ never happen this movement so that's why we use de to manage a current level and the next level efficiently yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all iniz result variable and if not root is know in that case we should return Mt list if not the case initialize d q and the Q do upend and root node and while DEQ has node so in the case first of all initialize max value with negative Infinity so in Python Flo minus in and uh we use a one more for Loop for so we don't use this data so that's why underscore in range and the length of Q and then so first of all pop most left node from DQ so node equal Q do pop left and then um compare max value equal Max and Max value M current node bar and then after that so check current node has child or not so if node do left so append left node to Q so node do left and if node do right Q do upend and node do write so after finishing the single Rebel and we append max value to result variable So Max Bar and then so we go back this while and then initialize max value again easy right so after that we should return result variable yeah so let me submit it okay looks good and the time complexity of this solution should be order of n because we visit all no one by one right and the space complexity is actually depends on like a three types and but in the wor case uh if three is like a balanced binary tree so in the end roughly DEQ has a node so how many I think a number of all nodes divide two so in this case we have four number at the same time at s LEL right and the total node is 1 2 3 4 5 six seven so and the we have four out of seven so that's why roughly nide two and we eliminate like a constant time so which is simply o n but it depends on the what tree we have let me explain this first such solution briefly so just in case someone wants to solve this question with a this for search or interviewers may ask you in real interview so I'll show you def F sear solution code here so difficulty of Def F search is we Trav us multiple levels like a back and forth so I think it's good idea to have each node with like a level information so that we can easily what level this node is located at and uh point is here so first of all um we call dep for such solution and passing the root node and zero is a level information and then so we try to put the max value to result variable so now result variable is empty right and then if level so let's say so top level is zero and one and two and if level equal length of data in result variable in that case um current node is a new element new node so that's why just openend the current value to result variable so in this case one right and then so look at this part so when we go left child so we add plus one to Rebel so that the next level should be one so in that case we uh we are now two right and uh so level is now one and then length of data in Vis variable is one right so that's why uh we can consider current node is a new node in like a new single lbel so that's why we just put two here and then so let me skip uh so this part and then in the end we reach three right from here and then oops so when we go right so also at plus one to level so in that case we uh now level one and uh so in reality so we Trav was four and F five fast so in reality we have more data in result variable but we skip here so but at least we have two data in result variable right and now current level is one so two is not equal to one right so in that case it's time to compare Max variable because we already have like a data a max value in level one so we find another value in level one so it's time to compare so in this case two versus three and three is a greater than two right so that's why update here and with three right and then so yeah this is a basic logic and uh we do the same thing for all single level and then in the end we can return this result variable yeah so and this is actually entire code and uh you can get uh this code from the description below I put the uh um post on the read code so you can get the code from the post 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
|
Find Largest Value in Each Tree Row
|
find-largest-value-in-each-tree-row
|
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**.
**Example 1:**
**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** \[1,3,9\]
**Example 2:**
**Input:** root = \[1,2,3\]
**Output:** \[1,3\]
**Constraints:**
* The number of nodes in the tree will be in the range `[0, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
387 |
hello everyone welcome to cs4 all so today we are finally starting off with the very first question of the algo master sheet that is first unique character in a string but before we head over to this question i would like to take you into an adventure of hashing because we haven't covered that much of hashing in the introduction part of our stl video we will be covering hashing in the very next module that is the hashing module after the stl module so without wasting any further time let's get started and by the way if you haven't checked the stl video it's one hour long video i have put my entire learnings and i can vouch for that video that you won't get a video better than that on the entire youtube so definitely check that out it will be available up here in the i button so let's get started so as i said there is a classical map and there is an unordered map so now let's see what is a classical map so suppose you have this container here and you have several pairs so let's say you have a pair here you have another pair here and you have another pair here so a pair consists of a key let's say k is key and v is value right so let's say this is k1 and this is v1 again there will be a key so let's say this is k2 that is a unique key and a unique value let's say this is k3 and this is v3 that is a unique key and a unique value so now we have this three pairs and we want to insert them into a classical map so what will happen let's say we insert this pair into the classical map then we insert this pair into the classical map and finally this pair into the classical map now in which order will be they stored in the classical map so they will be ordered as the same way they have been inserted that is first k1 will be here along with its value v1 then k2 will be here along with its value v2 and finally k3 will be here along with its value v3 so the order is maintained so when we will access the elements that is the key and the value we can access them in order okay now let's talk about an unordered map so suppose we again have the same container and the same pairs that is k1 and v1 and then a k2 and a v2 and then a k3 and a v3 okay now let's insert this pairs let's insert all these pairs into the unordered map so let's insert this one first then this one and finally this one now when we will access them there is no guarantee in case of an unordered map that the pair which we inserted at the very first will be present at the very first there is no guarantee of that the pair can be anywhere it can be at the very end it can be at the very first it can be at the very middle so it can be like k1 here v1 here then you can have k3 here and a v3 here and you can have a k2 here and a v2 here so unordered map is as the name suggests is not ordered whereas the classical map is present in the ordered form so let's talk about what are the time complexity of the operations in case of a classical map so in case of a classical map all the operations that is insertion access is done in log of end time okay so suppose you want to insert n items or n pairs into the classical map that will take you a n login time complexity but in case of uh unordered map all the operations that is insertion axis is a big o of one time complexity so if you want to insert n pairs into an unordered map that will be a bingo of end time complexity okay so this is a huge difference between a normal that is classical map and an ordered map so now that we know what is an unordered map and what is an ordered map we can head over to the question so let's see what does the question says so the question says that we are given a string okay a string is given we can see that lead code is a string and we have to find the first non-repeating character in the first non-repeating character in the first non-repeating character in the string okay so what we can see is we have a lead code here okay so let's go to the mero mode so let's see we have a lead code here right now what is the first observation from the question what is a first observation from the question we have to find a non-repeating character and the find a non-repeating character and the find a non-repeating character and the non-repeating character should be non-repeating character should be non-repeating character should be present first in the string that is the first non-repeating character now let first non-repeating character now let first non-repeating character now let tell me one thing will the frequency of a non-repeating will the frequency of a non-repeating will the frequency of a non-repeating character be more than one in the string no right the frequency of a non-repeating character will always be non-repeating character will always be non-repeating character will always be one in the string and a frequency of a repeating character may be two or more than that in the entire string so let's see the frequency of which character is only one in the string so i can see a l here can i see any l in the rest of the string no i cannot see any l in the rest of the string so i can say this is this l is a non-repeating character now let's say non-repeating character now let's say non-repeating character now let's say we have e here can i see another e in the entire string yes we can see another e that is present right after it so this is not a non-repeating character let's is not a non-repeating character let's is not a non-repeating character let's go to t can we see any other t in the entire string no we cannot see any other t in the entire string so it is also a non-repeating character let's go to c non-repeating character let's go to c non-repeating character let's go to c can we see any other c in the entire string no we cannot see so this is also a non-repeating character same is also a non-repeating character same is also a non-repeating character same for o it is also a non-repeating for o it is also a non-repeating for o it is also a non-repeating character same for d it is also a non-repeating character and e as we non-repeating character and e as we non-repeating character and e as we already saw it is a repeating character so what are the non-repetitive so what are the non-repetitive so what are the non-repetitive characters here the non-repeating characters here the non-repeating characters here the non-repeating characters are l t c o and d right these are all non-repeating characters in the string non-repeating characters in the string non-repeating characters in the string and what is the first non-repeating and what is the first non-repeating and what is the first non-repeating character among all of them that is l right so l should be my answer and we have to return the index of l so index of l would be 0 right so we have to return 0 as answer now suppose we don't have any non-repeating character so have any non-repeating character so have any non-repeating character so let's say we have a string m y okay so can we see any non-repeating y okay so can we see any non-repeating y okay so can we see any non-repeating character m it is repeating y it is also repeating so in case we find a string with no non-repeating find a string with no non-repeating find a string with no non-repeating characters we have to return minus one so i hope you understood the question so let's head over to the solution so i hope you already tried out the solution on your own so now i will be talking about the solution so as i said the frequency of a non-repeating character will always be non-repeating character will always be non-repeating character will always be one and frequency of repeating characters will be two or more than that right so we can either make a frequency array or an unordered map so i will be using an unordered map here so let's say i have this unordered map and i will be using the string lead code okay i will be using the string lead code so first what do i have the character is l so i will be writing l and what is the frequency currently the frequency of l currently which i can see is one so i will be writing a one so l is the key and one is value currently okay then i go to e so what is the current frequency of e here current frequency of e is one again so i will be writing e here and the value will be one i will go to this e what i see is e is already present inside the map right and i can again find a e here so i will not be writing a new key instead of that i will be modifying the existing key and increasing its frequency by a plus one because there is another e here so the frequency or the value will be two here okay then i go to this t i cannot find a t in the hash map so i will be inserting a t as a key and what is the frequency here frequency of t is 1 right so i will be inserting 1 as a value then i will be going to c i cannot find a c here so again i will be writing c as a key and since the frequency is 1 it will be one value then i go to o i cannot find the o in the hash map i will again write it as a key and frequency will be one right then i go to d again i cannot find a d in the hash map so i write a d here and frequency will be 1. again i go to e and i can see that e is already present in the hash map so i will be modifying the value of e by a plus 1 because frequency of e here is 1 so this will become 3 okay so now that we have formed our unordered map what we can do is we can again run through the string so let's make a fresh string so it will be lead code right so now what i can do is i will be going through each and every character in the string so i go to l i c if the l is present in the hash map so l is present in the hash map and then i check if value of l is one or more than that if value of l is one the value of l is one i store the index of this l as my answer so what is the index of this l is 0 so 0 will be my answer and i will break it i will break the loop from here ok now suppose i am doing the same thing for the string my okay so let's do that so suppose i have the string my and my okay so i go to m i see that there is no m present in the hash map so i write m and a frequency of one then i go to y i see there is no y present in the azure map so i go so i insert y here and a frequency of one so then i go to m i see m is already present in the hash map so i do not insert a new key m and modify the existing value of m by a plus one so this will be two right then i go to this y i see that y is already present in the hash map so i do not make a new key y and modify the existing value of y so this becomes two here okay now i will be again going through the string my okay now what i will be doing as i said in the previous example i will be checking for each and every character so m i check if m is present inside the hash map yes m is present inside the hash map and is the value of m equal to 1 no it is not equal to 1 so what does that mean that means it is a repeating character so i cannot execute with it so i go to y again i check if y is present inside the hash map yes y is present inside the hash map and the value of y is not equal to 1 so again i cannot operate with this right again i go to m again the same result value of m is not equal to 1 then again i go to y again the same result value of y is not equal to 1 so after i come to this index that is after i cover all the characters in the string and i did not find the answer i can simply written a minus one so i hope you understood the solution now we will be heading over to the code so first we will be starting off with an unordered map so let's write unordered map and what will be the key will be character value and what will be the value it should be integer value right that is the frequency and let's name this as basket okay now i will be traversing through the entire string that is the characters in the string and i will store them individually to the unordered map that is our basket so let's traverse through the string i could have written this loop in other forms as well you can write them and then what i can do is basket of s at i okay basket of s at i will be plus okay that is default value of a key inside the unordered map or a map is always zero so the basket at s of i so s of i is the character and basket of that character will be that is value of that character inside the map will increase by one okay so that's what this line is meant to be fine now we will be again traversing so this entire block of code will help me to find or to store the value or the frequency of each and every character of the string inside the hash map okay now i will be again traversing through the string as we have seen in the previous examples so now let's traverse through every element or every character of the string so end i equals to zero i less than s dot size and i plus okay now what do we have to check if the characters frequency inside the hash map is one or not okay if it is one we will store the index of this character inside the string and break the loop if it is not one if it is two or three or something else we will be going off to the next character that is we will continue the process okay so let's do that so first what i can write is if basket of s at i okay basket of s at i is equal to 1 okay then what i can do let's write our answer here and answer equals to 0 so this answer will store the index of the non-repeating that is the first of the non-repeating that is the first of the non-repeating that is the first non-repetitive character okay so basket non-repetitive character okay so basket non-repetitive character okay so basket of s at i double equals to 1 then what we can do is answer equals to i okay and then we also need to break okay we also need to break else if it is not 1 if it is 2 or more than that what we can do and if the frequency of that character is more than one that is it is two or three then we will continue the process and one more thing we need to make a flag okay so in case we got the index of the first non-repeating character what the first non-repeating character what the first non-repeating character what we can do is we can make flag as true if we don't get the first non-repeating character black will stay non-repeating character black will stay non-repeating character black will stay as false so what do i mean by this if flag remains true if lag is true that is we have got the first non-repeating we have got the first non-repeating we have got the first non-repeating character and that is present inside the answer the index of that character is present inside the answer so we can just write an answer else if the first non-repeating character is not found we non-repeating character is not found we non-repeating character is not found we can return minus one okay we can just written minus one so let us try running the code okay let's try submitting the code okay so it's done so this code here will take you a time complexity of big o of n that is linear time complexity and what did we see here we saw the implementation of unordered map that is hashing inside this particular question so that's it for today's video i hope you understood the solution i hope you understood the implementation and you bought the intuition as well so if you have any queries or doubts you can comment down below or you can directly reach out to us through linkedin or visit our telegram channel we have daily discussion over there so see you guys in the very next video till then stay happy stay healthy bye it's my life i
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
304 |
hey guys this is Jay sir are doing in this video I'm going to take a look at 3:04 ransom query 2d immutable we're 3:04 ransom query 2d immutable we're 3:04 ransom query 2d immutable we're given a 2d matrix find the sum of elements inside a rectangle defined by its upper left corner and lower right corner so in here right above your tongue okay we're given a matrix like this we need to return the sum and we may assume that matrix does not change so this is a hint and there are many calls to some region function so obviously we could do naivety and do the calculation right from here to here and then when we are with the some region is called again we need to do it again a but it's not if you do that it's not about algorithms right so actually we need to do some improvement on this knife solution well rather than we can't calculate the sum of 2 1 0 3 1 we can let's find some characteristic that we can like something we can cache between different calls of some region that's the part where we can improve right actually I did some problems as related to this one actually if we want to calculate the sum of this area we could for we could get the sum rather than with some B's part out we can do some subtraction like to be some the nice bigger picture right and then subtract this part but you know these 3 5 is swaps subtracted like 4 twice so we need plus it right so the basic idea is that like I J sum i j k l is actually equal to some and all start from zero it will be K L right let the most bigger area subtract with zero this is K a K L so this will be I L some zero this is a k j plus some zero i okay be actually the a to 1 0 1 to 1 so this is the coordinate and here's a problem we start from left top left this is actually the unit is inclusive so KL 0 zu I is here right I know you should I minus 1 l + k right I know you should I minus 1 l + k right I know you should I minus 1 l + k ke is okay KJ j that J minus 1 and here's folks minus 1 so you see when we're going to calculates the area actually we have a approach to do the subtraction and the sum up of this for area which originates all originates at 0 right so that these mmm they're these sums could be cashed across a different cost to some region so of course we could use a like cats and some from origin we need we could use a matrix to keep track of the some right who so it would be matrix man bro juice man no I'll say the input must be valid right we are not saying that I think it should be about it okay some origin would be road arose field with zero and map tap it with array coast but this will feel with zero who now we need to calculate the sound about from origin for each coin it so how we do it well we need to firm for example we're going to check get the some of this part we already know the sum of two three to zero right and to five so the Sun would be mmm the Sun would be the sum to 5 divided subtracted with three and plus these the sum to zero and then plus six right cool okay so we say cost some left would be if the if left is zero if the if J mean J is zero then there's no left so J if J equals zero then it's zero if not it would be some from origin I J minus 1 right some top I say well that become I equals zero then zero if not it could be I minus one J right okay now some top left these are number there well if it would be if I equals zero or J equals zero or we should where we could include add the new zeros in oh I think I'll stop using this I'll allow me to insert a new row and new column okay afterwards plus 1 here plus 1 so the constant Rho equals I plus one constant J column equals J plus 1 so here we could safely do this to the calculation right so some from origin I J equals to some to this one right so I J minus 1 minus some from PI minus 1 J minus 1 plus some from I don't I minus 1 J plus matrix I J right this is the sum for origin so we say this set this to it and the caches are done now if you want to return the sum of region row column what to do as we did here we could just return this summer again okay I'll cash it Konami caching so it would be some from origin okay and we need a plus one right so we all we need plus one okay return Row two plus one caught on 2 + 1 / / / subtract it with Row 2 plus one on us that matrix called 1 plus 1 minus 1 plus 1 call to post 1 + Row 1 plus 1 call to post 1 + Row 1 plus 1 call to post 1 + Row 1 plus 1 no it should be a problem minus 1 so it should be row and column itself yeah so it should work there might be some mistakes but hopefully ah cannot read - one off undefined cannot read - one off undefined cannot read - one off undefined Oh God oh I think mm-hmm J 0 called oh Oh God oh I think mm-hmm J 0 called oh Oh God oh I think mm-hmm J 0 called oh my bad I should replace I too though I hate this really I hate this come let's - can I read probably one of come let's - can I read probably one of come let's - can I read probably one of undefined comment - one we initialize it undefined comment - one we initialize it undefined comment - one we initialize it with extra row and extra column so we start with the row of IJ butter but we will have a fourth started with I plus 1 J plus 1 while this is right so some from so hopefully this will actually explain this one it's minus 1 both - explain this one it's minus 1 both - explain this one it's minus 1 both - form yeah plus and floss itself I think this should be right but my 50y what's the problem oh alright I think that maybe I'm not very used to of this fasting let's just do it in an old-fashioned like some do it in an old-fashioned like some do it in an old-fashioned like some aspartate before some left equals if J is okay it's for left so if J equals zero or should be will be the same comb once one I J song top is the same this one J some top left I 0 or J equals 0 then it's 0 it should work or lemons one I J I minus 1 J minus 1 cool so the I and J should be okay some left plus some top subtract twit sometimes left okay and then here we don't need to plus one thing i J so it's I go to Cana horn waving ro cotton - yeah and go to kata Milan now cotton - yeah and go to kata Milan now cotton - yeah and go to kata Milan now it should be minus 1 and halogen and that you should be go minus 1 plus column 2 minus 1 Lily's not defined Rachel oh ok cool I think we could be accepted the new yeah a beginning I sure I should as you check this if rose 1000 now if colds I should check this ah yeah so already stupid I really mean actually I still need the extra row and column because I can have it here but for here I still need to write it right let's try to wrote back okay I think there's some problem here it's just to rewrite it okay it's IJ this is not right should be row and come so row column should be sound from who grow cotton lights weren't subtract with - one yeah and this is the left part - one yeah and this is the left part - one yeah and this is the left part okay so folks in Milledgeville and some from the world - one but Connie from the world - one but Connie from the world - one but Connie + IJ matrix IJ it's cool so this should + IJ matrix IJ it's cool so this should + IJ matrix IJ it's cool so this should be right and what we're doing here still this is Row 1 column 1 Row 2 column 2 so it should be Row 2 column 2 plus 1 is right so subtract Row 2 plus 1 column 1 plus 1 but here should be minus 1 plus 1 n minus 1 subtract with Row 1 plus 1 but needs minus 1 and then column 2 plus 1 some - here should be plus 1 2 plus 1 some - here should be plus 1 2 plus 1 some - here should be plus 1 minus 1 this should be minus 1 plus 1 minus 1 this should be the right approach yeah I forgot that the checks here me and it's heart grows zero and case mmm not cool 0 if it there isn't it but there is no and no columns cool now we're accepted Wow yeah it turns out that adding a falsie row and the column will still help us I thought that I could just do a little shack in the matrix constructor but it turns out in the same region as it is if I don't do this it's gonna mess up so the time and space for time of course it's linear time right we will do we travel through all the points in the matrix and catch the result and in some region it will actually they constant right we get phone numbers and the to the mathematical to the Matt it to the earth after space we use a matrix to keep track of the sound so it's a XA ml here space Wow nothing so it's constant okay hopefully helps that's all for this problem actually there is a lot of similar topics about this kind of trick I like to think of this trick suppose there is an array like 1 2 3 4 5 if we need to sound of sub array if you like to be sum of 2 3 4 rather than we can in every time we could actually catch the sum from origin right like one like some IJ is actually some 0 J minus some 0 I so this is a trick we can using the 1 dimensional array and still applies to su dimension again and yeah hope it helps in excite bye-bye
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
460 |
provided with the capacity of the lfu cache that simply means whenever you have reached the full capacity and you want to do more insertion you have to perform some evictions from the cach first so as soon as you reach full capacity evict and then insert if there is capacity bending capacity you can simply go ahead and insert so remember this the next operation is a get operation which simply says you are pass the key and you need to return the corresponding value to for that key in case the key is not part of your uh lfu cach what do you need to return minus one in those cases the next method that we have is put where in you pass two parameters the key and the corresponding value because it we are basically implementing an lfu map and with respect to that map this key and value is to be stored the rules of the put operation are as follows check if capacity is full it should invalidate and remove the least recent L used key this is really important the least recently used keys and whenever there's a tie two element or two keys have the same frequency which one should be invalidated the one that was least recently used so you are implementing lfu as well as lru cache internally your lfu cache should take care of deleting the least recently used key Whenever there is collision and for the next operation that we have to take care of in the put operation is insertion if the key is already present what do you update the value of the key else you add the key as a new entry another important aspect that was specified in the question was frequency for the key in the cache is incremented either on a get or put operation if that key already exists in the map if the key doesn't exist in the map the frequency corresponding to that entry would be nothing but one so if you have understood this much then you have understood the problem fully now let's get and see how are we going to implement this up I have taken the same example that was specified in the question the main problem arises in terms of time complexity because the question says you need to create these methods that operate in time complexity of order of one this get method this put method and the Constructor of laru cache in order to solve this problem we'll have to create three maps and what are those Maps let's try and understand their significance the first one is a regular key value map which basically stores the key and its value in the form of a hash map since we are building least frequency frequently used cache we have to store the frequency corresponding to each key that we have so the second map that we have created represents the map between key and its frequency the third map is the most interesting one and this is where the main problem arises a lot of people are not able to think its significance so this map is between frequency acting as the key of the map and the values would be the keys that all the set of keys that have this frequency the data type of frequency is integer for the keys we are storing it in the form of a linked set why link said because the question said whenever there is a collision we have to delete the one that was re recently used and in order to identify re recently used we are storing all the keys in a form of a set the one that was added first into this map represents the key to be deleted so you'll get to know as we will progress over this iteration so let's get started the first is call is of a Constructor that defines the capacity of an l cash so the capacity gets fixed at two the next one comes as we are putting a value one as key and the value as one itself so we want to make an insertion for 1 comma 1 so what we are going to do we'll simply go ahead and make an insertion in key value map for 1 comma 1 along with this what is the frequency of this particular key is the minimum frequency that we have which is nothing but one so we will make an insertion over here for 1 comma 1 where one is acting as a key and one represents the frequency for this entry the next thing that we are going to store is in the frequency Keys map so the frequency is one for this entry so let me just write one over here and what all keys have one frequency so far so we are storing it in the form of a set only one is that key so inserted into our lru cache so this is it so far so good let's proceed ahead the next insertion that we are going to do is for 2 comma 2 so let's go ahead and add 2 comma 2 over here along with this we will store the frequency for key 2 in our key frequency map so the frequency becomes 2 comma 1 because the frequency for this entry for this particular key is one let's proceed ahead along with this we should also make an insertion into our frequency Keys map the frequency for key2 is 1 so we will make an insertion over here let me just change the color of pen and we will add two here that means the frequency one is corresponding to two elements one and two keys both have frequency as one let's proceed ahead next operation is put on 3 comma 3 but even before making an insertion what do we see check what do we see that the lfu cache has become full the capacity of lfu cache that was initialized was two and we already have two elements in it therefore even before making an insertion we have to make one deletion and what element will be deleted the one that has least frequency which one has least frequency what is a minimum frequency element the minimum frequency element is one and uh let's extract this entry from our frequency key map so this gets extracted and out of 1 comma 2 which one would be deleted because it was least recently used and this is retrieved by virtue of keeping the data type as linked hash set the one that was added first will be at the first position so I hope I make sense to you and with this we have deleted one from our map so this entry is gone so does this and let's go ahead and make an insertion for 3 comma 3 so let's start 3 comma 3 over here the frequency of key3 would be one so let's write 3 comma 1 and along with this since the frequency of 3 is 1 we will make an insertion over here as 2A 3 the updated value is 2A 3 in the set so frequency 1 has two elements in it two and three in an ordered format let's proceed ahead the next entry that we have is get over two that means we have to check whether key2 exist in our map or not it does exist in our map so the value returned from here should be two along with this as per the question whenever get operation is involed the frequency corresponding to that key will should be incremented by one that means the frequency for the element two should be incremented by one what is the frequency of the element two the current frequency of the element two is one it should be incremented to two and the same change should be reflected over here we check the entry corresponding to the previous frequency and in our frequency key map and we retrieve this we delete this entry from here because two no longer has frequency as one a new entry gets created and it would be two comma and the set would contain only two in it that represents that frequency 2 has one element pointing to it and its key value is two I hope that makes sense to you let's proceed ahead the next operation is get over three so do we have three as part of our key value three is part of our key value map that means three would be returned from here along with this we should be incrementing the frequency of three what is the frequency of three is one it should be incremented to two therefore what we will be doing we'll be deleting this from here and making an insertion over here so you extract the entry corresponding to the previous frequency you delete that key from that set and you make an insertion at the updated frequency let's proceed ahead the next operation that we have is put and we will be performing put operation over 4A 4 but wait we have exhausted the capacity of lfu cache that means we if I ask you guys which entry in our frequency key map has least frequency you will see one has least frequency however there is no element present in our linked hash set corresponding to one that means we'll be skipping this up we will be looking out for the next higher value what is the next higher value 2 comma 3 and this is what from where we'll be deleting an entry so we will be deleting the first entry which is two so this is gone and this is gone now let's make an insertion for 4A 4 gets added over here the frequency for n key 4 is 1 so let's write 4 comma 1 over here and let's make an insertion corresponding to the frequency value one and we will add four over here let me just change the color of pen for better understanding and we will be writing adding four over here the next operation is get over key 1 do we have one as part of our key value map no it's not there that means we'll have to return minus one in those cases let's proceed ahead next we have get operation over three do we have three in our map yes we have three in our map and what value corresponds to three so you'll be returning three from it along with this we should be updating the frequency for three by 1 unit what is the frequency for three the current frequency for three is two so we will be updating it to three and even before doing that what we'll be doing we'll be making a corresponding change in our frequency key map so we will extract the entry corresponding to the frequency 2 and we will be deleting three from here and we will be adding the frequency for the element three as three so let's add a new entry that represents the frequency and we will add three over here let's proceed ahead get operation over key 4 so do we have four as part of our lru cach yes we have and what is the value is four so we'll return four over here along with this we'll be updating the frequency for the key4 what is the current frequency for key4 it is one let's update it to two along with this we'll be making the corresponding change in our key frequency key map so we'll extract the entry corresponding to the entry having frequency one it is this so we'll be deleting floor from over here and we will be making an insertion for four over here this is it guys so if you have understood these steps we'll be exactly replicating these steps in code so let's get started I have created a private variable that will store the capacity of our L cache moving ahead I've created a minimum variable and I've initialized it to one that will help us identify the minimum entry that exists in our frequency Keys map and along with this I have created three Maps as I talked in the presentation key value map key frequency map frequency Keys map and here we have created linked hashset while Linked haset In order to avoid Collision cases in all the Collision cases you have to delete the least recently used key from our frequency Keys map and this will help us serve the purpose let's move ahead and look at the Constructor it accepts the capacity we set the capacity equals to cap equals to capacity we also create a new entry in our key frequency key map wherein the minimum frequency is one U by default and we will be initializing it to New linked hash that let's walk through the get method now if my key value map doesn't contain the key that is passed as an argument we return minus one in those cases otherwise the key does exist in our map in the end what do we need to return from the key value map whatever value is stored at Key apart from returning the value from the key value map corresponding to this key we should be updating the frequency for this Kei by one unit and this is what we should be parly doing so we extract the current frequency corresponding to this key from our ke frequency map we remove that entry remove the we remove the corresponding entry from frequency Keys map so we get the linked hash that and we remove that particular entry from it along with this we should be incrementing and storing the updated frequency for this particular Key by one unit so this is what we have done from line number 34 to line number 40 so in case my key frequency key map doesn't contain frequency plus one entry then what do we create a new entry in our frequency Keys map and once we have done that what do we simply get that entry and we add key over there along with this we update the frequency in our key frequency map so the key gets frequency + one value now we you will ask me what + one value now we you will ask me what + one value now we you will ask me what is the statement written at line number 31 to line number 33 do you remember we had to identify the minimum value that exist in our key frequency map while inserting the entry for 4 comma 4 we made a deletion from this particular entry although we had one but since there were no values coresponding to one entry we looked out for the next higher minimum value and we used two in that case in order to keep track of it we are incrementing the minimum value over here with this we have evaluated the get method now let's look at the put one is even simpler than get if the capacity is less than Z we simply return if my key is part of our key value map what do we update the value from our key value map and we perform the get operation over the key pretty simple and straightforward if my key is not part of a key value map what do we check if we have exhausted the capacity or not because capacity should never be overloaded we identify the key to be evicted we check the minimum frequency that exists in key frequency key map and we extract the key from it uh once we have the key we simply remove it from the frequency key map key value map and key frequency map all three of them once we have created a capacity we make an insertion and this is what has been done here over here we insert into key value map we insert into over key frequency map and the frequency here would be one why one because uh the element was not present in our key value map so since it doesn't exist it's a fresh entry therefore we have set it to one along with this we have rep pivoted minimum to one and again in our frequency key map we set the value at one index so let's go ahead and submit this up I hope I'm making sense to you guys all these operations have been performed in order of one time complexity order of one with this let's wrap up today's session I'll see you tomorrow with another fresh question but till then goodbye take care and don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead
|
LFU Cache
|
lfu-cache
|
Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache.
Implement the `LFUCache` class:
* `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.
* `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`.
* `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated.
To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key.
When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LFUCache ", "put ", "put ", "get ", "put ", "get ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[3\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, 3, null, -1, 3, 4\]
**Explanation**
// cnt(x) = the use counter for key x
// cache=\[\] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=\[1,\_\], cnt(1)=1
lfu.put(2, 2); // cache=\[2,1\], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=\[1,2\], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=\[3,1\], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,1\], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=\[4,3\], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,4\], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=\[4,3\], cnt(4)=2, cnt(3)=3
**Constraints:**
* `1 <= capacity <= 104`
* `0 <= key <= 105`
* `0 <= value <= 109`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Hard
|
146,588
|
207 |
Hello Everyone Welcome to my channel Today's Questions Schedule YouTube Channel Please Consider Subscribe Tak Hum Ise Zara Total Aaf Na Trysh-Try A Grade Level Form-002 Na Trysh-Try A Grade Level Form-002 Na Trysh-Try A Grade Level Form-002 Number Ko Trysh Maz For Example To Take 20 This First Ko Swarna Rath Express And Ped Total Number of Delhi to create fear is it possible for you all know through with examples for example to stay in dream practical result of question submit 120 first standard 10 and every day through now till 19 try that which number to back to try this Laya Ko Number One To First Question Button Se 10 To Take To Self I Net Means Equal Famous Cycle Weighted For Missile Mist Acid Possible To Complete All The Effort So Let's See How They Can Solve This Question To See Which Should Be The First To Leave One Degree Acid Decree Phone Number Of Not Going Right To Left With Example In Side By Graph Like This That Sui Degree Of One Is Your Indicators Towards One India Force One India 620 51512 Degree Of Two Disrupters This Dynasty And Degree Office I One Should You S0 8051 and degree of three were at this time knowledge to celebrate so it's his first fool-wool tay unmute that so it's his first fool-wool tay unmute that so it's his first fool-wool tay unmute that day decree phone ok free porn loot and will go into reduce the indigo once that e will only going to insult the not win degree open 202 500 Of I will take out one and they will remove the connection and will reduce in degree and election-2014 degree and election-2014 degree and election-2014 and silencer two main entry to now ok want to will reduce in degree of its name o my mitwa and winter collection jhal ka kal morning in degree For 15051 shirt for not visiting card free that i will reduce tha indicative 305 hai new set 5nov liquid for live video course that i office nahi par this android username degree 21 a noble text five and i will reduce the india group 505 se jor 916620 Hai 1.5 india group 505 se jor 916620 Hai 1.5 india group 505 se jor 916620 Hai 1.5 102 Numbers Videos The Number Of The Time Is Simple That In This Way Doing This Question On New Delhi Find Any Case And Suggestion Course One That Inko Tu The Code Shown A Prerequisite For Student Ko Short Tricks Usko Swapn Dosh They Cycle And Cycle Hai Is in that case victim fourth is 1600 temple in which will going to have a time so let's check the one two hands free that ho five ka sex write separately for tomorrow morning from 16 of the cycle right down the in degree that Mira Tower Degree Jhal Tomorrow Morning Will Take Note With Individual Swift 181 Will Remove The Connection Is The President Of You Agree 353 Ki And Will Reduce The Independent Ne Vo Ke Sever Mode Switch Connection And Discrimination And Reduce Degree Of China Incomplete Dependent Phase Vo Ki Inspire The structure of chheet swami number of account that instead of this photo you are removed after connection meet them to that video's description subscribe to Jhala Su's 180 Agyeya ne remote connections to phone number of connection is remote 15609 will take off he I will remove the definition Of Birth Number Android Number One Side And The India Counts Votes 121 Phone Number Officer Suman Number Of Note Sex And The Number Of Connection Remove This Element Which Is Not Same Time Answer Will Only Be Falls Claims For Venus Cycle Thi Aap Ko Ek Sham Ko Jain With Sha 9th Shampoo Diao Ninda Questions With 300 Winners Will Have 00 Votes Jhala Su In This Case Against They Need Not Whisper In Degree Total 2G Phone Batman That They Can Simply Officer Visit For Cycle That Antibiotic Another Example In Witch State Having Degree 2018 Monday Cycle Se Lakshmi Mein B The One To Chu The Indian Hands Free Chand Goyal At Should Be A Bhindi Coldplay One Kya Swami Will Start Scholar Dr 121 That Al Quotes Ne Bebo And I Will Reduce Egg Curry Election The Indicative Of To That Vikram 18102 Undhiyu Vikram 1451 Then In A Situation Where Did Not Agree With You That Jo Hind Is Case Against Implication For Status That Bigg Boss Man Number Of Connection Mode Snow Difficult Number Note Wishes For This Is The Way Can Solve This Question So Let's Move To The Point C What is the full form of 116 Siddha Code Number Three And Who Attacked In Degree Endowed Tv That Separate Collection And Set In With And Storing What Are The Individual Particular Node Inverter The This Statement For Course In Amla Feet Prerequisites For Single Prerequisites For Taking Water Positivity After the institute is doing r meda counter connection remote server connection increase the account pae tane meda mp list which is not individual in which you wish to read element us individual 2030 meaning of not in degree no entry no incident to aye andhero liye subscribe this channel in president means all remote connections are looking for Sohrai Submit I am David Member Solution for this problem you can find the co dinner description below this video was helpful to you please give them a thank you so much for watching the video please don't forget to subscribe to
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,268 |
That a hello everyone welcome to difficult chahiye bhringraj challenge to all boys subscribe to is dam more than free products finance minister tree tweet on the relax feel minimum products' idli the solution is minimum products' idli the solution is minimum products' idli the solution is a minute and lists person suggest products at each character who Died Without Don't Forget Performance Half Price Stop This Approach That Comes Everyday In More [ In More [ In More Subscribe To Are Let's Get Started Limit Tay That You Gender And Slideshow A Solar System List 128 Electronic Problems Subscribe Bill Dhund Subscribe Karna Abhi Na Wo Bill Mind Impatient Subscribe To 200 Electronic Dil Gautam Ajay First Epistle Maintenance Previous Water Will Solve The Element In Our Products And After Starting From Delhi In Food Bill Gets Momentum And Will Create Subscribe In Order Of The List But From 0.5 Video Order Of The List But From 0.5 Video Order Of The List But From 0.5 Video Subscribe Experience Of List Start Searching For two water bottles to the point that she is the first woman MP3 search engine stream of feel the person was the same will automatically give the answer log in the answer hair long will give another combination subscribe like and subscribe to and subscribe our subscribe voice mail Of Baroda Ki Anoop Ringit Newly Created Search In The Dream Of Using Back Em Plus Application Racket Slow Answer The World Of But All The Water In The Middle Name I Want Loosening To Am A Vision Opening Bracket Hai To Abhigya Complete Range And Words Starting From Going to kill them and looking at them and will never be a big boss dispenser only in lower case english characters e will expect vid0 in the map reading atrium you suicide of but i don't know the end you can easily spread over now school subscribe must visit A similar time activity will do for demo and a mode turn opening date again will get the same situation different look for the more you is this time seal volume of the more you will be used not aimed at we may you dare withdrawal loot plus And Avoid During clt20 Twitter The Amazing You Plus Limits That A Cross Which You Will Get Your Answers Hai To Starting From The Producers Guild To Porn Dance A Dil Se Trick Love In Which We Can Good Tuesday Processing And Talk Over Trick In The World In Section Or Just Remember That Will Be Starting From The Lava The Volume To Search For Free Struts Then Subscribe To A Defeat Possibilities If Possibilities When They Know Sach Characters Videos The Floor Posted by Creative The List of Spring Dales Store Me Answers And Andha Products Next Idma Labs Value Id M Id Porn Ki Type Cast And This Product Rings In To-Do List Object To Give Winners To-Do List Object To Give Winners To-Do List Object To Give Winners subscribe for More Video Subscribe Widowed Mother In To-Do List Widowed Mother In To-Do List Widowed Mother In To-Do List I Left Side Reaction Over All The Characters That Appear In This World Will Do The Current President Processing War's Value Animals For The Corresponding Spring In The Dream Will Find Your Feeling subscribe and subscribe that Bill Triangle Builders Play Starting From This Feeling Index Twitter Subscribe Now School Me Mid Plus One Dot Subscribe And Share Vid U Mein Hi Powder Minimum Volume Of But U Want To Pass Into Place Mrs Subscribe To The Last Subscribe Not Properly Subscribe And Subscirbe Ko WhatsApp Dad I Hope You Liked Videos Acid forget to like share and subscribe to have a splash interactions with moral do
|
Search Suggestions System
|
market-analysis-i
|
You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_.
**Example 1:**
**Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse "
**Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\]
**Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\].
After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\].
After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\].
**Example 2:**
**Input:** products = \[ "havana "\], searchWord = "havana "
**Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\]
**Explanation:** The only word "havana " will be always suggested while typing the search word.
**Constraints:**
* `1 <= products.length <= 1000`
* `1 <= products[i].length <= 3000`
* `1 <= sum(products[i].length) <= 2 * 104`
* All the strings of `products` are **unique**.
* `products[i]` consists of lowercase English letters.
* `1 <= searchWord.length <= 1000`
* `searchWord` consists of lowercase English letters.
| null |
Database
|
Medium
| null |
159 |
hello so this question is longer substance with almost two distinct characters so you're giving a shunes the length of the longest option can only contain at most two distinct characters so this question is pretty straightforward so you are still traversing from the starting all the way to the end and then for every single time you need to increment your what Your frequency right so um what I will do is well I'm gonna use the hashmap and my kids won't be the character my values can be the integer which is the frequency right and I would just basically for every single iteration traversal I'm going to check my size of my map if this is greater than 2 which is um there are three character in the lens right then I will just remove so I'm still traversing so I have two pointer I have I and J I'm traversing my J all the way to the right but also if the size is greater than two I'm traversing and I'm moving my eye pointer right by one then every single time I move my J one time right and if there is a size greater than two I only have to move my eye one time this is pretty much the idea right but what happens if I the answer is like c a you know b e right something at least right uh you probably will Traverse I mean uh the current maximum lens should be here right but you still have to Traverse in the E right so once you move your J pointer to here then yes maybe this is not a good idea so uh how about this AABB like a c a b e right so we definitely know a b is the maximum length for the atmos two distinct character right but once you know like J at least position I have to move my eyes so I was initial here right I have to move my eye twice because this current character and this character are the same so I would have to move twice so it is better to using while do when size is equivalent too right because I don't know when should I stop for my eye pointer and the length is going to be what J minus I Plus 1. we plus one this is because we are checking for the length we are not dealing with the index right so let's just start coding and this is pretty easy so let me start so hash map for the chart I'm going to call map and I need I equal to zero and also the results I don't need to initial my J outside because I can initial my chair inside the photo share less than extra lens and then J plus right so the current value is going to be what it's not chart at J right so I'm going to just increment my what my frequency so put SC map.get or D4 c0 plus one so put SC map.get or D4 c0 plus one so put SC map.get or D4 c0 plus one so this line meant if there is no chart inside the map I will initially to zero and then plus one immediately right so while the size is while the meta size is greater than two I need to move my eye pointer and decrement the what the frequency right as well as size right so okay so chart for remove is equal to the install chart at a I right I need to move my eye I need to know my current removed jar right so I'm going to say mapped up to a remote map.get remove mapped up to a remote map.get remove mapped up to a remote map.get remove minus one right and then if the current chart frequency is going to be equal to zero I need to work medical removes actually equal to zero I need to remove this is because if I don't remove I will what I will keep having the same size of my map and then I cannot break all the well break up the value right so now I need to know I need to increment my eye right for the next iteration but again this is actually not you know not smart right I don't have to do like this I can just increment my eye pointer right here right and then for every single time I need to just keep checking my uh length right J minus I plus one and I will return result so this is pretty much a solution so just submit all right so let's talk about the timing space this is a space all the fun this is a Time all open right even though this these are two pointer it doesn't matter because um every single traversal you know average case it's going to be all the fun because this is a for Loop and you are not going to guarantee it the size uh is always greater than 2 right so uh the time you know is all open so let me uh maybe the here something here let's just started development c a h e a t h sounds like this right all right let's start debugging and you just pause at any second and you know you can just see so again the hashmap you know it will just store the frequency right foreign but this one right all right so if you still have questions leave a comment below subscribe if you want it and I'll see you next time bye
|
Longest Substring with At Most Two Distinct Characters
|
longest-substring-with-at-most-two-distinct-characters
|
Given a string `s`, return _the length of the longest_ _substring_ _that contains at most **two distinct characters**_.
**Example 1:**
**Input:** s = "eceba "
**Output:** 3
**Explanation:** The substring is "ece " which its length is 3.
**Example 2:**
**Input:** s = "ccaabbb "
**Output:** 5
**Explanation:** The substring is "aabbb " which its length is 5.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
3,239,340,1034
|
1,015 |
Welcome To Day Shift Ne Absolutely Silent And Asked Questions Molested Divisible By K Also In This Question You Are Given Number K And You Need To Form New Number Three Do It Seervi Subscribe Thank You All Subscribe - 151 Question Number Idi Subscribe Combined 111 Will Be The Number Without Number Features Molested Subscribe to research the video below Tomorrow Morning Me Saturday Slideshow Molested by K and HideQuarters More than 100 on Numbers subscribe Video subscribe And subscribe The Amazing Veervati on Thursday Kabir Cases Tweet - One From Her So Kabir Cases Tweet - One From Her So Kabir Cases Tweet - One From Her So Thursday Opened tha Hua Tha So IF Taken In This Gives Away Free Life And Left Side Reaction Withdrawal 1000 subscribe to subscribe our Channel subscribe Video Subscribe Padh Veervikram Seethe Pattern Start Getting Repeated After The Instances Will Subscribe Ise Subscribe Button Video Idy Thursday The Phone Number Will Be Amazed That Can Be Found Out In Electronic The Times Through Till - Maintains A New Delhi Team India Number Permission Still Result Find At All District 9 The Amazing The Video then subscribe to the Video then subscribe to subscribe and subscribe the Video then subscribe to Hai Aur Ke Belcoms Difficult 5a Luta - Band Sainik Tips Number Responsible Luta - Band Sainik Tips Number Responsible Luta - Band Sainik Tips Number Responsible And Sister Loop Vinod Will Get All Possible Maximum K Times Se [ __ ] Subscribe Maximum K Times Se [ __ ] Subscribe Maximum K Times Se [ __ ] Subscribe Thank You Will Be Made Into A Ko Un Whenever Tips Reminder Turns Out To Be Brought To You For Development Unit Returns The Video then subscribe to the Page if you liked The Video then subscribe to subscribe Subscribe To That Good Backwater Accept Thanks For Watching Video
|
Smallest Integer Divisible by K
|
smallest-integer-divisible-by-k
|
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`.
Return _the **length** of_ `n`. If there is no such `n`, return -1.
**Note:** `n` may not fit in a 64-bit signed integer.
**Example 1:**
**Input:** k = 1
**Output:** 1
**Explanation:** The smallest answer is n = 1, which has length 1.
**Example 2:**
**Input:** k = 2
**Output:** -1
**Explanation:** There is no such positive integer n divisible by 2.
**Example 3:**
**Input:** k = 3
**Output:** 3
**Explanation:** The smallest answer is n = 111, which has length 3.
**Constraints:**
* `1 <= k <= 105`
| null | null |
Medium
| null |
1,450 |
hello viewers welcome back to my channel I hope you're doing great if you haven't subscribed to my channel yet please go ahead and subscribe I have created several playlists to cover various categories of the problem such as trees graphs tries linking lists binary search sorting dynamic programming and so on so please check them out I have uploaded the code for this problem to github repository you can get the link from description section below this video let's jump into today's problem number of students doing homework at a given time given two integer array start time and end time and given an integer query time the ID student started doing their work at the time start time I and finished at time and time I written the number of students doing their homework at time curry time more formally written the number of students their query time lays in the interval start time of I and end time of I inclusive so basically we are given with two arrays right two integer a start time and end time right and the other input that we were given is the query time so now we need to find at the query time how many students are doing their homework so basically if for a student I write the start time is mentioned in the start time array n time is mentioned in the end time array so query time is some another integer if the query time falls between the start time and end time right inclusive basically lays interval start time and end time inclusive then we will say okay this student is doing the homework between that start time and end time right so the query time falls between the start time and end time right that's what so how many students fall into that query time where start time and end time lies between the code in between it right so that's what we need to find out so let's try to understand an example right start time and end time so this is start time I'll call and this is n time right so let's put light below it right so now what is a query time is 4 right so now we will keep a counter right counter is equal to 0 right so we will keep an index so 0 index 1 and 3 so he's doing between 1 & 3 so it does for fall between 1 & 3 so it does for fall between 1 & 3 so it does for fall between 1 & 3 between 1 & 3 between 1 & 3 not really right and this guy's too to start time and end time is same for this guy so it doesn't fall between 4 so for this guy it starts at 3 and goes until 7:00 so he it starts at 3 and goes until 7:00 so he it starts at 3 and goes until 7:00 so he starts at 3 and goes until sir right so for falls in between 3 & 7 so we'll so for falls in between 3 & 7 so we'll so for falls in between 3 & 7 so we'll say well increment this counter 1 right so we are reached the end of the array so we will say this is the answer right so basically the query time should fall in between the start time and end time so there is not a big logic over here so all we need to check is the query time greater than or equal to start time and Corita should be greater than less than or equal to n time because it's it was said inclusive so even if it is let's say if it is it was 3 let's say right so if it was three then this student the student 0 would fall into the three category of course this guy golden food at fall this guy would fall because he is starting at 3 right so now the answer for that it will be 2 right so that's the reason why it's inclusive this is an important hint here we need to consider the equals operation also so we just checking greater than and less than is not enough so we need to use the greater than or equals and less than or equals right so that's what we are going to put the condition and verify whether the query time really falls between the start time and end time right so let's go ahead and look at the core right so first I'm getting and that is a start time length right so we know that for a give every student right if there is a start time there should be an end time so we don't have to verify whether the end time length is equal to n or not or whatsoever right so they should be equal so I'm getting m and count is equal to zero to start with so now I am going from 0 to n and checking whether a start time less than or equal to query time and Curie time is less than or equal to n time this is the condition satisfying right I'll increment it the counter finally just written the counter that's it so this is a very simple code and it should get it working very quickly right so now let's go ahead and look at the time complexity for this right and then we'll look at the space also time complexity so we know there are n students right there are n students for which we have we are given a start time and end time so we are going through the entire array once so that means we will have that time complexity out of that and space complexity are we using any space here yes we're using n and count that's it but only these are two local variables nothing much so local video space will be considered as constant space so this algorithm we will say it uses constant space and the de notion is order go on right so order of four so this particular algorithm is order of n time and order of one space algorithm if you have any questions please post them in the comment section below I will get back to you as soon as I can I have posted the code to github repository in two languages c-sharp and repository in two languages c-sharp and repository in two languages c-sharp and Java you can find the link in the description below this video if you haven't subscribed to my channel yet please go ahead and subscribe also share my channel among your friends please click on the bell icon so that you will be notified about all my future videos thank you for watching I will be back with another way you very soon till then stay safe goodbye
|
Number of Students Doing Homework at a Given Time
|
delete-leaves-with-a-given-value
|
Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`.
The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`.
Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students where `queryTime` lays in the interval `[startTime[i], endTime[i]]` inclusive.
**Example 1:**
**Input:** startTime = \[1,2,3\], endTime = \[3,2,7\], queryTime = 4
**Output:** 1
**Explanation:** We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
**Example 2:**
**Input:** startTime = \[4\], endTime = \[4\], queryTime = 4
**Output:** 1
**Explanation:** The only student was doing their homework at the queryTime.
**Constraints:**
* `startTime.length == endTime.length`
* `1 <= startTime.length <= 100`
* `1 <= startTime[i] <= endTime[i] <= 1000`
* `1 <= queryTime <= 1000`
|
Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
111 |
welcome to october's elite code challenge today's problem is 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 its nearest leaf node so leaf node is where it doesn't have any children no left no right and as soon as we find that we want the shortest depth so this would be two and there's two here we can see it be five so i'm gonna go through two approaches there's basically two we can go depth first search or we can go breadth first search and let's start with that first search what i'm going to do is initialize a self variable as the let's call the smallest number of nodes and we'll travel the entire binary tree and as soon as we find a child we're going to pass along the number of nodes we've seen so far and then just store the minimum value inside of that self variable so first thing i want to do is say if not root we want to immediately return zero otherwise i'm going to initialize a cell variable and we'll call this will have to be stored as the minimum right so i'm going to start off with the highest number possible infinite next we'll have a depth search and what i'll do is pass in the current node as well as the number of nodes we've seen so far so first thing is if there's not node we just go ahead and return and if no doubt if there's no children if not no dot left and not no dot right that means this is a leaf so what we'll do is update our self variable as the minimum between stuff that's small and the number that we've seen so far finally we want to pass in the search to the node dot left with num plus one as well as the right and you can see that i'm going to take care of the ones where it's going to be null by this condition here but you can also add it here say if not no dot left or if no dot left then pass it along either one works finally once that's finished we should have our variable there so we'll just call it root and we'll pass in one since we know that there's a root number and then just return the self.small and then just return the self.small and then just return the self.small so let's make sure this works submit that and accept it so that's step for search there's definitely better ways to do it than this but this is the way that i'm comfortable with what about breadth first search and really breakfast search is probably better because we can just go through the depth and as soon as we find a child we can just return that and not have to you know traverse through the rest of the nodes right so we'll still keep the if not root return zero but what we're going to do is create a q and we'll add in a tubal of the root and the number one so while there's a q we will first pop off a candidate as well as the number cue the top left and we'll say look if not candid left and not candid right then return whatever number we've seen so far otherwise we will if candid has a left we will append to our queue a tuple of candidate.left a tuple of candidate.left a tuple of candidate.left num plus one meaning that's however many notes we've seen so far do the same thing on the right and really this shouldn't ever have to follow the loop but just in case just return i don't know negative one so let's see if this works and looks like it is and there we go so there's two approaches you can go with but that first search or breadth first search either one work there are definitely more efficient ways to code it and make it look prettier but hopefully this explains it pretty well all right thanks for watching my channel and remember do not trust me i know nothing
|
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
|
784 |
Hello Friends This is the Problem Parmesan Cheese You are in Boxing Time etc Time Different Problem Name Letter Communication Electronics Withdrawal and Coins Problem Did Not Stay Tuned for This 600 Bluetooth Subscribe Transform Thursday subscribe and subscribe the Channel Please subscribe and subscribe the subscribe side but only difference between the liquid water possible activate and sleep by this agency is i will give this particular string for every character of like this a that in small form and for 1 hour tender kapil form and on this day i Can take the sweets mall from all records from indian tac various schools platform and 5410 how great for history now skimming swift see iso so what is code singh salute for this in the land subscribe and subscribe that ib medical officer and numbers vacancy mind state candy Subscribe Sloth It Means Videography Different State in Which Point Video Subscribe What is a Particular Time in More subscribe to the Page if you liked The Video then subscribe to subscribe and A dent burst every till now in function and recessive function olive oil can see how Then define this condition and the resources for it's not how are you still alive with others that then life is difficult here whose induced subjects with flute MP3 song status of valid Italian words do n't forget to subscribe Tuesday and subscribe to a northern states of matter if Candidates Selected for Temples Page for Villar Producers Pet Saaf Yuvan Subscribe for Paun Maulvi and Chapter Note Meltha Did you like this article 252 That in Hindi and S E Can See the Length of the State Will Vikram Lage Meanwhile Want to See Pimple Dubo Length of The Missions Tring Welcome to the The Master Plan subscribe our Channel subscribe and subscribe the Channel subscribe Woolen Top 10 Ringgit New Delhi Talk 202 Allots Sales Produce to the State Due to the Affidavit for Discussion Quite late in the string from which Will have to measure the show is the current and acts against Channel and subscribe See Show What is Best Country in the World Made Till Now subscribe to the Page if subscribe now skin the global celebs subscribe to who is this which content does not matter IF THIS WEBSITE CONTAINS NO NOTIFICATIONS LIST OF 102 INDEX THIS POINT I HAVE IS ELECTRIFICATION NUMBER THREE DO IT I WILL JUST DIFFICULT CURRENT STATE OF UP AND YOURSELF BUT ALSO SUBSCRIBE THE VIDEO THEN THAT YOUR ORANGE IS DECIDED ONLY ONE THAT IS INTACT ON WHICH We are in this number Midnight's Children subscribe and subscribe the Channel subscribe to the Page Bluetooth of the Day A Sweet Sister and Different State of Paintings Chapter of Here Type of Motivational Tips A Criminal Mind 1999 Bluetooth subscribe Like the Video and Subscribe to Unmute That in Hindi and English fonts possible all possibilities for the length left in a positive way to friends and your Twitter account the object of which you will come doing typing functions and objectives Yagya Naagin Dance Aap Soe Isi Understand Wah Cheez Problem Standard Platform Par Dikhao Little Bit Easier To You To Stay With Me In A Serious I Will Make You Understand By Studying In A Very Big Dipper
|
Letter Case Permutation
|
insert-into-a-binary-search-tree
|
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string.
Return _a list of all possible strings we could create_. Return the output in **any order**.
**Example 1:**
**Input:** s = "a1b2 "
**Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\]
**Example 2:**
**Input:** s = "3z4 "
**Output:** \[ "3z4 ", "3Z4 "\]
**Constraints:**
* `1 <= s.length <= 12`
* `s` consists of lowercase English letters, uppercase English letters, and digits.
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
783
|
468 |
Hello guys welcome back to tech division in this video also siddha validate ip address problem vismrit ko date 16th june challenge personal problem the giver validate it is the and otherwise is the veer is subscribe The Amazing This is the first floor This is not the statement latest novel on its own rules for etv immediately back a first will be truly ipv4 98100 representing the number for 40 acidity 012 this is not merrily because they are having a leading navodaya jab numbers for every 1000 acids bases In which the center will not be exactly Sales Officer shoot Subscribe like this Officer shoot Subscribe like this Officer shoot Subscribe like this 5192 dot Video plz subscribe and subscribe the Channel Must subscribe button on 08000980009 Quiet Sales Incentive for B.Ed first Quiet Sales Incentive for B.Ed first Quiet Sales Incentive for B.Ed first year will be having great souls and share with it Loan Suvidha Colony Separator Year and Flood Waters of Notification Numbers in Year 2002 subscribe our Channel and subscribe the Channel Rules for Basic Used to Solve This Problem but Not Be Liable for the Solution Regular Expression No Problem Se COD Fuse Alarms Bracket and Give Ranges Between the All elements which fall in this range will be included as well and expressions Swedish Valid CSS Valid Notes Will not be repeated Yes No This indicating character subscribe The Amazing Lead Character subscribe to the Page if you liked The Video then subscribe to the danger of seeing for this is the valley distinctive which has been generated in recent example you can see but 2009 ranges from this is invalid series for example plus to the difference between the times subscribe not repeated channel subscribe our Channel like this is very similar to the new delhi-110 030 pass delhi-110 030 pass delhi-110 030 pass that this is not fair digital india vs which comes into its duties in button two digits only did you to the number of units sid 08000980009 can be repeated in number of times and id Am Id Times But This Is Like This Is Not Working Or Not End Integral Bulakar Blogs 91 Se Zid Syndicate Just Seervi 90 Subscribe 98100 Birds Indicating Just Subscribe To This Blog And You Can Be Repeated In 100 1000 291 This Over the years more and more tubes and everyone knows this is not done subscribe now to plus 2 and repeated in the number of times but does not an example for example you can see from this is just indicating a single digit from 9 to indicate The first one side by side on the middle and the first digit can win range from 129 candidates can be in danger 029 so it will reach from basically tent 299 because what will be the minimum number using these two digits the minimum number can be formed by beating The Minimum of Different and Minimum of the Second Digit Research Minimum of the First Digit Ranges One Minimum of the Second Digit Ranges in Speaker Balbir 102 U for the Maximum Volume Maximum Backing Maximum of the Maximum 9.00 Acid Number 66 2030 to the Number Which Can Be Formed into 10 to maximum number 2424 in rate similar way here in directions three digit number where is fixed deposits and a single digit can be very from 025 subscribe now to receive new updates reviews and reviews subscribe must subscribe to no from small from capital letters To give a number of times indicating 102 to the number of times you want to join the dresses and this will indicate that you can speak any digit 15102 9 and you can repeat the times from solid up to 600 800 basically channels pe 2000 3000 1000 times Page Number 90 Number Idi Number Three Times As They Wish For This Number And Water Also Giving The First Digit Will Win The Range Of 129 Is Indicated In Years And Similarly The Third Desert Will Also Been Arranged for this one welcome is the President subscribe to the Page if you liked The Video then subscribe Give a number of times but they can also report and express in giving Range OK Solitaire Se You Want To For Two Digit Number And Sisters Digits Are 00 Dh0 To The Number Of Times A Request From This Subscribe Button Repeated Only Time Will Be Used To Avoid Subscribe Hai Naveen Dar Similar Way Country Just single digit and single character you can see in this case you want to Repeated 02-02-14 From this Z2 case you want to Repeated 02-02-14 From this Z2 case you want to Repeated 02-02-14 From this Z2 Force 2030 to 9 Tags Page 10 2012 304 You do not need a separate cases where you cannot use directly through Subscribe by using One Day You Will Have To Give Subscribe Quintal Aur De Sake Sequence E Will Have To Improve And Escape Sequence Bigg Boss Winner Will Be Compiled In These Two Escape Sequences Will Just Be Converted Into A Single Step Sequence And You Will Still Remember The Soldiers Will be the compilation result and you will mean that you want to add the regular expression subscribe regular expression similarly you will write to my channel subscribe now to the number 90 what is the meaning of this is the number two digit number one digit number Set 129 Handsfree Power Two Digit Number The First Win The Candidate Can Fall In Danger 029 This Is The Meaning Of Wave Regular Expression White This Number The Worst Condition Can Avoid Number One To Subscribe Must Subscribe Regular Expression Subscribe Digit Number 90 Number 129 302 486 This 134 Will Not Be Valid In This Is The Richest And Here Two Digit Number In This Post Regular Expression Dandruff Ban Sudesh Will Be Invalid K Subscription For Example Number 102 2013 Positive We Need Two Digit Number Can Very From 29 This Is To the number can very from 0001 number 90 for deliverance from one to avoid hotspot the second digit the minimum more than 100 you can form regular expression for this point two wheeler three does it well placid in 1000 basically indicate the number 1090 The Video then subscribe to the Page if you liked The Video then subscribe to the Quin Arrange 029 This is a view from the digit number Indore range 2009 se zoom and three digit number 90 I will be patient use and operator between the number 302 201 Sep 2010 se zee Regular expression in aadheen rangers do not want to right side regular expression in hindi is your mind will not get for regular ipv4 expression rate numbers will be in danger 202 255 ok android person again ok in this will have number 102 ok in this will have number 102 ok in this will have number 102 Regular Expression Already Regular Expression Will Not Be So After Forming Number And Then Check Number In What Is This What You Will Have To Give To The Subscribe Daughter Creating A Key And Have Also Know In Repeating Expression That In Order To Repeat Regular Expression Users Neetu Yudh Kar Li Dresses And Vitamin A Number Of Times I Want To Repeated And You Can Even Reported To Give One Range But In This Case Which You Want To Repeated Fax Number 109 December Expression 2002 Shift Dot S One To Three Times Every Three Times In This Year First Time Tenth Sleep Interview Video Pimples Only Thing You Can You Have Video Pimples Only Thing You Can You Have Video Pimples Only Thing You Can You Have A General Rule Day Celebration Will Be Having Three Times A Day After This Talk Time Set Up Repeated Wayward Small But You Will Have To Write This Expression Ignorance Okay Subscriber single time because I want to phone number indore range 2025 only one who does not believe in your general expression which is used to repeat regular expression subscribe regular expression for regular expression will take here ur pen number 102 and 108 times and whose numbers have been repeated send WhatsApp Radhe-Radhe Video repeated send WhatsApp Radhe-Radhe Video repeated send WhatsApp Radhe-Radhe Video Regular Expression With Daughter To One And For The Final Will Write And Alone That Is A Stand-Alone After Repeated Alone That Is A Stand-Alone After Repeated Alone That Is A Stand-Alone After Repeated Regular Expression In The Amazing Repeating 100 School Separated Saunf I Had Lunch With Her Through Which Seven To Lone Default Value From This number will be from this is nothing but did some distance from this is maximum digit number 0001 number six digit pin 302 98100 and in the capital subscribe times not give attention of celebration will be given more bracket and you will have to right one Courier Because Which Digit Can Be Repeated 124 Subscribe Thank You In Regular Expression For This You Will Lead Character And You Can Replace You Can Be Independent Directors And You Will Be Able To Form No. 102 And 108 Subscribe School And Inter Regular Expression Of You Will Reduce the number of times will be repeated in the last salute not want to the number 102 separately and subscribe to phone number indore range of 024 addition 124 thanks ok records number can withdraw 1024 digit so this point to interlude solid now you can avoid regular expression Subscribe to the channel Subscription for generating regular expression will use this is the function in library and subscribe regular expression in this indicates that you are not happy with this will generator object for this you will use this regular expression for the word you know you will give the match David Subscribe Will Be The Solution In Different Languages And Share With Everyone Can Benefit From Like Share And Subscribe
|
Validate IP Address
|
validate-ip-address
|
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type.
**A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses.
**A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where:
* `1 <= xi.length <= 4`
* `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`).
* Leading zeros are allowed in `xi`.
For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses.
**Example 1:**
**Input:** queryIP = "172.16.254.1 "
**Output:** "IPv4 "
**Explanation:** This is a valid IPv4 address, return "IPv4 ".
**Example 2:**
**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 "
**Output:** "IPv6 "
**Explanation:** This is a valid IPv6 address, return "IPv6 ".
**Example 3:**
**Input:** queryIP = "256.256.256.256 "
**Output:** "Neither "
**Explanation:** This is neither a IPv4 address nor a IPv6 address.
**Constraints:**
* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
| null |
String
|
Medium
|
752
|
139 |
hello everyone welcome back here is when I'm sen today we are tackling a very interesting uh problem popular on coding interviews it's called work break problem from lead code so this problem is a medium level question that's been asked by a number of companies so if you are preparing for coding interview you will find this video uh incredibly useful so let's Dive Right In in the word break problem we are given a string s and a dictionary of string word dick and the task is to determine if s can be segmented into a space separated sequence of one or more dictionary words and the same word in the dictionary may be reused multiple times in the segment so let's go over examples so we have a example with lit code and word lit and code and the output is true because we can segment let's go to as lit space code and present s and both lit and code are presented in the dictionary if we have a second example it's Apple pen apple and the work date is just apple and paint but we can use all words from addict so Apple pen and April and we are using April twice and the first example is a cats and Duck and as you can see it's cats uh and dog and we are given a word dig of cats dog Sand and Cat and the output is false because there is no way to segment cats and dog such that all segments are presented in our uh dictionary so now that we understand the problem let's move to the solution so we are going to use a dynamic programming approach to solve this problem and the idea is to use a Boolean RI BP to iteratively build up a solution that checks if the string can be segmented into a dictionary word so uh we are starting with a word break that takes parameter s and word dig and in the code the P will represent whether the string s up to index I can be segmented into words from the dictionary so it's very important part and initially all ml elements in DP are set to false except for DP 0 which is true because an empty string can always be segmented so let's implement it and will be Len s DP will be false times n plus 1 and dp0 will be true and Max Len will be Max map then word dict okay so we then iterate over the string as for each index we check if the substring ending at that index and C if it's in the dictionary if it is we update DP I to true so let's break a code down so I will Implement so we start by initializing the ri Max Len at the maximum length of word in dictionary and this help us to optimize the inner loop to only consider a substance that could fit a word from the dictionary so then for I in range 1 to n plus 1 and 4 J in range I minus 1 Max I Max Len minus 1 reverse and if DP J and s j i in our word dict DP I will be true and break and finally return DPN okay so let's break down the code so our outer loop so it's this part for I in range 1 from 1 to n plus one and this Loop iterates over the length of the input string s from 1 to n where n is the length of the string and each I represent the current length of upstring and we are considering so we start from one because we are interested in substring of at least one character so inner loop so it is this one for J in range I minus 1 Max I minus MAX Line minus one so this Loop it raised backward from I minus 1 to maximum position where a word from the dictionary could start so the max uh Max I minus Max n minus 1 Word ensure that we only consider substring that are at most maxland character uh long so where max length is the length of the longest word in our dictionary we calculated previously so then we have a condition and condition if dpj and s j i uh in vertex so inside the inner loop we check if the substrings from J to I exclusively exist in dictionary so s j i in word d and if the string up to the index J can be segmented so DP J so if both conditions are true it means that the string up to index I can be segmented so we set DPI to true and break statement uh so break statement is just once we find a value segment for the current length I we break out of the inner loop where no need to continue checking older substring for this I because we already know the answer and so and yeah finally we'll return a DP okay so let's illustrate with an example suppose as is lit code and uh word dict is lit and code and now when uh I is 4 and J is 0 and we considering a word lead and it is in the word dict so if d p 0 is uh true and science both are true dp4 so DP or is set to true so we have I so you can see that we have here the statement so I so dp4 is set to true because dpj so it's here is J it's 0 and our Uh current s is from 0 to 4 uh and it's lit and then if we have for example uh I equals eight and we are considering uh word lit code so it will be lead code and J is 4 then the condition checks code so J will be or and our code will be uh s and here will be yeah so it's from four to eight and uh we check if this code is in our uh word date and if the P4 VP or is also true and because our dp4 is true because we set it previously to true and again times both are true because we have this port this part in dictionary so code is in dictionary so for eight and DP or is also true we set dp8 DP eight two and finally we check DP and is returned uh here and DPN in our case is eight so we output true so this is uh how our code works so yep that's all for uh word uh break problem so let's run it and see and verify if it's working so yeah uh all works so we can submit it for unsynthesis cases to verify so yeah it's working and we beat 99.7 with respect to runtime so it's 99.7 with respect to runtime so it's 99.7 with respect to runtime so it's really efficient uh yeah a great problem to get your health around dynamic programming and manipulation of shrinking python so I hope you found this explanation helpful and remember coding is all about practicing so keep coding uh and you will Ace your next interview and don't forget to hit the like button if you learned something and subscribe for more coding problem solution and tutorial and if you have any question or thoughts make sure to leave them in the comment section below happy coding see you next time
|
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
|
329 |
hello friends so today we're gonna discuss another problem from the latest series i'm working on dynamic programming so here in this series i will discuss very good problems on dp from various platforms so this is a hard problem from lead code name longest increasing path in a matrix so as you can see you are given an integer matrix as you can see in this example and you have to find out the length of the longest increasing path so increasing doesn't that it should be strictly increasing so there should be a word missing it should be longest strictly increasing it should not be like that it can be like nine and then again nine okay so from each cell you can either move in the four directions left right or like up down you can move in any direction you want but you should not move diagonally or outside the boundary and you should not wrap around so you are given that this is the like matrix and as you can see this is the longest increasing path from nine till so as you can see path is one two six and nine okay and as you can see again in this the path is like three four five six so how you can solve this problem the main approach is if i am so how you can first or like you can first pause this video you can like look into this problem go to the description box try this problem on your own try to find out some key points and then you can came down or like come down to this uh explanation afterwards so now i'm gonna start the explanation part so what you're gonna observe uh in this example from this code here is that for every like as you can see for every line or like for every series increasing path there is one starting point and there is one ending point obviously there is one starting point of that series so if i somehow know that like let's assume that this is the starting point let's assume if i know a starting position of like this is the starting position for a longest increasing uh like path then i can easily just run a dss from here because if i run the dfs from this i will check that okay this is the starting point let's assume that i know a starting point this is the starting point then i will go in all the directions from this starting point and then what will i do i will run a dfs i will check the next number it should be smaller than this number or like let's assume that this is a starting one sorry this is the starting point so next number should be greater than this number so as you can see this number so i will again run a dfs this number i can also move in this path as you can see this one six eight this is up another path which has length three this part has length four so i can easily find out the length using dfs so i can confirm that okay i can find out using dfs but i should know the starting point okay there can also be one more case as you can see how you can use dp here see dp the main purpose of dp is to find out or we should not recompute the answer we have computed earlier so what are these answers let's assume that i am not filling out the numbers but let's assume that there is one number here then i will move in this path for that number and then i will reach here this is a like if i started this position the longest path starting at this position increasing part is look like this let's see now i am on this number and then i will move like this and then i move to this point when i come to this point i know that there is one path from this to this so i don't have to recompute this because for every point i am computing the longest path starting at this point so for this i have to go to this for this i will store like first i will for this point i'll store the longest part this for this point i will show the longest point for this so when i come from this point i will come to this point then i will have to just take this answer and add to my current answer till now so that such that i will not recompute this path again so my time is saved so how you can do that i will find out or like what can i do here is for every point i will do the same thing i will find out or i actually start from every point and find out the longest path from everyone okay so just that's a like a slight brute force way but if i take every point and i do a dfs and from every point i will find out the maximum path as you can see like let's assume that this is the maximum path for this point but whenever like i am using this path and i encountered a value which is filled which is already find out that for from this path from this point the longest part is this so i will like just use this answer to compute the longest path for this so that's the whole logic for this problem i have not actually drawn too much or write the code but i will explain you more with the code and also without explaining the code i will draw some diagrams okay so i will remove this part so i can actually what did i do i will draw the same example which is given in the question to make it even more clear which is nine four and six eight and two one okay and i will make a dp table okay let's start from this point and initially there is always exist a path to itself like there is always the maximum length equal to one like there is always a path of length equal to one okay so everything is in size to one let's assume that i have this value 1 and now i can see that the next part next number which is greater than this so there is no path this number is smaller that's number smaller so like i will not do anything i will come out of this group and the maximum length of the path starting at this position is 1 same i will do this and it comes out to be one from four my maximum that to calculate this i will go to the next point which is greater than this as you can see eight is greater than this so i will find out the maximum path and or like ending at this or like starting at this sorry maximum path starting at this point as you can see for finding out the maximum part starting at eight this is no path so for eight is one so if i know the maximum part ending at eight is one so i find out the maximum part ending at four it is equal to two because i can go to this part as you can see this is increasing but from eight is there's nowhere then i will go to six from six as you can see i can either go up i can only have the chance to go up and for up i have calculated the answer for up as you can see from up there is no way so the answer is only six or like six percent judges two this actually included itself and the upper value okay from this uh as you can see i can either go left or i can either go right so if i go to the left there is a one which means there is only one path if i go to the like as you can see if i go to the right the answer is two but i have to also confirm that the number the like this is just numbers i have to come i'll confirm that the number on the light or to the left they should be greater than this number then only i should take those numbers so as you can see this number is equal to this number so i will not take this number the above number is equal to greater than this number that's why i will take this number so it is 1 so 1 plus 1 which is equal to 2 so i will take now i'm on this point so i'm on 2 so i will say that what numbers which is like greater than this number so 6 is greater than this number okay i will take this path which is equal to 2 plus 1 equal to 3 so 3 and that's it from 1 what will i do i will find out all the paths so it will be top like left right and like bottom so as you can see for the top value i have already calculated it too so it can be the answer for this is max of all the directions so for the top direction i found out that there is some answer which is exist so which means that there is always some path from this point which is of length two and i have included this number also for this i will include one to it because i have including this number also and for the left part there is also a number which is smaller than this sorry greater than this so i like i can also choose this path also so i can choose this path this part is outer bound so i will not choose this path is equal to this number so i will not choose this these are the only valid candidates so for this valid candidate the answer is two plus one and for this quality calculator the answer is three plus one so this is maximum so that's this is four and for this uh which is greater this is outer bound this is inbound but it is equal to the stress greater so i can take this to top value which is the current value on it is 1 so i will find out the max of 1 comma one plus one which is two so i filled the db table and as you can see the maximum value in the whole db table is the answer as you can see with this and that's the answer for this problem i hope we get the problem how we are solving this so i will move on to the good part now they will make it more clear so i will take the input of n and m check that uh the length like actually the length is not equal to zero if it's equal to zero the answer is zero and also i will insert or make the length of like the height and the width actually global n m okay then i will make a dp table so i've initialized the gb table here only to make it global so that i don't have to copy it again and again but i have initialized this here with this n m value initialized to zero then the result is zero and then for every possible starting point i'll find out the result which is the maximum length so that's why i'm finding out the maximum among all the possible values so for all the possible values i have to find out the result so result is the maximum over all the possible values so i will have to send the ing starting indexing starting point index and the matrix itself and i will return the maximum path starting at every position so maximum among all the paths and that's the result so how this dfs function is working i will take the input of this dfs starting at this i like x and y if this x and y values already calculated because everything is zero if this dp value has some value this is not equal to zero then only it means that there is some path so what will i do i will check that if this value is already calculated so we'll just return dp of this value so i'm using memorization technique as i will do else i will go in all the four directions so these are the four directions this is a simple way to or like it over all the four directions and then answer is one so actually i'm finding out the answer means that i have to for every point i will check all these four directions and among all the valid directions i will find out the maximum so i will do an answer in size to 1 means that i have like i can already count the current position i'm on so the maximum length at this position or starting at this position is one at like at least one it can be more than one but at least one it can cannot be zero so that what will i do i will it over all the four directions find out the next direction so next direction capital x in the capital y the next direction it should be inbound so i will check that whether the next section is bound if it is it goes out of bound will continue that i will not consider that position in my final answer if this is inbound i will check that the next number it should not be less than or equal to the current number is x y and the next position i will jump to other like directions i can go into is x and y so the matrix of x and y or the next position x of y the number is stored in the matrix position it should not be less than equal to matrix if it is less than equal to matrix of current position then it means that i cannot take this because i can only jump to the expression when it is greater than the matrix position so i will continue else both of these conditions don't hold true which means that the next number is greater and it is also inbound then what will i find out the answer is maximum among the answer and i will again call this dfx function on the new direction plus one because as you can see i have included this number answer so that's why i have included this answer and i will call the dfs function again to the next direction and if the next direction may be in the next direction is already calculated using this dp so it does directly output the dp value and then after all the possible combinations all the possible parts i will find out the maximum answer for the particular or actually starting at the current i j i'll find out the maximum length of the path starting at the current times and i will turn out that answer and also have to like store that maximum path value in the dp table also so before returning i will store that dp of xy is equal to answer and then return all the dp value for the answer value whatever you want before like first store and then return that's what that's it means and that's the whole like dfs function using memoization and using dp and that's the like the starting function sort of function so i hope you get the gist of how you are solving this gp problem this is a very simple problem if you just understand the like trick of this problem if you still haven't already mentioned now thank you for watching this video and stay tuned for more videos in the next one keep coding bye
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
506 |
okay so welcome to the fourth episode not sorry fifth episode of date code so for today we are going to see the question number 506 so let me reduce my streaming yeah so let's read the question you are given an integer array rule of size n that is they are providing an integer array where score of I is a score of ith athlete in a competition all scores are guaranteed to be unique Okay so like each this is a array of score so each score belongs to an individual athlete that is suppose this is a score of Sachin this is a score of dhoni this is a score of Virat so on so this is the score of each individual athlete root player anyone so the athletes are placed based on their scores where the first place athlete has the highest score second place athlete has a second highest score and so on the placement of each athlete determines rank so first rank is a gold medal second rank is silver medal third is bronze and after fourth till nth it is just the number that is let me show here the highest score is 5 right so 5 is the top scorer so 5 is gold medal okay four is the second highest right so uh 4 is a silver medal three is the third highest so three is a bronze and two is at the fourth position so it is four and one it is at a fixed position so it gives five in the same way here 10 has the highest so it is gold medal and five oh three let me check first comes 10 comes nine then eight then four then threes right so zero one two three four five yeah so it's in the fifth position three is in the eight is the second third position so third position is bronze and at last four is it like before it's at the fourth position so it's output is as four so it is an easy problem so let me take I don't need to explain but still I will explain it um let me meanwhile I will let me tell you the logic for it so okay this is our array of score is there a real score so okay so one is for one gold two silver see bronze right and after four just written four in if it is fifth just return five it is so it's as simple as it so let me take 50 let me take an array not in like descending disorder 5 2 3 and so yeah it's not even sorted so um what we need to do is sort it in descending order first we need to sort it in descending order so what will be the output 7 5 then 4 then 2 then 1 yeah we sorted it in descending order what we need to do next is we have to iterate through this array we will iterate our map there is related through each element of this array and if we will take a variable as rest so what we do is if we have to find the index of that element index like index equal to let me store this written sorted and Dot index of what index of this element that is 5. this element 5 right that is index of Pi it does PHI so what will I get what is the index of Phi in the sorted array so it is 1 right index of 5 is 1. so I will do what is if equal to 0 . . . or I don't want to return now I want to push response dot push what push gold right this is a dummy data okay dummy code that is pseudocode you can say it as a pseudopod or else if it is one I'll silver in the same way if it is 2 3 like bronze if it is 2 I will give bronze or else what I just need to push one not one index plus one yeah this is our code let me show it in more cleaner way in the code so let me take a sorted array sorted or equal to the sort if I take this order like this it will sort the array itself score itself though I don't want to score I will restructure the array so if you don't know what it is you can just Google what is destructuring and array it's simple concept and sorting of a number in JavaScript is bit complicated not complicated it will seems a bit complicated when initially comma B logic of this also you can if I do a minus B it will come in ascending order but I need in descending order B minus a so I will get the array in a descending order let me show it in online okay and let's response is equal to okay it is opened I guess let me show you it here okay when I say I got oh it's already sorted I guess so let me give 9 comma three so yeah I got this ordered array right and now what I need to do is let response is equal to score Dot no yeah score.map element if you don't know what is element you have to Google it or you do there is a lot of tutorial for map also you have to definitely if you are using JavaScript you definitely need to know what map is else you can use for Loop also but and you can do the push but I would prefer map because that's what a pro developer will do and so what I what was the algorithm sudokode again yeah I need to check the index so let us check let index equal to index of what index of element right let me check okay I am getting the index of 5 is 1 yeah I am getting the index of element like index of I is one index of 4 is 2 index of three is three index of 2 is 5. so I am getting the index value so what I need to do is put the if condition if element not element index equal to equals to 0 then return what I think the spelling is correct I'm bad at spillings silver bronze add to here one and or else return index plus 1 right this is what we need okay oh here we have to return yeah we got the output I guess we verified outputs yeah silver Browns four points is good if you give like this gold silver medal bronze for pi yes we are getting the output so let me just copy this one and hopefully this will work uh I think I got some error what is the error output expected if I your bones it's same okay here they are expecting everything in string but I am providing it here as a number so we just need to do plus and it will automatically convert it as a string but y isn't working gold medal silver bronze four five gold medal I think some spelling mistakes silver metal bronze medal okay here the spelling of metal is in small at all it is also an issue yeah it got submitted yes that's a solution for you so yeah hope you guys understood the problem it's an easy problem Dairy workout will help you improve the logic so yeah let's see you in the next video next episode that's it thank you
|
Relative Ranks
|
relative-ranks
|
You are given an integer array `score` of size `n`, where `score[i]` is the score of the `ith` athlete in a competition. All the scores are guaranteed to be **unique**.
The athletes are **placed** based on their scores, where the `1st` place athlete has the highest score, the `2nd` place athlete has the `2nd` highest score, and so on. The placement of each athlete determines their rank:
* The `1st` place athlete's rank is `"Gold Medal "`.
* The `2nd` place athlete's rank is `"Silver Medal "`.
* The `3rd` place athlete's rank is `"Bronze Medal "`.
* For the `4th` place to the `nth` place athlete, their rank is their placement number (i.e., the `xth` place athlete's rank is `"x "`).
Return an array `answer` of size `n` where `answer[i]` is the **rank** of the `ith` athlete.
**Example 1:**
**Input:** score = \[5,4,3,2,1\]
**Output:** \[ "Gold Medal ", "Silver Medal ", "Bronze Medal ", "4 ", "5 "\]
**Explanation:** The placements are \[1st, 2nd, 3rd, 4th, 5th\].
**Example 2:**
**Input:** score = \[10,3,8,9,4\]
**Output:** \[ "Gold Medal ", "5 ", "Bronze Medal ", "Silver Medal ", "4 "\]
**Explanation:** The placements are \[1st, 5th, 3rd, 2nd, 4th\].
**Constraints:**
* `n == score.length`
* `1 <= n <= 104`
* `0 <= score[i] <= 106`
* All the values in `score` are **unique**.
| null |
Array,Sorting,Heap (Priority Queue)
|
Easy
| null |
91 |
hello hi guys good morningi I hope that you guys are doing well in this 91 decode ways although it's marked as a medium problem but I'll consider this as a hard problem considering the edge cases which this problem can encounter and also the follow-ups how it can have it has been follow-ups how it can have it has been follow-ups how it can have it has been asked by Comal Amazon Salesforce Uber Oracle in last 6 months Tik Tok Bloomberg flip cart and also Lexus like many companies it has been asked from so you know it's important problem although we have the video for it but still I have seen all these videos which you can see in the top like will are not good like they are not having or considering the optimized solution we'll go on from the very scratch recursive top down then bottom up then optimize bottom up that's reason let's start off cool a message containing the letters from A to Z and can be encoded into numbers you can encode a into one B to 2 Z to 26 now you can encode your alphabets to the numbers now I saying I have given you some numbers you have to tell that what are the possible number of decoded strings for that so for a specific string of numbers I have to tell you that okay we have a string s which has only digits I have to return the number of ways to decode it which means convert that back to a string and for sure please make sure that 06 is not equal to f 6 is equal to F but 06 is not valid for us so zero as a starting you should not consider this please remember this case because this will be a pain in your ass which means you have to handle this Edge case specifically for you every time you have to go now as simple as that we will take any example you can take any example and just try to replicate that what all possible decoded strings you can have so in general I just took this example like this exact same example and I simply added a one into it just to make a bigger example now you will try to just replicate the example and try to figure out what all possible ways should be there so as you have the string one 2 1 226 so you will firstly grab a single one now I am at this index one option with me is I can grab a single one other option is I can grab a one to right okay when I have grabbed this I will move on to the remaining portion okay when I say I will move on to the remaining portion now again I have again two options either I can grab a single two or I can grab a 22 okay when this is grabbed again I have some remaining option so I can grab a single two or I can grab a 26 so you see that every time I have two options which I can consider so firstly at the very basic thought as soon as I you have seen and you have just figured out okay at every IAT index I have two options either I will take the current index or basically the current element or basically the current number and I'll go and simply move on to the next number or I can just Club the I and I + 1 as a I can just Club the I and I + 1 as a I can just Club the I and I + 1 as a specific number and then I can simply move on to I +2 these two are the move on to I +2 these two are the move on to I +2 these two are the options with me again we are just seeing options we have to still verify that the number formed is actually less than 26 we have to still verify that this character is not a zero so there are certain verifications we had to do which actually make this problem a bit tricky than the standard medium problem like medium problem now okay um but the basic thought we have got okay we have two options either we take this one element itself or we take two elements which are basically the to just make a number which is of two digit we can do that and thus we can have a rough idea okay we can have two options and every time you can see we are building a tree having two options so ultimately there can be a chance we can have a repeating sub problem so for that repeating sub problem I can just see as you can easily see that okay if I just ask you for 1 2 two how many number of ways are there so you can see 1 2 two this portion entire portion one to do this entire portion so you can see we have a repeating sub problems so recursion is for sure there repeating some problems are there so you know one thing for sure that you will apply your DP which means you will simply apply topown DP now let's come back and now verify that how you will write your DP we have base cases in the DP we have Prime conditions in DP and simply we have the conditions for memorization condition is simply easy we can just initialize any of our data structure an our map vector and then we can just have a quick check if you have got the values it's good and simply return that if not then just go to the recursive function but the prime things are the base cases and stuff now considering that we took this example 1 2 1 226 so as I told you at this index I had two options either I can take this index which means I'll take this specific value itself one and I'll try on for I + 1 or I said I will just Club on for I + 1 or I said I will just Club on for I + 1 or I said I will just Club I and I + 1 which means starting from I and I + 1 which means starting from I and I + 1 which means starting from the index I for length two I will get it and then I will make a number I'll make a number out of it but as I showed you I will have to okay I started with the index I took the length of two I converted that to a string I converted that string to a number and checked it should be less than 26 if it is then okay it should be like or it is a valid it can be converted to a valid alphabet right okay so when I take two I will have to verify using this condition which I we also discussed previously also and then I can go on to I +2 Now by also and then I can go on to I +2 Now by also and then I can go on to I +2 Now by for the one element can I just simply go on and move on to the next element yeah you can because for sure it can be from 0 to 9 can be any number from 0 to 9 by but Z you remember something 0 you said that you have to make sure yeah exactly so if your I element is actually a zero so simply return a zero because it will have no ways possible to have because at I index if it's actually a zero so for sure you cannot have one as the because your encodings itself are starting from one itself so you cannot have any encoding for zero itself and also what about 03 like ify Club two Still 03 is also not valid because as in this example itself was saying 06 is not valid thing so for sure uh 0 is not a valid encoding and also 03 is also not a valid encoding so basically at the index I if I have a zero bro I'm screwed up I have to return a zero itself so that can be our base case that okay if the I index is actually having a zero please simply return a zero now if we just go on and simply drill down to say okay when to return because for sure we have just seen that uh the main recursive condition is I will try on for the index and for sure if it is not zero then I can try on for every values I can simply go on to I + 1 so one case I can simply go on to I + 1 so one case I can simply go on to I + 1 so one case is I'll simply go on to i+ one index is I'll simply go on to i+ one index is I'll simply go on to i+ one index and I can simply try on other is I will just have a quick check for um string like starting from the index I of length two if the actual integer is less than 26 so for sure this club 2 is also good then I can also try for I + 2 and then I can also try for I + 2 and then I can also try for I + 2 and then I know that I have to Simply sum up the actual okay uh the options which I have from left side the options which I have from the right side just simply sum up whatsoever number of ways they are giving me as you can also see if we go back and look at the base example so ultimately in the end let's say I have made a valid string now we will see ultimately in the end what it means ultimately in the end which means I know it's a valid string or not but yeah if it's a valid string so I can simply say okay it is one string which is valid right so it will simply return uh this will return a one to Upper thing so it is one string this will have one way one which is actually two ways so now this will return one to him so it is saying one way it is also saying one way it will return it will say two ways it will say one way it will say three ways so in total he will say five ways so just saying okay I'm just adding the vas for my left and the right side that's it so similarly I will just have solve function which will get me the V if I just go on to I + 1 and solve function just go on to I + 1 and solve function just go on to I + 1 and solve function of I + 2 considering again considering of I + 2 considering again considering of I + 2 considering again considering here I check that the string basically the integer formed with the two digits should be less than 26 that is then simply add up so that can be your recursive case considering these will be your recursive case now uh just having known okay when to end by this is one of the edge cases which I can handle while returning but by when to end actually so for that if we just simply go down a bit more then we will see okay if my I is here right if I have just one cter left then I'll go and try for I + 1 now if my I would have been for I + 1 now if my I would have been for I + 1 now if my I would have been here so I would have just clubbed it and I would have tried for I +2 so basically I would have tried for I +2 so basically I would have tried for I +2 so basically you see that ultimately if pattern is something like this then your eye in the next iteration your I will be here which is in the end of the string which is s do length and also if you have only one character left and for sure if you have gone into your recursion inside which means if you are inside which means you have skipped this condition which means the correct obv asically this digit was not a zero so it is some valid digit which is one digit which is valid so for sure if you have landed onto the last index and for sure when you have landed here which means you have skipped this which means you have passed this condition so the digit was not a zero so for sure it's a valid digit also so I can just say if my I is actually the S do which means it is the last index or I can say if my if I have passed the complete indexes and I have reached the Super End any which ways if you have reached then you can simply return a one which means okay you have found a valid decoding you have found so I can just simply write the same exact same condition as I if it is greater than equal to S do length minus 1 then simply return a 1 that is that will be my base case now simply have a quick look at theod exact same thing as I showed you the first Edge case which I have to handle is while calling my recursion before itself if my S of I is actually a zero then simply return a zero okay and the condition which I showed the actual base case if I is great than equal to S do length minus one again I showed you s do length minus one by combining these two bases these two base cases I got this condition uh this is a simple memorization condition although you can take the vector also but here I took the unordered map you can take anything just for memorizing your DP and for sure the answer which you've got you will simply put back in your DP itself now the actual recursive cases as I showed you it just has two cases which is go and solve for I + 1 go and solve for I + 1 go and solve for I + 1 go and solve for I +2 but go and solve for I +2 only and +2 but go and solve for I +2 only and +2 but go and solve for I +2 only and only when the integer form from the two digits it's less than 26 right because it like less than 26 represent a valid character for us so I just say okay go and try for I +1 so I just say okay go and try for I +1 so I just say okay go and try for I +1 and also just go and check if the two digits are like if I combine them so should be less than 26 if it is then simply go and try for i+2 also and as I simply go and try for i+2 also and as I simply go and try for i+2 also and as I showed you I'll simply add up whatsoever result I'm getting from left and right side and thus you will see because how you know how to add the results by just simply looking at the first drivon which we had left side right side simply if it's valid simply return a one which our base case which are base case will return for us and for sure if it is a valid then simply return one and keep on adding the okay uh like from the left side and from the right side so I'll simply keep on adding the vs from my left side and from my right side or basically same okay take the current index only and take the two indexes consecutively and then you will get the answer okay but it just a quick check that its time is actually over because you are going onto all the indexes because of the memorization which you have done because of DP and space is also of n because you have memorized all the indexes now the interviewer will ask you man can you please optimize it so what you will do you will start optimizing it but then you will think how to optimize like now optimizations cannot be thought of for the topown approach which means for the recursive approach memorization it is a recursive which we have memorized we cannot optimize this approaches we have to convert this to a bottom up so we will use exact same logic and convert this to a bottom up code again exact same logic now uh just to write the exact same code down we just have to know that okay uh I will just simply know that and for sure uh in to in top down you just say okay I am at the I index and you just try for the future indexes right in the bottom up you just say okay I am at the I index and I think that all my previous indexes are already calculated that is how you go in the bottom up approach now I just simply say that roughly what I have seen from my previous answer is that my uh answer which is the DP of I is nothing but the sum of DP of IUS one and DP of IUS 2 that is roughly what I knew which is what I was adding I was simply adding solve of I + 1 and solve of I + 2 right solve of I + 1 and solve of I + 2 right solve of I + 1 and solve of I + 2 right exactly same thing so I'm just doing the same thing for bottom approach also but have a quick check that how will you handle the base cases how will you handle that zero condition all that stuff so for that I'll just simply have a quick check that what I actually wanted so I took a very small example very small because base cases can only be found out with the smaller example so take very small example which means you take just one character you take two characters and so on and so forth so very small example can help you get the base cases out so I took a very small example one two if I have a one two I will have just two cases either I can form a one two or I can form a 12 that's it now if I form a 12 which means I have my index I here right then I will say okay I - 2 i - 2 simply get me the waste okay I - 2 i - 2 simply get me the waste okay I - 2 i - 2 simply get me the waste for i - 2 get me the vas for IUS 2 and for i - 2 get me the vas for IUS 2 and for i - 2 get me the vas for IUS 2 and I'll simply say DP of I is nothing but the DP of the vas for DP of IUS 2 but you'll see i-2 is nothing it's a empty you'll see i-2 is nothing it's a empty you'll see i-2 is nothing it's a empty string so with this fact and you know the 12 number valid if this number is valid so you'll simply go and check for IUS 2 but IUS 2 is actually DP of0 if your indexes are like this okay index is one indexes two so again I'm just marking that as one indexes you will know why I'm doing that but uh I'm Maring that as one indexes but I'm just going and checking for IUS 2 if that IUS 2 DP of zero which means Z means empty string is actually a valid case for us right which means ultimately you saw that in the top down you were actually reaching the super end then you were saying okay it's a valid string it's a Val string which means you have surpassed if I just go back and say I have surpassed it right so I'm now saying I'm starting it I'm saying now I'm starting it's a valid string for me I have just one character it's a valid string for me so Case is one simply return a one just making sure that it should not be a zero if it's a zero simply return a zero so I'll write the same exact same condition in these two forms right here that I will say um my if my actual DP of I minus which means my DP of zero DP of Z which means my empty string in the beginning is actually a one way for me as my complete string was a one way so my empty string is right now a one way for me and from that I'm starting to build my answer again this Edge case so basically these base cases make this problem a hard problem according to me else if you think it's easy problem great for you um now what about by IUS one yeah true IUS one also check but in that you just check one character itself so this one character you had now if this one character is a zero if it's a zero your value will be a zero so DP of 1 again that is one that is two indexing is let's say one based so DP of one will be a zero if the character is a zero but by what it would have been a one yeah if it would have been a one so you would have just said okay DP of 1 equal to 1 so I just combined these three conditions the two conditions right here which means just saying I have only one character I have no character so simply return a one but only one character only and only when if that character is not a zero if it's a zero simply return a zero so these three conditions I combined in saying that if my character is a zero simply DP of 1 is actually basically the DB of I is actually a zero and if it is not a one like if it is not a zero so simply DP of the first character because base cases are just same uh DP of 0 is actually a one empty string is a one DP of 1 DP of one is actually again a one considering that character which is s of0 because you saw that I am saying one based indexing but actually the string is Zer based so DP of 0 is not equals to a zero then I will say if it is not equal to zero then I will say that my value is one else I say my value is zero for my DP of one so these two are the base cases for your bottom approach which you can have cool and for sure exact same thing that for DPF IUS 2 you will just still go and check that the number formed should be less than equal to 26 right and also uh you know that from this I and this IUS one you will try to build a number out of it right so just have a check that this value should not be equal to zero so s of IUS 2 as I told you I'm saying for one based indexing so for sure s of IUS 2 is on the indexing based for the string so s of IUS 2 should not be equal to zero and this value form should be less than equal to 26 so here I just say s of I should not be equal to zero again that is a that is a0 based indexing because string is zero based indexing but I just thinking of in the form of one based indexing for my DP to actually solve and exact same thing which we have done for bottom up this is how we can replicate for sorry the exact same thing which we have done for top down the exact same we can replicate for bottom up now if I just write that again thing down so it is uh initializing my DP again I just did it for n + 1 because I know it will did it for n + 1 because I know it will did it for n + 1 because I know it will be a one based thing DP of 0 is a one empty string again empty string saying it's a one way because I mentioned that when the entire thing is completed when the entire thing okay uh where is called yeah when the entire string is completed it is actually a one way for me so similarly I just try to replicate my example and say okay if my indexes is here so this is a valid string so i- 2 here so this is a valid string so i- 2 here so this is a valid string so i- 2 it will Point here so it will try to get the value of IUS 2 so this is same i- 2 the value of IUS 2 so this is same i- 2 the value of IUS 2 so this is same i- 2 is just nothing but DP of0 so this should be a one considering this is valid so no matter what it is valid or not we will check have it differently but if I am getting a DP of Zer so it should be a one MP string is valid always valid for us now uh DP of one as I showed you will be nothing but considering this character if it is equal to zero bro um there is no way simply return a zero if it is not it is any other character any other digit okay from 1 to it is any other digit simply return one now I have got these two base cases I am very good to start off from I equal to 2 and for sure it is a one based indexing so I'll go up till the end again this is a one based indexing which means DP is one based indexing but my S is actually zero based so remember that if I am saying okay if I am at the index I and I want to access S of I'm ultimately saying that I will be accessing s of IUS one right it will be one less index which I'm considering so DP of I which means at the ith index of my DP I'm actually thinking of s of IUS 1 which is the actual index for my string so here you'll see that for the I index I'll just check s of IUS one again for the I index it is the current index it is the S of I 2 is the previous Index right so remember that your string is zero based so this is a small thing which you have to make sure okay I have add the I equal 2 I less than equal to one again I will have only and only one check if that is not equal to Z which means the current index value should not be equal to zero then I can simply add my DP of IUS one to my answer and also I'll convert this number into like this two consecutive digits I'll convert into a number and I just check if this number is less than 26 again this small check if it is also which means the S of I minus which means the previous digit should also not be equal to zero as I showed you uh if I am at this index current index I so I'm just saying this if this is zero okay skip it if the previous index also is a zero so it's not a valid case right IUS one and when I say IUS one I referring to S of IUS 2 in the string i s of I'm referring to S of I minus one in the string so with these two cases I will just verify so this is something which you always have to write down and with this you will just say simply add that if this is if it is not equal to zero and your number is less than equal to 26 simply add that in your answer which is DP of I with this uh this small piece of code will get you the answer and ultimately your final answer will be stor in DP of n because you're simply propagating all the values and summing up to the next DP of I now you can think of optimizing it so if I just ask you how will you optimize this so the first thing which you will see is that to calculate DP of I ultimately I want DP of n okay that is good but to calculate DP of I am only and only using DP of IUS one and DP of I -2 so using DP of IUS one and DP of I -2 so using DP of IUS one and DP of I -2 so I'm only using the previous two values I don't need any other value at all so I'll just do the same thing right now the time and space is exactly same as that of the top down approach but now I can think of optimizing because I know it is super visible that I just have to use two variables instead of using this entire DP I can just use two variables which one of which will be DP of I so let's name it as current other variable will be uh DP IUS one let's name it as one back and other variable will be D of IM let's name it as two back which means two backwards it is a current it is one back it is two back I just need three variables and you can see also that I just need three variables it is just being shifted so I'll just use these three variables uh exactly to get the answer so current state of my uh program code is looking something like this now I just have to remove these and modify them these I just have to remove these three and just have to modify that with the variables so I'll just use one back and two back as I showed you instead of I not do anything at all I'll just replace this and say it is two back right because it is two backwards it is actually one back it is actually current again replace this with two back sorry one back replace this with two back and vaa and for sure in the end uh you have to populate your uh two back value uh with one back and also one back value with current just to propagate forward as you do you just propagate the values so you just did only this modification to get the answer so I just initialize two back one back exactly same you'll see two back one back right forget this condition right now uh I just added this extra line that's it you will see why it is required but then I initialized my current uh as you saw that your DP was initialized to zero and I was simply adding in my DP file dpfi which means your dpfi was initialized to zero always right so I just do the same thing I just initialize my current with the zero as you saw I have replaced my dp5 with the current itself so I'm just initializing my current always with a zero okay I did that and then I just did current plus one back exactly same current plus one back right exactly same for current plus two back right exactly same uh it was current plus two back exactly same and then when this entire portion is done just simply assign the new two back and one back value so I just assign one back to two back and current to one back that's how I have got the new two back and one back and then I'll just keep on continuing this Loop ultimately I'll simply return my current which is actually nothing but my DP of n which is the current value which I have updated and that's how you can just use three variables now coming back to just one condition why I have to add it just for you to know that if I just have only one character let's say just one character I have so for sure uh it will not go inside this Loop so I will simply start returning my current which is nothing but a zero value so it will simply the current because it never went inside the loop so I just have to add some condition that if it's just one character simply return the one back itself because my current is not even initialized so how I can even return the current without even getting any of the other character so it is just one condition which you have to add and thus these small Edge conditions make this problem a very good problem for interview because interviewer will see how you considering the edge cases again it has so many edge cases not so many but to handle those edge cases you just have to zero case you just have two consecutive characters if you just get them a digit it should be less than 26 and for sure adding the we which is DP of i-1 and DP of IUS 2 and that's how of i-1 and DP of IUS 2 and that's how of i-1 and DP of IUS 2 and that's how you can simply get this solved in O of end time and O of fun space I hope that you guys got it uh if yes then please smash that like Baby and also if you have not watched uh the depression if you are in depression you want to get out of it and you are saying okay if I'm only one in the depression you can just go and watch the video of how to get out of debation if you're doing lead code for bye-bye-bye-bye-bye
|
Decode Ways
|
decode-ways
|
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s).
| null |
String,Dynamic Programming
|
Medium
|
639,2091
|
51 |
hi everyone welcome to the loophead today in this video we will be solving june lead good challenge and the question for today is and queens it is a very standard problem and it is marked as hard i wouldn't disagree to that but let us see what the question states um it is given that the end queen's puzzle is the problem of placing and queens on an n cross in chessboard such that no two queens attack each other given an integer and written all distinct solution to the end queen's puzzle you may return the answer in any order each solution contains a distinct board configuration of the and queen's placement where q and dot both indicate a queen and an empty space respectively so here the question states that we would be given the size of a board um let's say in this case we have the size of the board as four so we will be having a 4 cross 4 board and we'll have to place that many queens in such a way that no queen is able to attack each other remember that in a chess board or in chess a queen is a player who can move to the um like in the whole column can move to its right diagonal left diagonal or in any diagonal like it can move up down right left or in any direction not traveling diagonally and straight maybe up down so uh we'll have to written all the possible cases that those queens can be placed in a way such that no queen is attacking any other queen so let's see the first example so the first queen is placed on the second column so um it won't be able to attack any of the other queens present on the board similarly in the second case it is placed on the third column and first row so it won't be able to attack any of the other queens present remember in every row there is one queen present and similarly in every column there is only one queen prison so how are we gonna approach this problem first approach would be placing all the queens um in the first row like placing all the four queens in the first row and checking whether uh they would be following the rule or not and if it does not follow then we'll just shift the last or like change the position of each queen until we receive a configuration or positions of all the queens in a way that it follows the rule that is won't attack each other so that is pretty basic and i won't say it is a much efficient one since we have unlocked that uh there is only one queen present in each row so uh why should we place all the queen in the same row so that doesn't make sense so we will jump into a more better approach than this so one approach could be uh like if you could see uh like if i'll number all the rows and column in a way then i would be better illustrating you what is happening over here okay so the queens can move vertically horizontally diagonally and anti-diagonally so the approach here is anti-diagonally so the approach here is anti-diagonally so the approach here is that we know that in each row only one queen can be placed since one queen is placed at a position we'll switch to the next row and for each position we'll check whether it is a safest position for the next screen or not if it does not we'll just go back and try the next index so uh to be more precise uh let me just switch it to a whiteboard yeah okay so we have this initially we have our first screen at first position that is at zeroth position so uh we are over here since the row is filled and since in each row only one queen is to be placed here one queen is placed now we will switch to the next row and we'll check whether the first position is to be filled with the second queen or not or is it safe for the second queen so when we place the this will come to know that it is the same column of the previous mean so it will be attacked by the previous screen so we will go back and just erase this and move to the next column so over here we have this again we'll check if it is a safest position or does it lie in the same range being attacked by the previous queen if it does lie in the attacking range of the previous screen then we'll again just um switch this and move to the next position so in the third position we check that is it being attacked by the previous swing it is not it is the safest position for the next screen to be placed so we will just move to the next row and see whether what are the positions where the next queen can be placed safely so uh at first position again it cannot be placed over here because uh the column is of the first queen attacking range so in the second again diagonally this queen can attack the second one and in the third again it will be attacked directly by the second queen and again at the fourth position so now this configuration is not possible so again we'll go back to the screen and say hey this is not the right position now we'll move our queen to the next position and check whether um if it is safe for the screen uh it is indeed safe for the screen but is it safe for the next screen so we'll start with here and place our next queen here's but it is the attacking radius of the first queen so we won't be placing it here so um can we place it at this position yes we can so we gonna place our third queen over here and since um first and second queen cannot attack this we will just uh mark that this third queen is safe over here now we'll move to the next row and check whether the fourth queen can be placed safely with these configuration of the previous screens so we will check at the first column no it cannot be placed over here uh again in the second one no it cannot be uh then in the third column it cannot be again placed because it can be directly um attacked diagonally by the third queen and again in the fourth uh it will be attacked by the second queen so now what we'll do is this is not the solution so what we'll do we'll just get back to this and say hey this is not the right solution this is not the safest place for the next means and this will go back to this um and say hey uh this was not the correct position uh we need to change our position or be at some badder position now since this was the last column so this will again go back to the first queen and say hey we need to change we need some change over here so this first queen that is me positioned at this position will be shifted over here and now we'll again do the same thing so um let me just drive you again the same thing would happen it would check for all the positions and would find that this is the safest place over here now for the next one uh it will check which one is the safest so it will come out to be this one and the last would be this one so this is how we would be approaching our problem how are we gonna know that whenever a queen is placed at a particular position is the safest position for the queen to be at so here we have recognized certain patterns uh whenever we are placing the queen so first of all whenever a queen is placed at a position the whole column gets blocked that is no other queen would be able to be placed at any of the position in the same row next is the diagonals in the diagonals no other queen can be placed because if they are then they would be attacked by the initial queen being placed so that won't be a safest position for that queen now uh there is certain pattern regarding the um diagonals also so there are the positive diagonal as well as the negative diagonal positive diagonals are the normal diagonals that we'll draw upwards and the negative ones are the diagonals which are drawn in the opposite direction so let me illustrate you this with a diagram so the blue ones are the negative diagonals that is the difference of the row indices or the column indices a particular diagonal remains constant so let me take the first diagonal at position 0 the diagonal elements that is the diagonal row indices and column indices their difference is constant at every position so 0 minus 0 is 0 again then 1 minus 1 is 0 2 minus 2 is 0 and 3 minus 3 is 0 that is row minus column remains constant in the negative diagonal now uh this will be say this will hold true for every index okay now in this the pink one we have the positive diagonal so adding up the row and dice and the column and dice of a particular diagonal that is again going to be remaining constant so 1 plus 0 over here is 1 and 0 plus 1 over here is 1. so this is the positive diagonal now why are these pattern necessary so these are necessary because if we place a particular queen at certain position so we'll have to just uh check whether the next queen is that is being placed is at the safest position or not so what we'll do here is whenever we visit a particular position we would be just adding the column number in that in a site so that the whenever the next queen is positioned or being placed it would check whether that particular column is already visited or not if it is it won't be placed over here and that would save a lot of time like it would be visiting the same column again and it would just skip that particular curve and for the same case now whenever a queen is placed at a position so uh we will just append row minus column that is the difference of row and column would be appended in another set and when once it is appended and another queen is called to be placed at a position so it will check whether that the difference of the row and column is already present in the set or not if it is not then the queen is safe to go but if it is so it will just skip and move to the next one similarly for the positive diagonal we'll be appending or adding the row plus column that is the constant number whenever a queen is placed at a particular position that positions row plus column that is sum of row and column indices would be placed in a set and that set will be checked by the next queen that is to be placed at a particular position if the position of or the sum of the row indices and column indices at a particular position visited by the next queen is not present in the set previously it will be occupied by the next queen so this is what will be happening totally you'll get to know what actually is happening once we dive into the code so let us not waste time and just get into the code first of all we will have to declare the board the queens are to be placed and it would be a board having dot at initial positions um yeah so this is how we will declare the board for i in range of and next uh we have a set of column which would be storing the column where a particular queen is placed and once a column is added in the set no other queen would be placed at that particular color next we have the sum diagonal uh which would be having a set of sum of row indices as well as the column indice next we have difference diagonal which would be having the difference of the row end ice and column and ice at a particular position and we would be returning a resultant array so let us say we have output as array that will be returned next we define our function that is solve so it would be taking the row number as the parameter and its termination case would be whenever it reaches the last position of the board so it will return the mode so since we have to have multiple possibilities so we will have to return a copy of the um change the board or the change the configuration of the board so we'll create a copy of it let us say rest is the copy and since the format is in the form of a string being written so that will be done as like dot drawing function for let's say i we have for i in good so whatever row it is it will be whatever configuration is there in the row it will be written in the form of a string so this is how we are going to return it and we will just append this in our output array every configuration that we get would be returned or appended in this output array so we'll write output dot append address so we'll start tabling each column and check whether that column is present or the column that we are currently visiting is already there in column or not or there are certain possibilities that the sum of row indices and column and dices or the difference of uh row indices and column indices if they are present in positive diagonal and negative diagonal or these some diagonal difference diagonal sets already we are just going to skip them so how are we going to write it so this would be for c in range of n we would check if c is in column another thing is that if r plus c is in some diagonal or it may be possible that r minus c is in difference diagonal so if it is there we are just going to skip them so we will just write continue and those elements or those particular positions would be skipped next we once if this is not being skipped that is the column is not visited so we will just add that particular column in column set um next we will add the sum of the row indices andy column indices in the sum diagonal set so yeah this is our c and also the difference of flow indices and the column indices in the diff d set so this will be r minus c once this is done since we have added we will just update our board of position rc as q that is our queen would be placed at that position since that position is safe and not visited or not in the attacking position of the previous screen or the other queens and this will this position is safe for the queen to be placed at next we'll just call our solve function for next row so this is solve of r plus one since our one queen is placed in one row so our uh row thing is done now we'll again call it for the next row and our column will be traveled in the same way or unchecked for the safest position so far if it is um then our board would be updated with queen placed at that position and once all this thing is done we will just do the cleanup thing so a cleanup is required since we have to return all the possibilities of a particular chessboard in a way that chessboard is available for any other possibility of the configuration so we will simply remove all the things that we have added in this set so once this is done we would be able to find our answer so this is removal is done now also since we have updated the board of rc as queue so we will do the posit that is we'll update it to dot because again the cleanup thing so now we'll just call our solve function for desired row so solve 0 and we'll just return our output array let us see whether it works or not so it should do the work if there are no typos and yes it is a success let us try to submit it and check if it passes for all the test cases or not yes it does thus we could receive our coin for the next day streak so this was our and queen's problems i think you are able to get what i am trying to convey and this was our efficient solution in the backtrack solution so i hope to see you in the next video until then if you like this video hit the like button subscribe to the channel make sure you share with your friends and until next video stay tuned thank you bye
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
907 |
and today i'm gonna do little the medium question 907 sum of subarray minimum minimums i think this is the most interesting question so far for using one monotonic stack this question is asking you if you are given an array of integers which is doesn't have a pattern for all the possible subarrays which has to be continuous what is the sum of all the minimum values in each of these sub arrays if you are following the logic of this question it would be a very hard question because intuitively you would want to get all the possible subarrays from this given array which would be n square because you need to iterate out the beginning index and other ending index so that would be n squared and for each sub array you need to further get the minimum value which would be because it's not assorted would be another and it's not even logan so if you just blue force trying to solve this question it will be n uh to the power of three which of course will exceed the uh exceeds the time limit so what you want to do is you do not follow the logic of this question suggesting which is get all the sub arrays then get the minimum value what you want to do is do the opposite you want to assume each integer in this array is the minimum value then you'll find out the sub arrays this minimum value could be in so the worst situation is this minimum this uh given integer is the largest value like to the left to the right around its neighbors and then that would be just this integer itself so for example let me add a 10 so what you want to do is you want to actually let me draw it so what you want to do is to maintain a monotonic uh increasing stack this stack will help you to find all the possible subarrays given an integer in this uh entire array so let's go back a little bit so in so when you point to each so when you are iterating through this array for each given integer let's start from the first one you want to find its left boundary for the first one exists itself then the left boundary which is defined that the first number that is smaller than the current number because if it's smaller than the current number can't be the minimum anymore so that wouldn't be a valid sub array then you move to the next then you want to find at the left boundary which would be can include a three because one three is larger than one then you can move until here because one is smaller than all of these numbers so for one the boundary would be three and four for the next one for 10 uh it can't move at all because it's the very first left neighbor is smaller than 10 the very first right neighbor is smaller than 10 so the only sample rate it can be is 10 itself so monotonically increasing stack will help you to track the left boundary which is inside the stack and for the right boundary will be checked when a new number is scanned so for example the new number is here then we will start popping out all the numbers in the stack that's smaller than the current one which in this case is all of them you can start getting all the sub arrays when you are popping uh the values in the stack so when you are for example when you are popping this one this is the left boundary and the current new one is the right boundary because we know they are strictly smaller than this one and those empathy part they are bigger than this one so all this distance is a maximum sub array given this uh value that's being popped out and the question is asking you the sum of all the possible sub arrays so you have to get all the combinations that include this given array which would be a combination num of all the possible sub arrays given this current number will be the combination number between d1 and d2 and d1 is the distance d1 is a distance uh between these two d2 is the distance between these two so let me code it since we're using a stack of course we need to initialize a list then we neutralize the result then this is i'll show you the wrong way first to so you can see where the error come from which is the only tricky part of this solution so this is the part that i showed before if the current one if the current new bar is smaller the previous one in the stack then will keep popping and the one being popped out is the one that being considered as a minimum and we are trying to find the other sub arrays for this one and this is a i just to make it more clear and the result would be we want to get the value of this index instead of the index itself so that would be and using that uh using the calculation for combination is all the distance from the left which is the current i minus the very last one in this deck because we know it's strictly smaller than it the very first one is smaller than it then the left the distance on the right side which is the current i minus after popping out all the values in the stack that's larger than the current uh that this new value then we can safely append this new value to the stack because now it is it becomes the largest one in the stack and we can maintain this monotonically increasing uh requirement and the question is asking you to modular the result by 10 to the power of 9. so this is the main logic but if you do this directly i'll show you it will give you an error and the reason is oh not this error i forgot this one uh initially the stack is amplitude so you have to check so this is the error i'm trying to show you so this least index out of range is not from this one it's from this stack this is because you keep popping out while it's already empty so what you want to do is you want to append both beginning and at the end to guarantee it has something left there in the beginning because no one can be smaller than zero so there will be one never be popped out so that's the reason you add one zero in the beginning and you also want to add another zero in the end because at the end you want every value to be popped out like the example i gave you before so one here it if you don't have zero at the end this one will never be popped out because no other value is smaller than zero than one so that's why you need to add a zero to guarantee every value is popped out and to be counted so that's the solution for this question
|
Sum of Subarray Minimums
|
koko-eating-bananas
|
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104`
| null |
Array,Binary Search
|
Medium
|
788,1335,2188
|
162 |
hello and welcome to another Elite code video today we're going to be working on fine Peak element and this is a similar problem to the one I did before which find Peak element in a mountain array however in this problem there's a difference in this problem your array can have multiple Peaks so let's go through these examples so for this one two three one and we can return any of these Peaks so in this one two three one the peak S3 and then in this one here one two one three five six four there are multiple Peaks there's a two peak and there is a six Peak and we can return either one of those and so we need to return the index and there is a little bit more to this problem so in this problem they say that if your anything outside the array is less than anything in there right so for example if you have something like this get rid of this okay so if we have something like this laggy okay two one and then this can be whatever this is a peak because anything outside of the array is negative Infinity so that's a peak and then also if you had a two one here that is a peak as well because anything outside is negative infinity and here's negative Infinity so that's a peak and that's a peak that's all other things you need to know and so let's actually go through the second example and figure out kind of how we need to be doing this and we are asked to calculate it in a login time so we are going to do a binary search but let's just go through what we need to do for this example here okay so we're going to have one two one three five six four so the first thing we're going to actually do is we're going to check if the out of bounds like if these two are Peaks which is pretty straightforward right we're gonna check if these two are Peaks and if they're not then we can just say okay well then we're not going to include those in our binary search because we're going to be checking to the left and to the right of the element so because we're doing that we actually want to start our left and right to be the second element and the second to last element so our left is actually going to start here and our right is going to start here and we're going to preemptively check these before because we're going to be comparing elements to elements in front of them and behind them and so we don't want to have one that can add a bounds here right like if you check here we check for an element in front of it there's nothing there so we don't want to do that you could also start here and you could also just have like a an if statement there where you could just say like if this is zero index then let's just say we're out of bounds but I'm going to do that outside of the code you could do it either way smart so we're going to start here now what are we looking for so this is going to be pretty straightforward let's actually kind of draw what this looks like to give us a better idea right so we're gonna have one two one which is going to look like something like this so one two one and it's going to go up to three and then it's going to go up to five so let's just do like this and it's going to go up some more six and back to four so let's actually draw those right so one two one three five six four can you make this a little bit bigger so that's what we have here and these are our points so let's figure out what are we going to be doing so where's our first pivot value going to be so our first pivot value is actually going to be and let's actually draw this in another color just make it a little bit clearer first pivot value is going to be in between the left and the right so it's going to be right here so our first pivot value is going to be here and we're going to ask ourselves like we're gonna you can do this in a few ways but we're going to compare our element to the element after it so we're going to compare the pivot value to this element here we're going to say is the pivot value greater or smaller and in this they didn't write this but in this problem every value is either greater or smaller than the one after it so you're never going to have like four or something okay and so because of that let's ask ourselves we're going to compare to our next value and we're going to say okay is this 3 greater or smaller than the five well it's smaller so if it's smaller then we know there's at least one Peak that's to the right of this pivot value all right we're guaranteed that because we're smaller so since we're smaller we're going to say okay well we can just get rid of this whole part of the array because we know there's at least one Peak over here so then we are going to make our left over here and now this is our new searching region and we got rid of this whole part of the array so where's our next pivot values our next pivot value is actually going to be over here okay well now so this pivot value is gone we're over here and we're doing the same thing and actually this like this whole part of the array this whole part of the mount is basically crossed out now because we got rid of that because we know there's a there was a peak somewhere over here so we're going to do the same thing we're in compared to next time we're going to say are we greater or smaller well we're smaller again so for smaller we know that there has to be a peak that is somewhere over here right there has to be a peak because there's two conditions right if you think about it either it keeps going up and never comes down which means the last part is a peak or it comes up and then comes down and then there's some Peak here right so if the array ends at like five six then we know that six is a peak but we know from our previous work that the last element is not a peak so our case is always going to be this but either way it would work okay so we know that there has to be a peak here so where are we going to move we're going to move to the right again right so we're going to take this left we're going to delete it and we're gonna move to the right again so let's actually change the color there again so our left is now going to be over here and we're deleting this whole section of the array and we're deleting this peak as well so now our left and right are in the same value so obviously our pivot has to be the six and so let's draw that out as well so our pivot is going to be over here and now we have to try again okay are we greater or smaller where we are greater so if we're greater that means there's two things that are possible either we are on the down slope right like after if it's here and we're tracking over here and we are greater but there's still something greater here or we are the peak and so we're going to check the element to the left and we're going to say if we're greater than we're the peak and let's just return and we are greater so let's return but if we were not greater if we were on the downslope then we know that our Peak has to be to the left of this p and then we would just move our right that way okay so let's actually write down all these steps just to get a better understanding so one check four endpoints or ends of array to be a b if yes we just return Red then okay otherwise let's make L and R the second and second to last elements in the array okay and now for our checks let's get a pivot if pivot is less than pivot plus one that means that the peak is to the right of the pivot otherwise if pivot or so let's just write it down before if pivot is greater than pivot plus one we have two cases we are either on the downslope or we are on the peak so then we check for the peak by comparing the pivot minus one if it is greater if sorry pivot is greater than pivot minus one then we have the peak rate then return the peak otherwise so if we're on the down slope right once again if we're on the downslope here if this is if we're on some down slow Peak then we have to go left so otherwise the peak is to the left and we're guaranteed to have at least one with these cases right so let's go over it one more time so we can check the ends we make the L and R the second to last elements we get a pivot if the pivot is less than the pivot plus one that means we're on the upslope so we're like here somewhere and there's a peak that's to the right so we just need to get rid of all this stuff to the left and go to the right otherwise if the pivot is greater then pivot plus one so this would be like pivot plus one that means we either have we're either going down or we are at the peak we check the element to the left if we're greater than both then we have a peak otherwise we need to just go left in our binary search to go to the left side so now we have everything to code it up it's pretty sure four Once you recognize like we don't really care how many Peaks there are we're just looking for one and so there is guaranteed to be at least one peak in the direction we're going if we know for going up or down if we're going up there's a peak that has to be to the right and if there's if we're going down there's a peak that has to be to the left otherwise we are the peak itself okay so now let's actually code that up so the first thing we're going to check is if our end of the array are a peak right so if length nums so if you actually look at the constraints length numbers can actually be one in this case that's left sometimes equals one we only have one element and that has to be a peak or nums zero is greater than nums one or nums negative one is greater than nums negative two we can just return here uh actually we want to do these separately because this will give us two different values so if either one of these is the case that means the first element is a peak so we can just return zero and then we need one more check here so this is the case for that it's the case for that now let's do our second check for the uh so if nums negative one is greater than num is negative two that means our last element is the peak so we can just return length of nums minus one so now that we removed the first and last element now we can just start with the second and second to last element now we have these comparisons that we can freely do without worrying about going out of balance so I think it's more easy it's like an easier way to do this problem as opposed to doing uh left equals less than or left is less than right we can do left is less than or equal to right but I'll show you here so we're going to say left equals uh one and then right equals length of nums minus two right second to last element it's a while left is less than or equal to right we're going to get a pivot so we can just call that P even just make it even easier P left plus right over two now what's our what are our conditions so if nums p is greater than nums P plus one or I guess let's do less than first so notice p is less than minus P plus one then that means we are on like the upslope of the mountain so we need to be going right so we can just say in that case let's just say if we need to be going right we need to do left equals pivot plus one else so otherwise we are on the downslope of the mountain that means p is greater than P plus one so we need to check if we are the actual Peak itself so if uh nums p is greater than nums P minus one that means we are the peak so we can just return here return P otherwise we are on the down slope and then our Peak is to the left so we're going to need to say uh array equals P minus and so we should theoretically in this binary search we should always get an answer assuming there's always amount and uh I test this before there is always a peak so we don't have to but if you wanted to you could write like return negative one or something here okay I think we have everything here let's just double check local variable array I guess this is left right so we don't have an infinite Loop although we might looks like we do okay so let's just double check this yes it's an infinite Loop for something small okay so let's just double check this so if length of numbers is one or if num 0 is less than nums one that means we know that we have a Peak at num zero so that part's fine if numbers one is greater than those two we would return that's also fine this is fine so if nums p is less than nums P plus one that means a lot of capacity P plus one that's correct otherwise numbers P has to be greater than numbers P plus one so if numbers p is greater than P that part is fine um yeah so let's think about what we did wrong oh yeah right so we have a right so we're assigning right but we're not our signing R so we just have a wrong variable name so you can see it's pretty efficient and for the time and space complexity let's think about that so obviously we did write an algorithm that right that runs in login time so that's pretty straightforward so that's going to be log n because it's just a simple binary search this is over one this over one in a binary search space as typical of a binary search most binary searches it's ob1 because we just have a left and a right parameter we don't have anything extra saved so that's going to be it for this problem hopefully you liked it like I said it's a common interview problem as you can see um so I would definitely encourage you to know it and I definitely encourage you to know the difference between this and the problem where you have just one Peak and like what are the different things you're looking for they're pretty similar but yeah so if you did like this problem please like the video and please subscribe to the channel helps grow it a lot and I will see you in the next one thanks for watching
|
Find Peak Element
|
find-peak-element
|
A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.
You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in `O(log n)` time.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.
**Example 2:**
**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
* `nums[i] != nums[i + 1]` for all valid `i`.
| null |
Array,Binary Search
|
Medium
|
882,2047,2273,2316
|
305 |
hi everyone welcome back to algorithm simplified this week we are going over number 305 number of islands 2. there's a hard level question in particular that uses union find data structure as its solution and it's definitely a prerequisite for this video that you understand at least what the union find data structure is so if you don't know what that is i provided a very useful summary video at the top of the description so if you'd like to check that out before continuing this video that would be the best option and also recommended is that you at least try number 200 number of islands since that is the prerequisite to this question right here okay without further ado let's get into the problem itself so basically this is what you're given three variables two of them are integers representing a dimension of a grid the other is a series of or an array of arrays uh each of these sub-arrays are too long of these sub-arrays are too long of these sub-arrays are too long each one with its own integer coordinate between 0 and m and 0 and n accordingly i write them as i j which represent some coordinate in the grid let's illustrate what this means in an example so let's say you're given m equals three and n equals three this means you start off with a three by three grid like so and to start off with all plots of your grid are going to be zero where every single zero represents water and one represents land so this is where you start with okay so afterwards after you start for every single position in position starting from the zeroth index all the way to the last we go step by step adding the land at position i j in positions to our grid so what does that look like for index 0 we start with that so that means at 0 we're going to update that into 1 and everything else remains the same this means at 0 we add a plot of land continuing forward okay pretend that's also 3 0 1 so that's going to be right here that's going to become a one everything else remains the same as the previous state and the one carries over from here so this is index zero this is index one and then here for index two i'm just going to do so this is one and this is two right here that's going to be updated to a one everything else carries over from before and this is the state of our grid after index two of positions and then following that for the last position update we're going to change the one at position to one into one as well so everything else remains the same and all these get updated to zero right so what the question asks so what you're expected to give as an output is an array of integers of the length of position so let's call this result so we're supposed to return an array with here you know four items each one representing the state of the grid in the corresponding uh corresponding index so for example here this points to this grid and what exactly we have to have in this result array is the number of islands and we define the number of islands as the number of ones that are or number of groups of ones that are completely surrounded by water horizontally and vertically so what this means is for example here this right here is one island because it is either surrounded by all zeros it's surrounded by zero vertically and zero's horizontally or it's out of bounds we also considered water so that is a proper island on its own there's one island right there here we have two ones connected together horizontally so and they are all connect aft they're all vertically and horizontally neighboring water on the outside so these ones right here are considered one island on their own so that's one island and here in index 2 we have one island here but since this right here even though it's diagonally connected it's not horizontally or vertically connected so this right here is a separate island on its own so we have one island here two islands here and finally for this last one we have one island here horizontally connected one island here and also one island here that's also on its own because vertically and horizontally it's surrounded by zeros or out of bounds so we have three islands and in the end we're going to return this so our task is to given m and dimensions and also these positions in the m by n grid we're supposed to return an array of length of positions that gives us the number of islands present at every single position corresponding to the result array index before we head into the solution here's something we need to consider so in number of islands 1 the predecessor to this question 305 one of the ways we could have solved it was using either bfs or dfs in fact i believe in that prior question bfs and dfs were actually quicker and better solutions however in our case can we do that well let's consider this case so let's consider that we have at some position i this following scenario in our grid so we have one two three four islands uh separate from each other all surrounded by water horizontally and vertically so here we have number of islands equals four but let's say in position i plus one we're tasked to add a plot of land or change to zero to one at position one then what happens well now all these plots of land are connected horizontally and vertically together meaning we decreased our number of islands from four to one meaning we decreased our total number of islands by three using one island this means that because we cannot strictly increase or remain the same with the number of islands as the positions change or as we increase the number of land plots added in we can't use bfs or dfs as the number of total islands can range anywhere from decreasing in three all the way to increasing in one it could be anywhere in between so this means no let's switch no we cannot use bfs or dfs but instead we have to use union fund and while union find is definitely an accepted way to go in this solution video i'm going to discuss union find implemented with rank and path compression which is going to give us a much more efficient time-wise solution time-wise solution time-wise solution and implementation of union find now let's see how we would solve this problem using union find with rank and path compression so the basic idea here is that we're going to treat each ij node or each ij in the grid as a node in some graphs in particular those graphs are going to be trees each tree is going to be an island so if you can imagine a root representative node as the parent the root parent of everyone else in the tree that would be one island right there and each island has one distinctive root or no representative so if the island just consists of one plot of land it's just going to be one node so using the same example i'm going to walk through the algorithm and the implementation so first we initialize some variables we initialize parents to be an array of size m by n and all containing negative one to start the parent of some grid position so of some node is negative one if it's an ocean and to start we have an m by n grid of only ocean plots so all negative ones make sense rank refer to the position or how close a certain node is to the top of a tree so if we had a tree like so the rank of this node would be greater than the rank of this node we're also going to initialize a count to be zero this is going to count how many islands we have at one time and then find and union methods are the same as you would expect from any other union find data structure except with our finds implementation we're going to use path compress so we're not going to care uh you know that we're going to hold exactly the parent above so let's say we had something like this in compression the parent of this node right here is ultimately going to be compressed to this node right here even though the direct parent is this so you'll see what i mean as i go through that and then union in union we're going to compare ranks to make our algorithm go faster and we also initialize a result array with the length of positions which holds in accordance to every single positional update how many islands we have at that very instance and also to note when i refer to id that's union find or find uh id of some i j in the grid is calculated by i times n plus j and this makes sense because if you have say an m by n matrix like so with x and y axis or it could be the other way around and we have some i j right here basically think about it as well we're going to have how many columns over well we're going to have i columns over because that's the x axis right and each column is of length n so that's i times n and within this column i times n right here we're going to have to move j up in order to reach i j so if you do the other way and do j times m plus i that's also a valid way to calculate the id though the id values will be flipped the other way around so just as long as you have one consistent way to hold your id either way works okay so let's run through our example right here so what we're gonna do is we're going to loop through every single position and perform the following so first let's start with our first position and that is zero right here and let's calculate what that id would be so that id of zero would be zero times n which is zero plus zero is equal to zero okay so first we plus one to the count if the ocean is at our current zero position well at index zero accordingly we could see that parent is negative one meaning that right there that plot is ocean and this makes sense because we start off with an ocean only grid so we plus one to the count since we added one plot of land then we update the parent's id equals the current id if it's at the ocean and it indeed is so we update it to b0 as you can see any as i said before any position or any index in parents that is ocean is going to be negative one but anything else is going to have a non-negative one value going to have a non-negative one value going to have a non-negative one value meaning it's a piece of land so here zero pointing to itself as its own parent means zero is the representative route for its island and this makes sense because right now our island looks like this with one node and no children okay so for left up right and down neighbors so as we can see above zero it's out of bounds so we don't care left is also out of bounds right and down are both within bounds but they are all ocean zeroes which means we're not going to union with anyone because there is no land beside it neighboring it horizontally and vertically to union with so we skip this part and then finally we're going to update the result at our current index which here we are at index 0 in positions to be the current count so we are going to have one right here great now we're going to loop through this again and i'm going to go a little faster because hopefully you understand what i'm doing now so now we're here at index one in positions with position zero one the id for position zero one will be equal to zero plus one which is equal to one and then we're gonna plus one if at the ocean and indeed it is at the ocean because it's a negative one in the parents so we're gonna add one to our account make it two and we're going to update the parent's id if it is an ocean so yes it indeed is an ocean we're going to update its id to be its own representative new node and then for left up right and down we're going to see if any one of them is a land plot within bounds and indeed we do see that zero is why because at zero's respective id which is index zero we have a non-negative one parent we have a non-negative one parent we have a non-negative one parent meaning that zero its neighbor is a plot of land so what this means is we need to use union so what union does is using find it finds a root id of d2 and that's very easy because we reach 0 and 1 right away itself right away so those are its own roots so then we use the rank to establish who should be the parent over the other well since right now for zero and one accordingly they're both of equal rank zero that makes sense because both of them are uh root nodes themselves to their own respective islands as of right now so we're going to make one have greater rank and then thus make that greater rank the parent node so in this case you could do this either way or i'm just going to make 0 the parent node so that means it's going to look something like 0 is this and then its child is 1. so that's one island and then i also need to update the rank so now we need to plus 1 to index 0's current rank to show that it has higher or closer to the root node than any other node so one is greater than zero now and since this union was successful so we did indeed find a union to merge this land onto then we need to subtract our counter by one and since for the other three positions in uh next to zero one we have no other land plots then we continue on as you can see we're going to update in position one our current count one all right next over we're looking at one two right here so what's the id of one two the idea of one two is one times n which is three plus two equals five so first we're gonna plus one count if the ocean is at our position well the ocean is at the position five right here so we gotta add one now see if say we were at 0 1 again then we shouldn't add this one because 0 1 is already a piece of land that was considered so that check right there is to make sure that no duplicate land ads occur okay and now we update the parent id to itself since it is an ocean so we make this five to represent the one two's respective id and then for up down left and right we check if any neighbors are land well up down left right of one two as of right now there are no lands they're all negative one for parents so we don't change anything to um to the total count and we just add the count to index two next over we are going to look at two one right here so id of two one is going to be three times two equals six plus one which is equal to seven so at seven you see that it is negative one that's an ocean plot which means we have to count one more piece of land and then we also update itself to represent the fact that it's its own piece of land so far and then we're going to go up down left right to confirm if it does indeed have any land neighbors no it does not so we don't union anything and then finally for the results we just update to our current account and now that we're finished we return the result so right before i head into the coding part of the solution if you've made it to this far in the video and you like the content you see please do consider subscribing and liking the video so that i can make better content for you without further ado the coding solution now i'm going to code out the solution in java and i'm going to give detailed comments as we go along and also give the time complexity at the very end even though it's in java the same logic follows for any other language so you can follow along no matter which language you're coding in so first let's get the logic down for the for loop or basically what we're going to try to do so first we're going to instantiate a instance of union find which we will declare it later and it's going to take in the parameters m and n then what we're going to do is well for the sake of simplicity i'm going to have a variable that's going to be representing the length of positions so that i can instantiate a result array i'll make it an arraylist with length p then afterwards we're going to use the same for loop logic as discussed previously so for some index starting from zero looping throughout all of the positions we are given we are going to add the element x corresponding to the positions we're going to add the result of something we're going to call place now this is going to be a method we're going to write inside the union file but you can also break it down here it really doesn't matter but the implementation is up to you and then we're going to return result at the end great so that's the basic logic for what we're going to do but the hard part is that we actually have to define the union find class so what we're going to do is let's write class union find and it's going to have the following variables once you hold parents it's going to hold the rank it's going to hold the count and it's going to have m and the dimensions of the grid and now for every instance we create it's going to take the m of the grid it's going to take the n of the grid and what it's going to do is we're going to set m and n accordingly and then we're going to make parents instantiate it to be the size of m times n and we're going to do the same thing for rank and remember that since in our implementation we make parents all negative one what we do is we're going to iterate through parents so we're going to make each one instantiate to negative 1 so that index zero and default value zero which java instantiates it two are not mixed up so parents i equals negative one and note for any other languages rank is going to be instantiated with all zero values so if you're in a language that needs to indicate what it's instantiated to instantiate it to zero okay so that's the i'm gonna find great so now what i'm going to do is i'm going to define methods we're going to need one method called find that's going to give us the so if we give it the position index it's going to give us the index of the root of the tree in return and we're also going to have a void so something that doesn't return anything called union which is going to take in two ids and in the end it's going to union the two lands with rank and then for the place method that we've defined right here what it's going to do is it's going to return the current count given a specific position i j so let's get to writing these functions so for find what we're going to do is we're going to use path compression so how do we know if we've reached the end of the tree as in we've reached the root representative well if the parents of the current position we are looking at is equal to its current position that means we're at the root but in order to compress it what we're going to do is we're going to check if it is not equal to the position index in other words we're still in a child node we're not at the very representative root node yet what we're going to do is we're going to make the parents of this current index we're looking at equal to find parents position index and what this does right here is next time we search for the parents of the position index or we're trying to find the root of the position index we don't need to go all the way up its parents so on so forth all the way till we reach the top all we're going to have to do next time we try to find the root of some index we previously searched is we're going to be able to directly access the parent the very root node so then at the end if it's the case that we've reached the top then we simply just return parents position index great and now what we're going to do with union is that well we're going to leverage the find method that we've defined here to find the root ids of these two id1 and id2 so int root index 1 is equal to find by and then int root index 2 is equal to find id2 and now the thing is if id1 and id2 so these two pieces of land nodes end up being part of the same island so ultimately meaning root index one and root index two are the same then we don't do anything we only bother merging them together we're unioning them together if they're not part of the same island already so if group index 1 does not equal root index 2 then we do something so what we're going to do here is use rank in order to make our algorithm more efficient if we didn't use rank well we could have simply just made any random one what could have been one it could have been two over the parent of the other forming ultimately one bigger tree with one subtree from the previous island but instead what we're going to do is we're going to use the checking of the rank so if it's the case that the rank of root index 1 is greater than the rank of root index 2 meaning that root index 1 has more children than root index 2 or more depth of children higher more height in island tree than the tree of root index 2 then we make the parents of root index 2 equal to root index 1. so in other words whichever root index node ends up having a greater height for the tree it's connected to is going to be the parent and here else if you know rank of root index two is greater than the rank of root index one so what if it's the other way around then we're simply going to flip it the other way around so we're going to make parents of root index 1 equal to root index 2. but what if it's the case that both of them are equal and this could be very likely if they both have the same depth or height for their connected trees so then what's going to happen is we're going to just make any one of them the parent over the other but whoever is maybe parent has to have their ranks changed accordingly and then since the root index one root index two have successfully been merged into the or union into the same island we're going to decrease the count of the islands by one well why does this rank make sense well this ranked check is very important for making sure that our binary trees are as short as it can possibly be because the higher the rank is the more layers or more heights we have after this root node so if we somehow always happens to be that we make an insanely long height tree from one node with a really high rank instead of balancing it out on either ends then we will have a very inefficient find algorithm so the rank is very important to shorten the time needed for find okay so what would a place look like well place leverages both find and union together so let's write it out i'm going to define into i as just the position zero of our given position and into j as position 1 for ease and basically if we have yet to encounter this ij land node then we first add one to the new island count and set the land node to its own parent to start so what this looks like is simply if parents of i times n plus j remember our formula for the id is equal to negative one that means it's currently an ocean plot right now we're going to increase the count by one and then we're also going to set itself to be its own parent because it's the oh it represents its own island representative node to start with but afterwards what we're going to do is we're going to compare it with all up down left right neighbors to see if it actually we need to union and update parents and also update count what i'm going to do is i'm going to define some directions in which the land nodes can be connected what that would look like is int array of array directions is equal to so we can go 1 0 meaning we can go to the left uh to the right we can also go to the left we can also go up and we can also go down now you can you don't necessarily have to define this array of arrays i just find that it's easier for me to understand because in this for loop right here what i do is for each direction in directions i create or i name i2 and i uh i2 and j2 as the variables for i and j of the new direction so i equals i2 equals i plus direction zero and j2 equals j plus direction one and then right here we're going to check if there are any adjacent land nodes and if yes we join the lands so if our i2 is within bounds so less than m and is greater than or equal to zero and our j2 is also within bounds because remember anything outside of bounds is automatically considered ocean so greater than or equal to zero and making sure that if it's the case that those checks have passed the parents of this i2 j2 is not equal to negative one meaning that it's a land node so if that's the case then we're going to union the i times n plus j so the position we're currently on with its neighbor that we're looking at so i2 times n plus j okay so that's our algorithm right now and let's give it a submit and great we're faster than 90 and less than 56 percent of memory you
|
Number of Islands II
|
number-of-islands-ii
|
You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s).
We may perform an add land operation which turns the water at position into a land. You are given an array `positions` where `positions[i] = [ri, ci]` is the position `(ri, ci)` at which we should operate the `ith` operation.
Return _an array of integers_ `answer` _where_ `answer[i]` _is the number of islands after turning the cell_ `(ri, ci)` _into a land_.
An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
**Example 1:**
**Input:** m = 3, n = 3, positions = \[\[0,0\],\[0,1\],\[1,2\],\[2,1\]\]
**Output:** \[1,1,2,3\]
**Explanation:**
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid\[0\]\[0\] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid\[0\]\[1\] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid\[1\]\[2\] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid\[2\]\[1\] into a land. We have 3 islands.
**Example 2:**
**Input:** m = 1, n = 1, positions = \[\[0,0\]\]
**Output:** \[1\]
**Constraints:**
* `1 <= m, n, positions.length <= 104`
* `1 <= m * n <= 104`
* `positions[i].length == 2`
* `0 <= ri < m`
* `0 <= ci < n`
**Follow up:** Could you solve it in time complexity `O(k log(mn))`, where `k == positions.length`?
| null |
Array,Union Find
|
Hard
|
200,2198
|
238 |
chances are that you have already tried this problem and you're wondering why you're getting a wrong answer how hard could it be you are given an array and you have to find the product of all the integers except that one number right well this is a really fun problem to solve and i really love it most of the interviewers do and in this particular video i will tell you why is that so hello friends welcome back to my channel first i will describe you the problem statement and we will look at some sample test cases next we will see the most obvious way to solve this problem and why there is a problem with it why are you getting that wrong answer going forward i will tell you an optimal way to solve this problem and then as usual we will also do a dry run of the code so that you can understand and see how all of this is actually working in action without further ado let's get started first of all let us try to make sure that we are understanding the problem statement correctly in this problem you are given an array of integers and you have to return me an answer array where each element is a product of all the elements except itself right so what does that actually mean let us look at our first test case we have an array 1 2 3 4 and you can see all of them are integers now you have to return me an answer array and it should have some elements but how do you get these elements so for the first element you need to find the product of all the other elements except itself that means a product of 2 3 and 4 right and that will be 24 so 24 comes in my first place for this next position i need a product of all of these elements except this middle element 2 right so in this case i will get 3 into 4 that is 12 as the answer in my third place i need a product of all the elements except the third place right so that will give me 4 into 2 into 1 and that is 8 for the last place similarly i will need a product of 3 2 and 1 and that is 6. so for that first test case this will be your answer based on the similar idea we have a test case number 2 as well right and in this test case also you will need to return me an answer array correct and this will also have 5 places the answer for this test case would be 0 9 and then 0. that is because if you are not at the third place no matter whatever multiplication you do you will get a 0 in between right and anything multiplied by zero gives you a zero right so all of these places have a zero only when you are at the middle element or the third place element you have to give me a product of all the remaining elements right and as you can see 3 multiplied by minus 3 will give you a 9 in fact so for test case number 2 this resultant array will be your answer now if you feel that you have understood the problem statement even better feel free to try it out first otherwise let us dive into the solution so what happens when you start to solve the problem it seems so simple right but why it is under the medium difficulty so the most obvious way to approach this problem would be let us say i have this area with me 1 2 3 4 so the first thing that comes to my mind is okay i have to find the product of every element except self so my first intuition is that okay i will take a product of every integer in the array and then what i'm going to do is when i will create my resultant array i will just divide every number from this result right so that will give me 24 divided by 1 24 divided by 2 24 divided by 3 and then 24 divided by 4 right and this in fact gives you the correct answer right but when you try to write the code for it you will see that your code fails right you will get a wrong answer so why does that happen well the primary reason why this is happening is because the problem has a certain condition it says that all of these products will fit in the numeric range of 2 to the power 32 so when you expand 2 to the power 32 this is the maximum integer that you can get right so now try to think about it when you are creating a product of all the integers in an array it could be possible that your product gets above this limit and if it gets above this limit it will fail it will give you a wrong answer for example let us look at this test case i have three integers with me and they are 10 to the power 4 10 to the power 3 and 10 to the power 5 correct so technically when i will be solving this problem what will be my answers in the first place i will get 10 to the power 8 in the second place i will get 10 to the power 9 and in the third place i will get 10 to the power 7 right because of all of these individual products right and if you see all of these integers are lesser than 2 to the power 32 right so this in fact is a correct test case and the correct answer but what happens if i try to apply this original approach to my problem when i try to multiply all of these numbers i will get 10 to the power of 12 correct and if you see this 10 to the power of 12 is greater than 2 to the power 32 right and that is why this will fail and you will get a wrong answer so this is one kind of edge case that you have to take care of the other case happens when there are zeros involved in the array for example i have this other test case with me right so what happens when you try to approach this problem in the same way of taking all the products as soon as you take all the products you will get a 0 as the resultant product right and how do you divide it now 0 divided by anything will be a 0 and 0 divided by 0 will not be a definite answer correct so once again this approach will fail so you have to handle all kinds of these special test cases right sure if you try to find a lot of if conditions and if you try to somehow skip all of these edge cases yes you can get a correct answer even with this approach but then your code starts to look a little ugly and that is not a recommended approach so what is your interviewer expecting what kind of a solution should you come up with let us take a look at it now okay so let us take up our sample array once again this time i have five elements right and the resultant output for this particular array will be this resultant array right so sometimes when you're trying to find an optimal solution just look at the input test case and the output that you're expecting and try to work out in the middle so technically or theoretically what you are doing over here you are multiplying every element in here right and then you get 144 as your total product right but you have to find out the integer except itself right so what you do 144 divided by 3 and that will give you 48 right you do 144 divided by 4 and that will give you 36 correct this is the approach you are taking but if you try to approach this problem in a more logical way and if you try to think a little bit out of the box there is a neat little trick that is hidden in the problem so let me consider 4 over here right when i look at 4 how do you obtain the result for it you multiply 3 on the left and then you multiply 6 1 and 2 on the right correct so this will give me 3 and this will give me 12 over here right and then to get my final output i do a 3 into 12 and that gives me 36 correct similarly let me look at 6 this time what are the elements on the left i have 3 and 4 and on the right i have 1 and 2 correct so what i will do is i will multiply all the elements on the left that is 12 and i will multiply all the elements on the right that is 2 correct and then to get my final output i will multiply the left and right values so 12 into 2 and that will give me 24 right so this kind of gives us a very neat little trick what we can say is the result at the ith position is equal to the product of all the elements on the left into product of all the elements on the right correct and to verify this what we can do is we can try to create two products a left to right product and a right to left product so first of all we will move left to right and then we will move right to left and make all the products so let me first start going from left to right i start from the very first element that is 3 i do not have any element to the left of it so we move ahead now i move at four right i have only one element to the left of four right so i will write down three over here correct now move ahead now i encounter six what do i have on the left i have three multiplied by four so i will write down three multiplied by four over here next i move to the next position then on the left i have three four and six so i'm gonna write down 3 into 4 into 6. moving ahead i have the element 2 and all these four elements so we are done with one part now the second part is going right to left so once again start over here there is no element to the right of two so i will leave this place empty moving on i come at one i have only one element to the right of one correct and that is two so i just write down two in this position moving ahead at 6 i have 1 and 2 so i will write down 1 multiplied by 2 over here then coming at 4 i have 6 1 and 2 and for the last place 3 i have all of these 4 elements as soon as you evaluate these results you get all of these new values correct and now to derive your answer what you need to simply do is just multiply all of these values because technically what you are doing is you are taking a product of all the integers on the left and a product of all the integers on the right so you can easily see that these are forming your result answers and this way you can solve this problem very efficiently now let us quickly do a dry run of the code based on this concept and see how this actually works on the left side of your screen you have the actual code to implement this solution and on the right once again i have a sample array that is passed in as an input parameter to the function oh and by the way this complete code and its test cases are also available on my greater profile you can find the link in the description below moving ahead with our dry iron what is the first thing that we do first of all we create two areas to store all the left products and all the right products correct now what you need to do you need to start traversing your original array right and first of all we will fill all the elements in my left array and then what i'm going to do is i will fill all of these elements in my right array as well for the left array i will start from the first position and go all the way up to the end because the first position do not have any element to the left and for filling my right array i will start from the second last position and go all the way to the beginning right so when i run these loops and i fill both of my arrays they start to look like this correct once you have formed both of these areas the last step is to just multiply both of these values right and that is what we exactly do in the final step i will create a new answer array and in this array i will just pick up each value from the left array and multiply both of them if it is blank i treat it as 1 because of multiplication with 0 will give you a 0. so what i just do is i multiply all of these values and i will start getting my final output so you can see how easily and efficiently we are able to arrive at our solution this array is now ultimately returned as your answer the time complexity of this solution is order of n because we are only doing two iterations of the array and the space complexity of this solution is also order of n because we are taking some extra space to store our final output i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say that these kind of problems do not test your coding skills specifically think about it there is no code involved right it is just about the logic and that is why interviewers will try to ask this type of a question they are trying to judge how you can look at the problem and what kind of a logic are you applying because most often complex problems like these can be broken down into very simple parts and as a good programmer and as a good problem solver you should be able to do that so tell me what other problems did you find which are more about your logical thinking and not about the coding skill tell me one such problem in the comments section below which you have found in your interviews also tell me if you faced any problem with the approach that i had tell me everything in the comment section below and i would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more such videos where i can simplify programming for you also let me know what problems you want me to follow next until then see ya
|
Product of Array Except Self
|
product-of-array-except-self
|
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
| null |
Array,Prefix Sum
|
Medium
|
42,152,265,2267
|
1,850 |
hello guys today we are going to see the DAT for question 1850 that is minimum adjacent waps to reach the K smallest number you are given a string num representing a large number and an integer K we call some integer wonderful if the permutation of the digits in Num and is greater in value than the num there can be many wonderful integers however we only care about the smallest valued ones so here this is a num which is a string given over here and a k value is given that is the number of next permutations we have to find so if four is given as the here uh 4 k = 4 is four is given as the here uh 4 k = 4 is four is given as the here uh 4 k = 4 is given in the example so four next permutations are found what do you mean by next permutation if 1 2 3 is present then it next permutation would be greater than the 1 2 3 that is 1 3 2 this would be the next permutation and we would be using the buil-in next we would be using the buil-in next we would be using the buil-in next permutation in C++ so after uh permutation in C++ so after uh permutation in C++ so after uh taking four or after using that four number of times that uh next permutation we would be getting this number and after that we would be comparing uh the original num with the final num that we have so after comparing if both are equal then we have to just continue and we have to find the first element in which they are both different then we have to move till the last element or till the last ele up to the last element uh in which both the element are different to the same corresponding index then we have to iterate from the last suppose will reach the last um number then we have to iterate till the point where you have got the first number uh first distinct number in both while comparing this both the uh num and the final answer that we get then we have to swap them and increase the count then we will get the number of times the swap is minimum number of times the swap is needed so let us see the code of the question here is the code of the question first we have taken the string original as the uh as because the permutation next permutation will result in the change of the original num so we have taken a temporary variable to St the num and answer uh we have initialized with zero until the K is minus that is given in the question we have to find the next permutation and we will be reaching the uh K times after applying the next permutation then IAL to 0 Jal 0 is taken and the num length is taken till I is less than SJ we have to make that J is equal to I and we have to check if the original number and the non number are both equal then we have to increase the j++ and along with it if I is less than j++ and along with it if I is less than j++ and along with it if I is less than J this will only be possible if this condition is violated at least once then I and J would be different otherwise I would get implemented similarly as J and the first element in which we will get that I less than J and in or this condition will get satisfied then till I less than J we have to swap num J and num J minus one and we have to decrease the J and make create a count variable or increase a count variable and finally we have to return the answer thank you
|
Minimum Adjacent Swaps to Reach the Kth Smallest Number
|
minimum-length-of-string-after-deleting-similar-ends
|
You are given a string `num`, representing a large integer, and an integer `k`.
We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones.
* For example, when `num = "5489355142 "`:
* The 1st smallest wonderful integer is `"5489355214 "`.
* The 2nd smallest wonderful integer is `"5489355241 "`.
* The 3rd smallest wonderful integer is `"5489355412 "`.
* The 4th smallest wonderful integer is `"5489355421 "`.
Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_.
The tests are generated in such a way that `kth` smallest wonderful integer exists.
**Example 1:**
**Input:** num = "5489355142 ", k = 4
**Output:** 2
**Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number:
- Swap index 7 with index 8: "5489355142 " -> "5489355412 "
- Swap index 8 with index 9: "5489355412 " -> "5489355421 "
**Example 2:**
**Input:** num = "11112 ", k = 4
**Output:** 4
**Explanation:** The 4th smallest wonderful number is "21111 ". To get this number:
- Swap index 3 with index 4: "11112 " -> "11121 "
- Swap index 2 with index 3: "11121 " -> "11211 "
- Swap index 1 with index 2: "11211 " -> "12111 "
- Swap index 0 with index 1: "12111 " -> "21111 "
**Example 3:**
**Input:** num = "00123 ", k = 1
**Output:** 1
**Explanation:** The 1st smallest wonderful number is "00132 ". To get this number:
- Swap index 3 with index 4: "00123 " -> "00132 "
**Constraints:**
* `2 <= num.length <= 1000`
* `1 <= k <= 1000`
* `num` only consists of digits.
|
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
|
Two Pointers,String
|
Medium
| null |
881 |
you must have solved these kind of problems when you were young there are a certain set of individuals who either want to cross a river or they want to cross a bridge correct and then there are these certain conditions that you must satisfy and then come up with a solution right so there is one such problem on lead code which explores around a similar concept let's see what we can do about it Hello friends welcome back to my Channel first I will explain you the problem statement and we will look at some sample test cases after that we will look at a Brute Force solution and see why it ends up taking so much time going forward we are going to use the greedy approach to find an optimal solution and then as 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 us try to make sure that we are understanding the problem statement correctly in this problem you are given an integer array that has the weight of certain people so for example if you have this particular test case then it has four elements and each of this element is signifying an individual and then each of this element it is telling me the weight of that particular person so you can assume that the weight of first person is 3 Kg then 2 kg and then again 1 kg right and after that you are also given a maximum weight limit so the maximum weight limit over here is three so there are a lot of boats available and then these people have to use these boats the maximum weight a boat can accommodate is this limit so if I have a boat like this the maximum capacity of this boat is 3 Kg and you are also given a condition that a boat can have a maximum of two people right so it simply means that if I have a boat like this its capacity is 3 Kg right now in this boat I cannot have two people of the weight two each then this boat will thinkink the maximum weight is three so in my boat I can either have one person of three or I can have two person of 2 kg and 1 kg right so you can see that there are a lot of different combinations by which you can transport people you want to tell what is the minimum boat required such that you are not wasting any boats so what happens for the first test case look at this example there are two people and one of them has a weight of 1 kg and the other one has a weight of 2 kg correct so now when you will start to take boats I have one boat with 3 Kg capacity and now I can put both my people in this boat right so they are both happy the boat does not sink and then you can say that okay you needed one vat so one is your answer correct moving on now I have my second test case in my second test case let us take up a boat okay and now once again the capacity is 3 Kg so if I put this first person in my boat then I am at the maximum limit I cannot have more people right so I will have to end up taking one more Port as soon as I take up one more Port now I can add one person over here right I still have space and still have the capacity so I cannot put two over here because then it will again be 2 + 2 4 because then it will again be 2 + 2 4 because then it will again be 2 + 2 4 and it will be more than three I can put one right so this becomes one scenario so now I have used two boats but I have one person remaining correct so I will take up one more boat and this person sits over here so what do you get this time you need a minimum of three boats so for your second test case also three is the answer correct let us look at the last test case now in this example the limit of the boat is 5 kg correct but if you notice I cannot place any two persons in the boat as soon as I pick two people the weight becomes greater than five right so 3 and 5 is 8 3 and 3 is 6 3 and 4 is 7 right there is no combination by which I can fit more than one people in the boat so in your last case you will have to be taking four boats at the minimum each person is going in their individual boat that is because the boat does not have the weight limit to accommodate two people so in your last test case you will need a minimum of four board and four is your answer right so that is what you have to do you have to tell me the minimum number of boots correct now how can you go about approaching this problem to start with a Brute Force approach let us take up a more generic example this time I have a bigger array and even my boat limit is high I can accommodate 12 kgs in total so if you have to start off with the Brute Force approach what can you do you can say that okay I will start off with the first person and put it in the boat now the first person is in the boat and then what you will do you will try to find the second person that you can fit can you put two in there no because 11 + 2 you put two in there no because 11 + 2 you put two in there no because 11 + 2 will become 13 and it is greater than 12 so once again what you will do you will try to look at the next person possible 11 and 9 they also cannot go can 11 and one go yes because the limit is 12 so this completes one of your boat similarly now you will start your second boat and you can again repeat the same process you will try to fit in two and then you will try to fit in nine they both can fit in the same boat and you can proceed ahead so this is a Brute Force approach of doing things but you can see that it can end up taking a lot of time because you have to keep on itating again and again to find out the best possible combination for whichever your first candidate is right and it ends up taking so much time you will have repeated Cycles correct so certainly we want some better approach by which you can minimize the number of vots because think about it right now you are not even sure that the boats you will have that will be minimum it could be possible that you will get minimum boats when you start with three and then go in this direction right so this approach is not deterministic let us see how we can use the greedy method to attack this problem once again you have the same array in front of you and just keep in mind what is your target you want to have the minimum number of boats correct and when do you need more number of boats when you have a lot of heavy people think about it if your boat capacity is 12 and all the people in the group have a weight of 11 kgs then in no case you can ever have two people in the boat correct and similarly if you have a lot of light people for example if all the persons in the group have a weight of 1 kg then in every boat you can fit two people correct so it all depends on how many heavyweight people do you have in the group so that gives you one clue so what we can do is we can try to sort the array by sorting I am sure that all of the lightweight people will be on the one group and all of the heavyweight people will get on the other group and then we can proceed ahead and what just happened I am getting all of the lightweight people over here and all the heavyweight people over here so try to think you have to transport all the people correct that is no exception and all the heavyweight people will also have to go so what we can do is we can start off with the heavy person my heaviest person has a weight of 12 kg correct so I place him in the boat as soon as I place him then I check hey do I have any more capacity available right I do not have any more capacity so this boat is now full just remember that this is the best case it can never be possible that you can have any more person sitting with this 12 kg person correct so this has to be always there so this is where we are being greedy we are starting off with the heaviest person possible and now what happens I took care of the person with the weight 12 kg time to pick another boat now once again what I will do is I will start off with the heaviest person available I now have 11 kg person available so I put him in a boat as soon as I put him try to think the limit is 12 so what I will do I will ask from the group hey is there any person with a weight of 1 kg so since you have your array already sorted where will you find the lightest person you will find the lightest person from the left side correct so that is why we had sorted our array and now what we can do is we can take one lighter person and put it in the boat your boat is now full and now you can take up another boat once again we will follow the same approach take this person with the weight 10 kg and put him in the boat so he is over here and now you still have some weight remaining so try to fill up a lighter person and you will find the lighter persons on the left so I will take up this person with 1 kg and put him in the boat again we go ahead and take up another boat follow the same approach take the heavier person and now fill up with a lighter person so you start from the left you find a two and put in the boat I am now left with just one more person and this person also goes in the boat and VOA all of the people have now been transported we needed a total of five boats based upon this approach let us quickly now do a dry of the code to see how it works in action on the left side of your screen you have the complete code to implement this solution and on the right once again I have my array and this limit which is passed in as a input parameter to the function number of rescue boards the first thing that we do is we sort our array as soon as you sort this array you get your array something like this all of the lighter people are on the left side and all the heavier people are on the right side and we are going to take advantage of this fact what do we start off with a two-p pointer do we start off with a two-p pointer do we start off with a two-p pointer approach we have a left pointer which starts at zero and the right pointer starts at 12 also I initialize a variable boats that is set to zero right now we haven't taken up any boat correct next what you do is you run a while loop and this while loop will run until your left pointer is behind the right pointer because that is when we know that okay we need to stop so now what do you will try to put the heaviest and the lightest person on the same boat correct so we will try to see okay 12 + 1 that so we will try to see okay 12 + 1 that so we will try to see okay 12 + 1 that is 13 you cannot not fit both of these people in the same boat so what do I don't do a left Plus+ I will just put I don't do a left Plus+ I will just put I don't do a left Plus+ I will just put this person 12 in the boat and then move ahead because this person cannot be paired with anyone so this right pointer moves one step backward and this person occupied a boat correct so we will do boats Plus+ so this is telling me that boats Plus+ so this is telling me that boats Plus+ so this is telling me that okay I took care of one person and I have taken one boat up till now notice that I haven't picked up any person from the left side this Loop will now run again and this time what do we try to put the person 11 and the person with the weight one in the same boat this 11 + 1 it is less than equal boat this 11 + 1 it is less than equal boat this 11 + 1 it is less than equal to 12 correct so they can come in the same boat what does that mean I can easily move my left pointer also one step ahead because one person got in the same boat and the right pointer will anyway move one step backward because a heavier person went in the boat and no matter what the case I took up additional boat so I do a boats Plus+ up additional boat so I do a boats Plus+ up additional boat so I do a boats Plus+ so this way this Loop will go on and these pointers will keep on advancing one step ahead as soon as they reach a common point this Loop will stop and at the end you will return the total number of boats required the time complexity of this solution is order of n log n because you need that time to sort your array that is the only time required when you are doing the traversal that happens in order of end time correct and the space complexity of the solution is order of one because you are not taking up any extra space to arrive at your solution I hope I was able to simplify the problem and its solution for you as for my final thoughts I just want to say that this problem can be converted into a very generic problem for example right now you have had a maximum capacity of the boat to be two correct what happens if this capacity is not defined what happens if you're only given a limit then you can put any number of people in the boat right and suddenly the entire question changes the approach may also change you can also have a limited number of votes so there are all of these variations and it is not necessary that one approach will also apply to the other question as well so just keep that in mind while going throughout the video did you face any problems or what other variations of this problem have you already seen tell me everything in the comment section below and I would love to discuss all of it with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also a huge shout out to all the members who support my channel you guys really keep me going and as a member you do get priy reply to your comments as well stay tuned for my next video Until then see ya
|
Boats to Save People
|
loud-and-rich
|
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`.
Return _the minimum number of boats to carry every given person_.
**Example 1:**
**Input:** people = \[1,2\], limit = 3
**Output:** 1
**Explanation:** 1 boat (1, 2)
**Example 2:**
**Input:** people = \[3,2,2,1\], limit = 3
**Output:** 3
**Explanation:** 3 boats (1, 2), (2) and (3)
**Example 3:**
**Input:** people = \[3,5,3,4\], limit = 5
**Output:** 4
**Explanation:** 4 boats (3), (3), (4), (5)
**Constraints:**
* `1 <= people.length <= 5 * 104`
* `1 <= people[i] <= limit <= 3 * 104`
| null |
Array,Depth-First Search,Graph,Topological Sort
|
Medium
| null |
52 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem n queens2 now we did already solve the first one on this channel and i would say that this one is actually a little bit easier than the first one so i do recommend checking out the first video as well if you want to and this problem is very similar to the first one i would say it's like 90 identical so the problem is again about the end queen's puzzle which is a given an end by end board now the dimensions could be anything in this case you can see it's four by four we want to place then four queens whatever n happens to be in such a way that none of the queens attack each other now if you're not familiar with chess a queen it can basically move in any of the four horizontal and vertical directions for an unlimited amount of spaces and it can also move diagonally top right top left bottom right so our goal is to place the queens on the board such that they're not attacking each other you can see that for a board of four by four we can do that two different ways so in this problem we want to return the total number of distinct ways that we can satisfy this puzzle in the first problem we actually had to create the board for each of the possible ways but in this case we just have to count them so you can see that in the first solution we were returning the unique solutions in this case we're just counting them so you could actually just take the first solution take the length of the output right and then return that but i'm going to explain this from scratch and then code it from scratch logically this problem is a backtracking problem because we kind of have to brute force it and when we do brute force it we think about it in terms of choices let's say uh to make things simple for us we're picking on the first row we're placing a queen on the first row right because what we're trying to do is just generate every single combination of how we can place queens and try to place them such that they're not attacking each other do it for the first row do it for the second row do it for the third row do it for the fourth row if we're able to make it to the fourth row and there is a valid position that we can place the queen then we found a solution and we can increment our result if we don't find a solution then we don't increment the result but the goal is to find all possibilities and to make sure that there aren't any duplicates and the way we're going to do this backtracking it's actually going to eliminate duplicates by default let me show you how so first row we have to pick a position for the queen let's say we just start with the first one now second row we have to pick a position for the queen but also before we get to the second row we know now that we can't place another queen over here so before we get to the second row we're kind of just going to take that out of consideration we're going to remove that and since we're going row by row we don't really have to eliminate these positions even though technically they have been eliminated from consideration because we're going row by row but now as it comes time to choose a value in this row we can pick any of these three let's just pick the first one for now and then afterwards after we generate the possibilities doing it like this later we'll backtrack reverse this decision and then try all combinations that start like this and then try to generate those valid ones but since that was eliminated we're also now going to eliminate this from consideration actually i just realized this is a good point to talk about the diagonal case yes these are not uh attacking each other horizontally and vertically but diagonally they are so actually turns out we can't put a queen over here now it's pretty easy to detect horizontally and vertically right for this uh queen was placed at this column so we're just going to eliminate all future uh possibilities at that position in this column but for diagonal it's not so straightforward but there actually is a clean way to do it diagonally as well and that's kind of the trick that you have to know it's really hard to come up with this kind of trick but when you do it makes the code a lot easier it is possible to kind of do it without this trick let me just show you this queen is placed at this position right this position is row zero column zero now if we go diagonally in this direction and i call this the negative diagonal but you can call it whatever you want if we go diagonally like this we're gonna go to the right by one and then down by one when we go to the right by one we're increasing the column by one when we go down we're increasing the row by one so notice how the difference between these two values is always going to stay the same let's say we're doing it row minus column we're going to get zero minus zero that's zero we're gonna get one minus one that's zero we're gonna get 2 minus 2 as we go you know diagonally let's say from this position we're going to get 0. now if our queen was actually over here you can see that's again going to be true here we have 0 minus 1 let's say that's negative 1. here we're going to have one minus two that's negative one here we're gonna have two minus three that's negative one it's gonna be the same idea uh but one the negative diagonal is not all like suppose from here we actually also have the left diagonal i'm gonna call this the positive diagonal because you know going in the other direction it shows like a positive line but again you can call it whatever you want but in the positive diagonal it's gonna sort of be a little bit different because here you can see okay we're at row zero column two when we go left diagonally we are decreasing the column by one and we're increasing the row by one so it's not that the difference between these two values is going to be the same as we go a left diagonal it's actually that the sum of them is going to be the same because as we move in this direction we're incrementing one of them but we're decrementing the other so that means that the sum of them is going to stay the same not the difference so it's the kind of opposite but the idea is still the same so here zero plus two is two go to bottom left 1 plus 1 is 2 go here 2 plus 0 is 2. so that's the main trick that you have to know after you know that trick this problem becomes a basic binary search problem so we're going to eliminate all the right diagonals for this eliminate that and eliminate that we're also going to eliminate all the values in this column there's no left diagonal so don't have to eliminate them so now we have two possibilities to choose from this row we're gonna uh let's try this position okay so we're gonna eliminate all uh you know values uh you know positions in this column and technically you know we're eliminating that as well and just uh for clarity i'll say that we're eliminating the values in this row as well also we're going to eliminate the right diagonals right going this way so that's not a possibility and we're going to eliminate the left diagonals that's not a possibility notice now how in the third row we can't put the queen anywhere so we have to backtrack we have to say that we made a mistake we can't get any solutions with this so now let's consider if we put the queen over here i'll just fast forward and tell you that this won't lead to a solution either you can tell that by you know looking over here but generally i think you probably get the idea of what's going on with this algorithm a thing to notice though how we're not ever going to have duplicates with this is because just the nature of backtracking every time we reverse we're making a new decision that's never been made before we might have multiple solutions where a queen goes for example in this position but if that is the case it must be because this uh queen was you know placed somewhere else instead of placing it here we put it over here and that led to a different solution that's the main idea though in this case the upper bound for the time complexity uh is roughly uh let's analyze it so every time we go through a row we can choose between n uh positions where we can place the queen the next one will be n minus one uh positions etcetera so that is ultimately i think n factorial uh so that's how many different uh possibility possible board situations with the queens we could have now to build each one of them we have to put place a queen n times so i think the time complexity is n factorial times and that's the upper bound for the time complexity okay now let's code it up and the first thing i'm going to do is actually create a couple hash sets and these are going to be used to make sure that we you know how we eliminate possibilities from the board for example this column set is going to tell us which columns we've already placed a queen in so that we don't place another queen in the same column unless we of course backtrack and then remove that queen the other sets are going to be for the positive diagonal and the negative diagonal remember that the positive diagonal is defined as when r plus c are constant as we're going bottom left and negative diagonal is defined where r minus c are going to be constant as we go in the bottom right direction so i'm going to create a variable of variable for our result i'm going to additionally set it to zero and the way i'm going to implement the backtracking actually is going to be in a nested function so that and the only parameter we're really going to pass in is the row that we're in so the base case for this backtracking is if we reach the last row or rather we've already gone through the last row so r is equal to n which means we're kind of out of bounds here if that's the case though if we even get that far that pretty much means that we found a valid board and when we find a valid board we can increment our result it's not in this function so you have to use the keyword non-local you have to use the keyword non-local you have to use the keyword non-local this means that we're not referring to a local result variable we're referring to the outer variable and i'm just going to increment result by one and then we're gonna return otherwise if we don't have a valid board we have to continue to build the board sort of and so what we're gonna do now is go through every possible column that we can so let's say c in range n of course though we know that there's some positions in uh that we've already used uh possible columns so what we're going to say is if call this column is not in the set of columns that we've already used before and if this is not on the same positive diagonal that's already been used before so if r plus c is not in positive diagonal and this is not a part of the there's a typo uh this is also not a part of the ones that have been used in the negative diagonal so not in negative diagonal uh actually to make this simple we could say that if it is in any of those uh if oh basically we are in a position that we're not supposed to be in for this queen we're going to continue to the next iteration of the loop we don't want to place a queen in any of these positions uh one thing i kind of noticed is since in this column we're not actually automatically skipping the possible positions uh like this loop will iterate n times each time so it's the technically the time complexity i was talking about is not necessarily n factorial it is actually going to be n to the power of n the way i'm coding this up but after that if statement we know that we are at a valid position so at least so far and we're going to continue backtracking to the next row so r plus one but before we even do that we remember we have to update our sets before we make that recursive call so to the column i'm going to add the current column to the positive diagonal set i'm going to add a new value that's not already in the positive diagonal set which is r plus c we're now using this particular positive diagonal line so that the next queen cannot be placed on this same positive diagonal let's do the same with the negative diagonal add our minus c and then after those we're going to do our backtracking after our backtracking is done we're going to basically do all three of these and reverse them instead of adding the column we're going to remove the column and same with the other ones and that actually is the entire code for the backtracking so the only thing left for us to do is call the initial backtrack function starting at row 0 let's say and going up until our base case which is n and after calling backtracking we know our result variable is going to have been updated so let's go ahead and return that actually and one thing i forgot about when we were doing uh this conditional is so if our column has already been used before or the positive diagonal has been used before or the negative diagonal has been used before then we want to skip this position but we have an and on all of these if any of them are true we want to skip it so let's make sure we change these ands to ors i'm really sorry if that caused any confusion okay now let's run the code to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
N-Queens II
|
n-queens-ii
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9`
| null |
Backtracking
|
Hard
|
51
|
1,456 |
problems on the sliding window algorithm are really fun to solve that is because you can actually see how the window is sliding and how are you coming up with the solution one such problem is finding the maximum number of vowels in a substring of a given length so let's see what we can do about it Hello friends welcome back to my channel first I will explain the problem statement and we will get some sample test cases going forward we will start with the most obvious solution and then try to optimize our solution and look at how the window is actually sliding after that we will also do a diagram of 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 talking about the problem statement I feel that it is pretty straightforward you are given a string and you have to find out the maximum vowels you can find in a substring that has the length K so what does that mean for example I have this particular test case right the value of K is 3. this string can have a lot of different substrings with the same length 3 correct so for example ABC is a substring of length 3 then IDE is also a substring of length 3. similarly you have all of these different substrings which have the same length 3. and out of all of these substrings you have to tell me in which of them you can find the maximum number of vowels and you just have to tell me that hey these are the maximum number of vowels that I can find you don't have to identify the string itself so for the first test is you can see that this substring III this has a length of 3 and you can find three vowels right there cannot be more than three so for the first test case 3 will be your answer similarly when you look at your second test case now if you notice all of these characters are vowels right but the value of K is 2 that means you can choose a substring that has a maximum of two characters so no matter whichever substring that you pick you will get a maximum of two vowels right so for a second test case 2 is your answer similarly if you look at the third test case the value of K is 4 and if you notice there are two such strings u d y a and a l g o both of them have the length 4 and both of them have two walls right so you can choose any of them because you don't have to tell me which substring has the maximum number of hours but how many hours did you find you found a total of two vowels in your maximum substring right so for the third test case 2 will be your answer so if this makes the problem statement a lot more clear feel free to stop the video right over here and try the problem on your own otherwise let us type into the solution let us say you have the sample test case the value of K is 3 correct now if you think about the problem what is the most obvious way that comes to your mind the most obvious and The Brute Force solution would be that okay you start finding out all the substrings so this is my first substring ABC and out of this string how many are vowels all of these are vowels right and only a is a vowel so in the first substring you could just find a maximum of one vowel right so you just record that okay I found one vowel in this moving ahead what you can do is now start from the second character and then find a substring of length three now how many vowels do you find you once again find just one vowel so you can once again record this value similarly what you're gonna do is now start with the third character and then once again get a substring of the length 3. so this time my string is CII right and how many vowels you can find a maximum of two vowels so once again you will record this value so basically what you are doing is you start from each character one by one and try to find a substring and then you will keep on doing it all throughout the entire string correct once you are done with your complete iteration you can check which value was the maximum and then yes that will be your answer right so this method works and in fact correct answer but do you see the problem with this approach every time you are trying to calculate your substring right and for every substring you are again trying to find out okay how many are vowels how many above us so this ends up taking a lot of time and this is not what we desire certainly we can try to come up with a better approach so let's see what we can do about it once again I have my sample test case over here right and the value of K is 3. to start thinking about an optimal solution first try to analyze what was the problem in the Brute Force approach in a last approach we were every time calculating a new string right and that was taking up a lot of time if you think about the problem a substring of correct and all of these characters they will be contiguous right so it is guaranteed that you are only looking at three characters at a time this kind of gives me an idea that a sliding window algorithm might be helpful over here if you're new to sliding window algorithms you can also check out my introductory video over there that will really help you to understand what does a sliding window algorithm actually looks like so let me take up a window right so this window is telling me that I am looking at only three characters at a time correct just ABC and what else you have five hours right so I take up a hash fit and I add all of these vowels to my hash fit ensures that I will get a Time complexity of order of one because you can look in the headshot in a constant time correct for how do they proceed ahead first of all I look at my window and then I check hey how many of these characters are vowels I check that hey if a vowel yes if B a vowel no if c a vowel no so in my first window how many vowels did I have I just had one vowel correct so I just store this value over here now what you're going to do is you will simply slide your window and by slide I literally mean slide phone is a slide what happens your new character is I correct so check if I a vowel yes you can find it over here so what I simply do is I increment this value now my value is 2 but wait a minute also removed a certain character right and you need to check hey data remove a vowel so once again you look in your hash fact that is order of one time complexity correct so you can say that hey I removed a vowel so once again just decrement discount and you will say that hey I can still find just one vowel in my window now simply keep on moving this process ahead take this window and slide it one step ahead as soon as you slide it what is the next character you get an i again you check if I a vowel yes so what I will do I will increment this value at the same time you will check which character did I remove I removed a B and B is not a vowel so this value remains constant and this is 2. so as we are sliding this window kick off how many maximum vowels are you able to find up till now you have found a total of two hours right so similarly just keep moving ahead slide this window one step ahead as soon as you slide it what character do you see u v and I is also available for you and at the same time you will update this value and it becomes a three what happens next If You observe the value of Max vowels has now reached 3 and the value of K is also three so if you drop over here because if you ahead you will never have a value greater than this right that is greater than K so if you are writing the code you can simply add a condition and stop over here but just for learning purposes you can try to analyze what happens next so what happens when I slide my window one step ahead I add a new character d right so if d a vowel no it's not so do not do anything with this value as of now but at the same time look at what character are you removing you are removing an eye so this tells you that you are removing a vowel so decrement this value by one now you check if 2 greater than 3 no so you do not have to update your max vowels so basically what you're doing is as you are sliding your window ahead encounter a vowel just increment this value and at the same time if you are removing a vowel then decrement this value by one just keep on moving ahead and keep a track of the maximum value that you are getting once you are done this will be your answer so you can see how in just one pass using the sliding window algorithm we were able to arrive at an efficient solution now let us quickly do a drawing of the code and see how it works in action before moving ahead I would just like to say that if you do like my content consider joining my channel and becoming a member it really supports me to keep on bringing all of this quality content to you let's get back to it on the left side of your screen you have the actual code to implement this solution and on the right I have a value of K and a sample string that is passed in as an input parameter to the function Max flows now moving on with the driver what is the first thing that we do first of all we create two variables that will store our values Max vowels and the window walls right now both of them are zero right because we haven't done anything Max vowels is gonna store what is the maximum number of hours are you able to find and window Walkers are gonna store how many vowels are you able to find in the current window for moving ahead my next step is obviously to create a hash fit this hash fit will store all of my vowels so I can quickly access and look hey is this character vowel hey is this character a vowel so this will help to speed up all of my operations right moving ahead with a dry run we now count how many vowels do I have in my first window will be of the three characters right a b and c so how many vowels can you find over here only a is a vowel right so I will increment my count of window vowels and that changes to 1. since you have to start somewhere you just point that Max focus is also equal to your window hours because that is also a possibility everything is now set up the next part is starting a for Loop this for Loop is responsible for sliding your window all the way to the very end so as soon as you move to the next step you check hey the character that I am removing is it a part of vowels yes so you are gonna do window workers minus because now you reduce one character and at the same time you are gonna check hey the new character I added does the vowels hash set contain it yes so you are gonna do windows plus 4 the window went one step ahead but the window walls remained the same right this is for this particular test case eventually when your window will move ahead you are gonna include another vowel and this will increment the window wobbles count right and at every iteration you just keep a track of the max vowels so once your Loop ends completely this variable Max flowers this is gonna hold what is the total number of wobbles that you were able to find for this particular test case 3 will be your answer and this is ultimately returned over here as Max models the type complexity of this solution is order of n where n is the length of the string and the space complexity of this solution is order of 1 because you just need a constant space to store your vowels in a hash fit I hope I will be able to simplify the problem and its solution for you as per my final thoughts I just want to say that whenever you see problems on substrings and sub arrays the most important question that you must ask your interviewer is the element of the substring contiguous or are the elements of the sub array contiguous because that changes the problem a lot so it is better to clarify these doubts first rather than trying to just dive into the solution and try to come up with something you might be surprised that how a small statement can differ your entire solution so while going throughout this video did you face any problems or have you seen any other problems which are based on the sliding window algorithm tell me all of them in the comment section below and I would love to discuss all of it with you it will be also helpful for anyone else who is watching the video and you will have a compiled list of all such problems that will be really amazing 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 can simplify programming for you also let me know what other problems do you want to follow next until then see ya
|
Maximum Number of Vowels in a Substring of Given Length
|
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
|
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`.
**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
**Example 1:**
**Input:** s = "abciiidef ", k = 3
**Output:** 3
**Explanation:** The substring "iii " contains 3 vowel letters.
**Example 2:**
**Input:** s = "aeiou ", k = 2
**Output:** 2
**Explanation:** Any substring of length 2 contains 2 vowels.
**Example 3:**
**Input:** s = "leetcode ", k = 3
**Output:** 2
**Explanation:** "lee ", "eet " and "ode " contain 2 vowels.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `1 <= k <= s.length`
|
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
|
Dynamic Programming,Graph,Shortest Path
|
Medium
|
2171
|
1,431 |
okay so this problem here is leak code number 1431 kids with the greatest numbers of candies so basically given an array of candies and the integer extra candies where candies at index i represents the number of candies that the ice kid has for each kid check if there's a way to distribute extra candies among the kids such that he or she can have the greatest number of candies among them notice that multiple kids can have the greatest number of candies so really all this is asking is so if we see here in the bold the greatest number of candies is very important so basically to have the greatest number of candies uh the ice kid has to have the max integer in that array because that is the greatest number of candies that exists so we want to see for each kid if giving it the extra candies so this thing right here giving it the extra candies would make it the new greatest candy so to figure all of that out first we need to figure out what the current greatest number of candies is so we can just have a max here and the first thing we want to do is we want to just go through the candies and set the max so we can go in candy of candies to go through each candy and then we can just set a new max so basically max of the current max and the current candy and then this will get our max that we want so another thing we want to do is this actually the return type is going to be an arraylist of type boolean so let's just get that ready and then call that res and then make that a new arraylist and we know we want to return that at the end so let's just get that ready so basically what do we want to do we have our greatest number of candies so at each kid we want to see if giving them extra candies would make it the new greatest now it says notice that multiple kids can have the greatest number of candies so this means that it doesn't have to be greater than the max but it just has to be greater than or equal to the max so does it become the new greatest number of candies is what it's asking so basically what we want to do is we want to go back through our candies array and we want to see if so for our output array it's an array of boolean types and this represents if this kid so the ith kid given its current candies if we add the extra candies will it make it the new greatest number of candies so at this candy basically all we have to do is add that condition so that boolean so if candy the current candy that the ice kit have plus extra candies is greater than or equal to the max number of candies and that's all we have to do because this is the condition this will evaluate to true or false and that'll fill up the resurrect so let's run this and see what we come up with and we'll see that it's correct we'll submit this and everything's good so this is just a simple way of how to do it and just an interview friendly way to do it and i hope that was helpful and thank you for watching
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
234 |
hello everyone let's solve the problem pali drum linked list so basically a palindrome is anything really that reads the same forward and backward a notable example is an example like mom so mom reading forward and backward is essentially the same thing but we want to check if this linked list is a palindrome and as you can see from the example giving one two one easy palindrome because it reads the same backward and we want to return false if it is not a palindrome so if we add something like one two this is going to be false because it does not read the same backward backwards it reads us two one not one two now like let's give ourselves some rooms and tackle this problem so we're going to be solving this in two different ways the intuitive approach and using two pointers now the intuitive approach is um this actually just came about when i talked about arrays right if you've tried to check if an array or a string is a palindrome basically the best way to do it is to use something called two pointers where we have the first pointer on the first item in the string or the array and the second pointer on the last element in the array and then we're just comparing if they are the same thing if it is a palindrome the first and the last item will be the same and as we move forward this one will be incremented this one will be decremented so meets at this point and we would see that indeed this is a palindrome but if we add something like this right um if we had something like this it still would be a palindrome because the first and last will be the same and when they get to the middle when the pointer gets to this point they still count they are still the same thing but if we add something like um want to write if we add only one two and the first pointer is here the last pointer is here we can see immediately that this is not a palindrome and so this is immediately going to return a false because it is not a palindrome now recall that a linked list is not um an array so we have to first a link list is basically a list right it's not an array we have to traverse the entire thing to get the element at the last index so the best way to solve this problem efficiently is to traverse the array not array traverse the linked list study values in an array okay i used one two three four let me be consistent study values in an array and then now today now use the um to pointer thing um compare and write if the first element and the last element is a palindrome so this is the intuitive approach now this takes a linear time operation but we use an extra space array that is as large as the linked list and so this is also um a linear space operation now this is why we are actually considering a second approach since this uses um linear space and we are basically considering okay can we do this any better and yes we actually can um all right this um time complexity just came to me that is wrong no just came to me i just realized that this is wrong first this is a linked list we're traversing a link list and we know that this take of end time operation and then we are basically traversing our um our array right but we are not traversing the entire length of the array because we are moving at two at a speed of two power one like in one iteration we are considering two numbers first we are considering these and this then we are concentrating this and this at the same time basically we are dividing our step by two so this is going to be an o of n plus o of log n operation so this is not a of n operation this is an o of n log n operation but now we are actually going to solve it with two pointers using an o of n time complexity and a constant space complexity again let's give ourselves some room and solve that now this problem actually didn't come intuitively to me but after solving it i saw that it used a lot of knowledge that i have worked on solving linked list and you will see that too in fact the cards is going to be linking to the littlest playlist if you can go through this playlist and solve some of these questions that i'll be listing out so the first thing i want to do with this problem okay if we're giving a link list of one two and one and we want to solve this using two pointer the first thing is that we want to find the middle of the linked list and why do we want to find timmy do we want to find the middle because um it will find the middle here right let's say this is the middle and we reverse the middle so the middle is the middle linked list is going to be 2 1 we reverse it to 1 2. if we start to compare the original linked list up to the middle we would see that one two is the same as one two right but if we add something like um if we had something like one two and we found the middle here and then we reversed this middle so this is going to give us 2 1 and then we still go back to this original list right and we start to compare the values of the middle with the values of the original list we would see that this is not the same and we can immediately know that this is not a palindrome so what i'm actually saying is that um let me write back our values first we want to find the middle of the linked list then we want to reverse the middle then we want to compare reversed with original if there are if it is a palindrome they will be the same but if it is not a palindrome it's going to fail at this point now we have already solved um a problem a linked list problem but finding the middle of the linked list it sits in the cat so if you don't know how to solve that problem this might be a good time to just check out how to solve that problem because we are doing the exact same thing then we also have solved how to reverse a linked list now this is reversing the middle but that doesn't matter because it is still a linked list we're reversing the 8 and that is basically what we are going to be doing with this problem now just to um run through it quickly again recall that we are giving a linked list now when we find the middle we are basically saying that okay i am at this point this is the middle of my linked list fine we've got in this middle great that's our first step get the middle of the linked list then we want to reverse the pointer from the head now we know that if we should reverse this two one we basically have one two finally we want to compare we are going to still have our original linked list which is going to be one two one and our reverse linked list is one two obviously we are going to reverse up to the length of the middling list since we know that the head is going to be definitely longer than the middle right so once we um compare up to this length and it is the same then you can just return that is a palindrome it can return true but if it is not the same then we can return false so this is how we are going to approach this problem using the iterative method and using the um pointers now this second approach uses pointers and i find it in the middle while just using pointers to reference the middle let me do linked list when we are trying to reverse we're also using pointers in fact when we walked throughout reversing english we talked about i was just a solution of manipulating pointers and so we are not using any extra space we are using the pointers are already pointing to already exist is a fixed state and fixed space right we know that okay you are pointing to an element in our linked list that is of fixed space there is no extra space being used no extra data structure and we are also doing this in a linear time operation all right let's jump right into the solution all right so let's solve this iteratively uh not really iteratively less so this is a new brute force approach so the first thing is that i want to define the array that is going to store the value of the linked list and while it is true we want to append the values of the linked list and so we are not stuck in an infinite loop we also want to move it to the next value in the linked list now our left since we want to define our pointers like we should one pointer if we have something like one two one and we already have it in an array the first and pointer should point to the first um element in the array the second pointer should point to the last element in the array compare if they are the same and then move forward from there so we can say left to zero because it's going to represent the first item in the array and right is going to be the um last element in the array now we can say that y left is less than or equal to right we want to check that they are not the same right because if they are the same they will just want to return a true so we can just check that if left is not equal to and recall that they are already an array yes so this is valid basically this operation is valid because we already stored the values in an array so if they are not the same right we want to exit with a false otherwise we want to increment one decrement to two this one operation runs right and then we can just quiet and return a true and delete this you know we don't need it let's run this be sure that it works this works submit it and we should be good to go cool this works all right now let's see if this is in the two pointers approach so first we want to find the middle of this eight and we're going to use find this using a fast and slow pointer when the slow pointer ends the pointer they are running at the same pace they call it tortillas and air or floyd cycle detection algorithm we've used this in the number of questions and again if you have not solved this problem i highly recommend that you check out the playlist attached to this um video and solve middle of the linked list and reverse the linked list problem as it will make this one so much more easier so we are trying to find the middle of the link list using this um tortis and a technique and while fast and basically while and basically while and basically while this condition is met then slow is going to be moving at a slow pace right but first is the air and it's going to be moving two times faster than the slow this condition is going to run up until this is no longer being satisfied and we know from the problem we solved where we found our slow um list the note at the slow point that slow is now whenever fast ends slow is going to be the middle of the linked list it's going to be at the middle of the linked list then we want to reverse the list from the slow pointer once we evaluate from the slow point and we want to reverse we know that we are also manipulating pointers so we need a previous node that points to what already existed previously and in this case it is none because we have nothing um stored previously now we are going to run this up until slow is no longer true and then we are going to say that slow is rather previous is going to be slow right if slow is known then we have to believe that previous is now slow dot next is now going to be previous right because we are updating the pointer of previous but this needs to come first this needs to confess before previous because we are changing what previous is so we're going to say it here that slow dot next is previous because if we change previous face then we are losing access to the original previous right also we need to store variables we are also changing slow dot next right but we need to move this we need to traverse the slope by moving over to the next item so we don't lose access to that we need to store it in a variable and we're just going to call this nxt and we can move and see that slow dot next is going to be nxt basically so this is what we are doing here in this place we are just um not slow dot next this is actually going to be slow right because we are treating it what we're just doing is reversing the list from this slow pointer we are trying to manipulate the point as where slow dot next now points to previous whatever if we add something like one two we are not saying that um slow dot next year one no longer points to two it now points to what existed previously it's pointing to the previous node then previous is now slow we now want that okay when next item wants to point at a previous it no longer points at none it now points at this one and then we are just updating this pointer to move on to two we don't since we already updated the next of this we want to store the initial next in a variable so that we have access to it here and that is basically what we are doing then finally we can compare and we're going to let's compare this using the left and right um let's just redeclare variables left is going to refer to the original head of the linked list while um right is going to refer to the previous because previous is now going to contain the new head of the reverse link list and let me just leave a comment here that says compare now we can just say that while right is true since right is referencing the previous i know that the previous length is definitely going to be lesser than the original edge so while right is true if left dot value is not equal to right starts value we want to return a false immediately we also want to just go ahead and move on to our left pointers and also go ahead and move on with our right pointers now if all of this condition is satisfied then we can just return a true give ourselves some room um try to run this is a bit lengthy but i believe that once you grasp finding the image of a english reversing delays from the slow pointer then we are literally good to go all right this works fine thank you for watching this episode i really hope that i said episodes what did i say though i have a podcast thank you for watching i hope you learned something um please give a comment if it helped you if there's anything that you want to comment basically please give it a like and subscribe we are currently walking through the sean prasad lead code patterns and yeah we are trying to solve this and build our knowledge of data structures and algorithms so if that sounds like something you might be interested in you definitely want to be subscribed so you know when a new video comes out thank you so much and i'll see you the next problem
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
312 |
Hello hello everyone welcome back to my YouTube channel special barrenness today we are going to do just the balance problem okay in this subscribe our page like in the beginning I will take it as if it is about the meaning in the now so this I will finish it then Now I would like to say that your gift is fine, I noticed that there is a need to add left and right points, it is fine because there is nothing on the left, there is nothing on the right, it is fine, so it has Ghaghra point, so this rumor spread. What should I do? Keep my volume at maximum. When we start, if we need help, then subscribe to my channel. Then subscribe and let's see Prabhjeet. Then see other suits in this. Now we are like I have saffron, more means only its answer. I want that by simply doing this, I can take it in it, like to subscribe to the problem, I don't have to subscribe so that I can tell that just by doing this, how many do I want which is on the right side, while if we talk about it, then the last one is that if I Said that I will do this for the last time, so my two problems which are closed, that is my problem Pandharila and this problem of mine has been 50. To fix it, we need because with if subscribe, just do it. Just do it, then the quality will remain that yes, I will subscribe last and I will give you this security, for this there is an account, what will I do, now see, by applying in Delhi, I already feel that it is decided, okay, so it is done. By doing this, it can become a yes, because by subscribing to this video channel, I had this problem and now if I have that problem, then there will be left and right notification questions, so I can choose which part to do. First I just do it and then the problems will continue like this, so now it means which photo has been taken by the last forces to identify me so that my maximum can come in, okay then if you see, quintals of men are admitted through the net, these people are From stock IPO to doing subscribe like and subscribe my channel and subscribe the symptoms and ghee in this it is not only the problem in doing tips but also the problem 158 subscribe like I got all this from school so this became my side. What are the points you will get for just doing this? I am late by 10 minutes. Left and right, the name of the is Android and now what is it that like mine was this, I had put one here, how much is my index - - Subscribe to - - Subscribe to - - Subscribe to A. plus b beef can z plus left * A. plus b beef can z plus left * A. plus b beef can z plus left * phone numbers off k into right left arrangement so for this I can say if my a is good okay if I can say if my i - bank so if this thing is means my i - bank so if this thing is means my i - bank so if this thing is means That's how it is, how are you right, my value of left is that I - So I told this, value of left is that I - So I told this, value of left is that I - So I told this was my name, you are mine, you have to point left and right, so come, if you have taken the frustration of my mind. What has happened to me, his practical life has become fine, acid element is fine, otherwise my name is cleanliness, my father will be looting, similarly, whatever right side is required, after that you can do it in such a way that means I can do that now I have only one I know that I have the element, so if I have it, then I want to do Bigg Boss, then I became my 173 life partner of the left parties, women, now to do this from the point, I used to live in between that. Ticket Your Best Quotation Is Bloody Mary that mine if jail My iPad is local Return it Zero ok in my kitchen Can do any I can tell you Ajay came to me in memorization Greens say first defeated Will you have to do it, I hate love story - Hai and mother, I hate love story - Hai and mother, I hate love story - Hai and mother, this is mine, this was points 152 meaning, I can be on Vilas point, meaning this fall, Jai Hind hai, meaning will come person - Band and hai, meaning will come person - Band and hai, meaning will come person - Band and activities, and one to come, like point, mother could be my I want this - could be my I want this - could be my I want this - 1 loot, interest is closed, till the end, this is bread and because I take it in some way but you know that hey man, whatever it is that if I say, I will in the meantime I have smoked a cigarette I have done it, okay, for how many hours a day, due to lack of interest, Bigg Boss will come back, how many elements and studs and jewelery will I do in the end half, okay, it is done for all of you friends, now come on, this means - 120. This means That is, if I mean like on, this means - 120. This means That is, if I mean like on, this means - 120. This means That is, if I mean like this - 110 003, okay, and this will be my mapping, I mean, by mapping it in the comment below, I would set it in this, I had to return this subscribe to me, I would just balance my lower caste. ing range in which they just have to do okay, after that my number should be simple, na and now first of all basic pension fication has to be written, on top of relationships, my tashan will repeat the previous song that I first I am someone's problem Want a that America city cancellation it's ok now it was my very was doing so easy lane ji that's what I do that's what I will do for one to declare do candy crush on the phone so the items are in the cases That plus was the lack of okay that I had to remind the maximum not for which value is my value this is my maximum so I take a poor maximum points that and that time rebelled that a and your exam is And I will weight the expression of inches and see that if it is more than the maximum point then I will replace the active value. I will say that this is MP3 from video file name like . So here what will happen to me is that I will weight this points on 1020 plus. I should do it okay, I do it here, okay so I am here, I had written the chest earlier that if you are a person 125, then similarly my jo was right, Jat vote bhi agar ji mera Equestrian hai 121, you can write a different name, I will update. Of that I point that if I get maximum points for basically identifying my qualification then it becomes 101, Dabi beef is kept medium, plus beef's era is that and plus k is appointed as lieutenant to right into fluid * into fluid * into fluid * Name of Sa K So what happens after this is that my A will know the maximum point time by solving the question in which Veda, okay friend, what should I do, I will simply return the max points MP3, my simple equation to convert to quadratic nice DP said that the lower key There is a meeting tomorrow, whether it is calculated first or not and after calculating I have to go to bed at * Ability for calculating means * Ability for calculating means how much is this DP of eyes on P5 Plus1 Schezwan Latest Notification - 110 is written in the same thing Notification - 110 is written in the same thing Notification - 110 is written in the same thing 512 A doctor on Thursday said that if there is a problem in the DPO of IPS 101 sequence again, then I can easily get 100% then I can easily get 100% then I can easily get 100% confidence. All about this video. Subscribe. If there is a problem in subscribing, then please like this video and
|
Burst Balloons
|
burst-balloons
|
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it.
Return _the maximum coins you can collect by bursting the balloons wisely_.
**Example 1:**
**Input:** nums = \[3,1,5,8\]
**Output:** 167
**Explanation:**
nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\]
coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167
**Example 2:**
**Input:** nums = \[1,5\]
**Output:** 10
**Constraints:**
* `n == nums.length`
* `1 <= n <= 300`
* `0 <= nums[i] <= 100`
| null |
Array,Dynamic Programming
|
Hard
|
1042
|
1,379 |
Jai Hind this problem is search for not in a given point will not give 1872 The Video then subscribe to the Channel and subscribe the Channel ko hai sonth approach vich can do me to return hai panch lootere example subscribe and subscribe the Channel subscribe our Supervisor Target And Let Us Know How We Can Do It So You Think That Subscribe Other Policy Channels Subscribe To I Am Just Twitter Muzaffarnagar That Now Rich But Things That Enter And Question Is The Muffler 5050 Simple Subscribe And Subscribe Kare Motu Patlu HD 520 You have written this but this was wrong turn on rebellion bodh pimple sauvir web address subscribe and liquid long will immediately subscribe to 200 vikram and root vikram and due to this alone or in the same time vikram par is not match with attribute to give oo That on this important match day indulge in travels that and again with each rate and scroll body avatar great indian more controversy in different way you can post in english subscribe this Video Please subscribe and subscirbe to ultimate relief Twitter not embryo back employee drive business friend Thank you later this one so both are improve on Thursday share will find its way back from the current node in tune with this channel subscribe and improve the time complexity of disapprovals that number and specific time that in big Boss House Traffic Jam Thursday Do n't Forget To Subscribe And Subscribe A Super State Will Write Inch Plus Tomorrow Morning Fog Extra Porn Just Do It Is Original Software Day Is Original Is Equal To Target The Return Blonde That Hurt Any Point Of Time Original End Follow there point does not have been st louis suarez 121 custodians swift against others will have to continue research indicates the worst thing in left and right that you can do the beatles and hindu inverter fashion house that sushil function target photo copy and this channel were Left O Clock Lift Enter Gaye Intimate Scene That Sui Is Friends Date Nodal Point Will Returns But Not Always Be Late Amal Sure That Fitton Sanwarlu That General Tonti Is Disposal Daily Will Go For Brother And Searched Right That And Will Finally Bigg Boss Better Plan Feature Target is from the which is present in Roddy that and finally eternal is did not find that and let's see that it works for this so let's submit duplicate listen to Vigyan Vikas Vihar comparing the is actually mood and what value Sudhir values in you can compare subscribe now values in you can compare subscribe now values in you can compare subscribe now To The Ultimate 9 News Room That Do It In Java And Pratham That In Every Small Solutions With Can Be Imported Very Easily Loot Lo EPFO That Sting Bit Long Way MP3 Well That And Were White Hair One Millisecond Subha A Better Than There Solutions You Can Get Zero Millisecond Observed on a Family Laddu Til Pratham Pradhan Mantri Kar Do On Karo Ki End Pattern Solution of Chapter
|
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
|
reconstruct-a-2-row-binary-matrix
|
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree.
**Example 1:**
**Input:** tree = \[7,4,3,null,null,6,19\], target = 3
**Output:** 3
**Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
**Example 2:**
**Input:** tree = \[7\], target = 7
**Output:** 7
**Example 3:**
**Input:** tree = \[8,null,6,null,5,null,4,null,3,null,2,null,1\], target = 4
**Output:** 4
**Constraints:**
* The number of nodes in the `tree` is in the range `[1, 104]`.
* The values of the nodes of the `tree` are unique.
* `target` node is a node from the `original` tree and is not `null`.
**Follow up:** Could you solve the problem if repeated values on the tree are allowed?
|
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
|
Array,Greedy,Matrix
|
Medium
|
1711
|
744 |
Welcome back to my channel, so today's challenge is Find Smallest Letter > Target, challenge is Find Smallest Letter > Target, challenge is Find Smallest Letter > Target, so in this problem statement, what have you given us? And you have been given a character from the target names and what you have to do is to find here the smallest letter but greater. Give the target. If it is possible then if not possible then what you have to do is to donate the first character so now look here. In the first example, what is given to you is latest and a target A is given, then what can be the just greater element here, see when is > and what can be the just greater element here, see when is > and what can be the just greater element here, see when is > and JB is greater then which can be just greater, it will be C. Neither, what is the answer here? Your C is C. Now look in the second example, you have given C. We have given X That if there is X here, then what will be our output? In other words, one is asking you to fine the bound, it is from just get an element, so what do we do, if we understand this, then we have given ourselves first, so what do we do, hey, let's take it. Hey Di I 0123 456 789 What do we do, let's take F here. Okay, 10 total, we have so many 11 elements. Okay, now we have been given target, C is given here. Okay, so just get element from C here. What will be your answer? What will be your output here? What will we do here? Now, what do we do here? We will find out how we can do it. Look, what will we do here? We will take a left painter, right one is given in a way. So you just have to find an element from here, you have to search, we will do that, we can also do liner, wherever we find it, we will turn it, but what will we do with it, we will solve it in binary. Okay, so what will we do? Will take How will we understand that what we need is just a greater element than this, what will we get on the right side, that is, where will we have to start the search now, we will have to do it from MedPlus One, that is, what will you do by shifting L and bring it here, then what will L do? What will happen to your six? And what will happen to you today? What will happen to 10? Now let's find the middle, what will happen here in this, okay and this which has come, it is greater than your C, okay so this How will you do, see, this can also be your possible probability, if it is greater then it can be in the answer, then what you have to do is to take a variable which you will start with the answer zero if you get any data element. If so, update its index here, then what will we do? We will update it here in this way, we will keep coming because it is possible that we see that we are the best here, just want to see, this is greater, it is possible that this is its just greater. We do n't know, so we will keep updating the answer, we will bring it as it comes. Okay, now what is there here, now you will compare it, what is yours, it is just greater, okay, that means it is greater than C, so it is possible that look here on this side. On this side, we will understand that whatever is on the right side, it is gate C, it must be greater, so what will we do, on the left side, we will find what is less than C, but is there anything less than this? The answer is, what will we do with this, how? I will update our And for how long will you keep doing this process, till then let's not take out = R, so 6 + 7, you will do 13, = R, so 6 + 7, you will do 13, = R, so 6 + 7, you will do 13/2 will be your 6, okay, what is 13/2 will be your 6, okay, what is 13/2 will be your 6, okay, what is your pay here at six, okay minute, take out six at your place and you will know. Let's say that this is given which is greater than C, then you will understand that we update this answer because we found it from here on the right, so what we will do is update it and fix its index, okay We have done six, so what will happen now you have seen here, I have seen that you have got the song, so you will try again, what will you do now, yours is here, we are here, yours is 67 and now how is this? What will you do, then you found yours here, now you will try, maybe what will happen to me is in this side, okay, let us look a little in this side, so in this how will you then update R? What will happen? Yours will go and mid - 1 i.e. it will be your What will happen? Yours will go and mid - 1 i.e. it will be your What will happen? Yours will go and mid - 1 i.e. it will be your five here then what will be the condition this will be your break if the break will happen then we will not move ahead i.e. then we will not move ahead i.e. then we will not move ahead i.e. you will get the final answer here then what is the six pay if it comes then what will you do latest given Answer: Turn here, dog, if this story is given Answer: Turn here, dog, if this story is given Answer: Turn here, dog, if this story is also not updated, how was it third, how was it here? XXX A, let's check the answer for that, our zero is zero in the initial, okay what will we do now 0 1 2 3, we have taken L, this will be ours, and this will be mid, we will find this zero plus three a, you will do this, then one will come out, one will be this. Okay, now what is smaller than s, so we will understand, we will get this on this side, so we will find l here. Will do it and Apna yahan pe hain tu plus three kya aapna yahan pe will be five. If you do five by you then it will be 2 then you will come to tu pe then you will see what is this also if yours is smaller than s so we will again add l here. If you update the page then what will happen then we will see that if it is equal then we will understand that if it is on the side here, then what will happen with this is that you will go out of index and here you will not get the answer even on the story, it will not be on the story when you attend the letter answer. If you do this, what will it do? The first one has got the pick, so this is how we will solve this bowling, so what I do is show you the code, when what we did here, we have taken zero R, we have taken the letter dot. Size minus one and in the answer we have taken zero. Okay, now what we have done is we have taken a loop, what is the connection of the loop, what have we kept L <= connection of the loop, what have we kept L <= connection of the loop, what have we kept L <= We have found the element made here, now we will see whether the target is equal to what the target is. If K is equal then shift L to mid plus one. Okay, if our latest mid is l from the target, we just need to gather, otherwise what will we do, we will break the alcohol. Mid + 1 is another vice. If our latest mid Mid + 1 is another vice. If our latest mid Mid + 1 is another vice. If our latest mid is l from the target, then That's a possible possibility, so we'll update the answer as well and also update R to mid-tree update the answer as well and also update R to mid-tree update the answer as well and also update R to mid-tree because we'll try to maybe get something just greater than this on the left side, so we'll update R to M - 1. so we'll update R to M - 1. so we'll update R to M - 1. Okay. And finally what will we do, we will turn to the latest answer here, then what is the time complexity here, your login will happen, I hope you have understood, if you liked the video, then please like and subscribe.
|
Find Smallest Letter Greater Than Target
|
network-delay-time
|
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter.
|
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
|
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
|
Medium
|
2151,2171
|
352 |
today we're gonna be working on lead code question number 352 and data stream as disjoint intervals uh given a data stream input of non-negative a data stream input of non-negative a data stream input of non-negative integers A1 A2 up to a and summarize and the numbers seen so far as a list of disjoint intervals so implement the summary ranges class so in this one it's going to initialize the object with an empty stream okay and then now we're gonna have an add number where we're going to be adding adds an integer value to the stream and the get interval is going to return the summary of the integers in the Stream currently as a list of disjoint interval start to file to the end of file so in this example he is initializing he is adding a number one and getting the interval so the interval when only one is added is going to be one to one then here's another number and which is three so now the interval we have two intervals because one and three are disjoint it we don't have two in the middle so it's gonna be one is one interval and three is another interval and that was the answer then here it's another number of seven so now we have three disjoint intervals one or three and seven but then he adds two and so 1 2 and 3 is gonna become one joint interval so this is going to be one two three and seven to seven is well on its own then in the end we add another number which is six so now we have to connective or joint intervals which are disjoint from each other one interval is one two three and the other interval is six to seven we're going to be using a data structure called remap for that it's going to be much easier it's going to take care of joining them and giving us the lower end and the uh and the upper end like all the floor key and the ceiling key so let's just do that so we are just gonna have our Declaration of the tree map and it's gonna tree map it's gonna take two integers integer and integer photography map yes and then uh we're gonna initialize it so our tree map is equal to new tree map looking good so far so add number and then the get intervals right so let's just start with the adding the number okay now when we are given a new value right so we when before processing the new value what we're going to do is to get the previous a number and a next number right so an integer called previous would be when we get this uh the floor of that so tree map dot it's called a floor key for that value so you get him the value and it's gonna tell you what's the floor key for that one and then an integer next uh would be three map dot it's called the ceiling key of that value okay if basically if the like there are a couple of things where we don't even need to process it uh if we have two conditions like when I said the uh the previous is not null right and uh when you get the previous value that is actually greater than the uh let me just write it down F and that previous is not equal to none and at the same time uh if you see that we have a value for this previous key and that value is greater than equal to the value that means we don't wanna we already have it in the interval and we don't want to process it we don't it's not going to create a new boundary for us so we're just gonna return okay the other thing we want to see is about if our next is not null and the next is equal to the value itself right then again we don't need to process it uh if the next is not equal to null and the next is basically equal to the value itself right and then we don't want to process that either okay now we need uh like a starting interval and the so we're gonna say that initially we're going to assume that this value is going to be an interval on its own so the start is equal to value and end is equal to okay now we need to check that if the next is not equal to null and uh the next minus one is equal to the value if that is the case right then in that case uh our end is going to become equal to gmap.get gmap.get gmap.get next and we're gonna remove the next itself right three map Dot remove the next what's gonna happen because in the end we're gonna change the limits of the start and the end of that treatment so what we are saying is like if the next if basically uh basically we are saying that if the next which we have is equal and x minus 1 is equal to the value so we all so this is going to become of that interval so we are saying that okay the end is Gonna Change now the start may not change uh because start may be the same value for the interval but the end is gonna it's gonna get updated okay and the last thing we want to see if our starting point is also gonna change so for that if the pre is not equal to null and J Dot this three plus one is equal to that value right then we have to update our star two so the start is going to become equal to 3 and then we also want to remove the old uh like the pre from the map okay so and then we're just gonna put the new interval in the tree map so that would be put the start and end now when it comes to getting the interval all we have to do is like basically uh there are two things in it one is like the basically we can just get and get the start and the ma the end from it but we also need to convert into uh like an integer array so let's just say that the list because it's gonna be three map is going to be returning a list of integers okay result is equal to new arraylist okay and we're gonna say our start is gonna be equal to map Dot uh what do you call uh the tree map dot get key set sorry foreign so it's going to be new and the values are going to be equal to start and the tree map dot get start okay in the end we're gonna just say that um is looking for an answer and the integer like array to the array of integer so we're going to say the answer is going to be equal to new end and the sizes are going to be equal to result dot size but all of them has to be the second one needs to be hard coded to two yeah it's gonna be just start in n so for and I equals to 0 okay and the answer of I is gonna be equal to result dot get of I and then we can return the answer this should be remap looking good and it works
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
1,029 |
The latest solution to two cities having problem in this problem is enter a particular company to call candidates for interview and this number of candidates actually and candidates can be divided between two cities of candidates can go to do subscribe list subscribe and subscribe the Video then Sainik Candidate one two cities and a prosperous and improves the TV and candidates will be selected or not but from subscribe to that MBBS condition is that you were to equal number of wages and we time when and candidate three cities pe kal subah do so let's start with A Simple Ask Listening to all candidates with them tomorrow morning send everyone to wage Swadeshi to wage but initial state and what will be the cost of sending to for chronic plus that 3001 leading of complaints in three years and everybody to see there on this is Not Correct Will Update Them SUBSCRIBE MY CHANNEL SUBSCRIBE CHANNEL NOW TO RECEIVE NEW UPDATES ELECTION 2014 KI BATIFY SEND SEEDHI DUBAI WHO HAIR WILL HAVE SCENT OF CASES IN QUEST FOR 105 SEND WHATSAPP CANDIDATES TO BE CHIEF SE JHAAR HU IS THE COST OF SCENT BEADS NOT CHEEPER AND SHARE WITH YOU HAVE 0 BOX SINCERE ITS STAND AND CHEAPER THE SUN WHICH ONE SURAI PIC P51 CLEARLY I WILL SEND YOU CAME INTO BEING SUCH CHANGES INTO BEING THAT NEWBORN SHIFT THIS IS PAGES AND DIFFERENT IN 12TH PART PLUS APP THAT NAVVI AB PATI IN THIS WAY Need One More Attractive Clerk Again Will Next Flight Number In Negative Is And In Factories In Next9news Number Rich And The Most Negative Number That This Value Will Be Maximum And Twitter Negative Sign In Next Negative This Black Value Day Lament 500 Plus 172 Tomorrow Morning At Already transport this software left with next this shubh lagna se 10 and you will get your life but not to this exercise for the width of what is the basis of dividing subscribe this Video not negative - 1 not negative - 1 not negative - 1 I will be soft by this - also let's right It is I will be soft by this - also let's right It is I will be soft by this - also let's right It is - also it is - 20 - more than 170 solve - also it is - 20 - more than 170 solve - also it is - 20 - more than 170 solve values will send you we will send and hadith values will send you we will send and hadith values will send you we will send and hadith 220 short note on the basis of this dangerous and the second after to be and first way is Android use autism that it is minus be swift donate - 151 - 117 that it is minus be swift donate - 151 - 117 that it is minus be swift donate - 151 - 117 Is The Smallest Dennis - 03 Fifty Shades Is The Smallest Dennis - 03 Fifty Shades Is The Smallest Dennis - 03 Fifty Shades Where Saint To Be With Sacrifice In First House Will Saint They Secure Subscribe Button And Morning Herbal War Shot Function The Cost Notification The Cost And Have And Custom Computer Will Be To Switch Off Jim Is Active Development Element Repair Vision-2020 12121 President Sudhir and Repair Vision-2020 12121 President Sudhir and Repair Vision-2020 12121 President Sudhir and Hai Ajay Ko Shooting The First Letter of Bal Compare Him with First Factor This is 10 Notes Chapter Take Cost Ascendant Way - Cost Sending To Be Way - Cost Sending To Be Way - Cost Sending To Be That Length And Second Convector Well-known Basis Of And Second Convector Well-known Basis Of And Second Convector Well-known Basis Of Comparison Tomorrow morning 9:00 am send pic we this minus b Tomorrow morning 9:00 am send pic we this minus b Tomorrow morning 9:00 am send pic we this minus b that tweet sirvi ne - benefit way and that tweet sirvi ne - benefit way and that tweet sirvi ne - benefit way and sacrifice on the sun will cost is 0 the reason for more 13424 the vectors notification first complaint with the price of vital force of doing within will Take the price of B.Ed and finally returned cost as Amresh work share also did not well played actual value what was the cost 100 to 120 by sending every thing to be done with ghee and 350 rates by sending this candidate to become B and Another Temple Built By Sending This Dr To 20140 On Turn Seven - 5 - One Is Vansh Youth Sweet Turn Seven - 5 - One Is Vansh Youth Sweet Turn Seven - 5 - One Is Vansh Youth Sweet Will Cost 100 Works And Semi Pimple Is Egg Content 90 So Let's Submit That And Solution Accepted In C Plus Torch Light System Details That Previous Reddy Speech Of distribution of its parent 70% of the missions parent 70% of the missions parent 70% of the missions a snyder same logic in java in python ajay ko that in here also fruit use exam hotspot key and within those spy begin and on do ajay ko a improve operators temperature key and you vikram length hai main Anil Singh also remains same Unmute Boxing Jewel at Summit My solution which was accepted in your valuable debate in Python 3 that Surya will again define a cooperative and started it's cost equal to [ __ ] request started it's cost equal to [ __ ] request started it's cost equal to [ __ ] request post a solid the cost is that total to remember I 10 - I 10 - To 90% To 90% To 90% That In Terms Of All Accept Submission That 24 Looks Fine But I Think For Python Twitter User License Agreement For Calculating Excise Rate In India From 028 Sexual Cigarette Using Hotspot I So They Can Create Subscribe To Is So Insited Of These Flash Lights To be size in convention the cost and win a policy in that ho cost zerotil that in vapi to suit the first half that hand pure-buddha cost pair 1000 from hand pure-buddha cost pair 1000 from hand pure-buddha cost pair 1000 from r ki and something bill copy hai in til and ₹10 even in til and ₹10 even in til and ₹10 even that alerts feet box That Sudeshwar So Let's Submit Accepted And Tricks Much Cleaner Dena That Runway Calculated Length MB Created Engineered 0 Then Engine Laxative In One Additional Inductors That Fish Na Let's Join For Inclusion In Changing That Runtime According To t-20 Near The Pick Classes That Runtime According To t-20 Near The Pick Classes That Runtime According To t-20 Near The Pick Classes By Making Changes Tomorrow morning you can also go to the office much faster to run
|
Two City Scheduling
|
vertical-order-traversal-of-a-binary-tree
|
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Hard
| null |
1,833 |
here I present the third of January lead code challenge the problem that we have in today is delete columns to make them sorted this question is an easy level question based on the concept of strings and I know most of my subscribers rather all of them would be able to solve this question by themselves for those who are new this solution is for them here in this question you are given an array of strings and all the strings are of same length what do you need to arrange them in a form of a Matrix let's assume they're arranged in the form of a matrix and you need to iterate them in a column wise fashion and check whether each column happens to be lexor graphically sorted or not if that column is not lexor graphically sorted then you need to delete that column up and in the end we need to finally return how many columns do we need to delete for example here if I trate from a b c you can see that this is in Le exog graphically sorted order a b and c so this is a happy case the next column that we have is the b c a this is not in lexor graphical order that means we need to delete this sub the last column that we have is c e as you can see C is lower in value than e that means we are sorted again we have e so e is equal to e again that means we are lexor graphically sorted over we can finalize that the third column that we have happens to be lexor graphically sorted so overall how many elements were you able to ident how many columns were you able to identify that were lexor graphically unsorted there was only one such column and as a result of which the answer becomes one to conclude it up let's quickly walk through the presentation section and so I have taken a very simple example the same one that was specified in the question so there are three columns if you arrange them in the form of a matrix then there are three columns the first row will have a BC the second one will have b c e the third one will have a c e and what we are going to do we need to iterate in column wise fashion so the First Column is this the second column is this the third column is this and lexor graphical sorted is a really simple way to check you check the Sky Value if this value happens to be greater than this value then you say that it is lexor graphically unsorted otherwise you keep on progressing ahead so we'll take two pointers the first one would be I for the row count the other one would be J for the column count that we usually do and for J equals to0 we will be iterating over the three doors that we have so in the first iteration we'll compare I with the previous row so if this if I starts from one the previous row will have be the zeroth one so I minus one would be zero so let's compare these two up and since B is greater in value than a that means we are it's a happy case we are basically comparing s of IUS one at the G index with s strr of I comma J index If the previous value happens to be greater than the current value that means it is lexor graphically unsorted in nature and we will be creating a global variable we will say that is whenever such a condition is met that corresponding column is lexor graphically unsorted and we will increment the pointer the counter so we can say delete count kind of a variable we can keep this by default it is initialized to zero so whether this condition is met or not over here also remember guys we are starting I from one going up till the last uh is this condition met over here no this is not me this A happy case let's proceed ahead now I will be incremented to this place IUS 1 would be 1 uh C is greater than b again it's a happy case we have iterated over the entire Z column let's move on to the next one here we have B and here we have C this is again a happy case let's proceed ahead next we have a over here and C over here as you can see the value at s Str of IUS one J is greater than the value of s Str of I comma J C is greater than a this is that means it is lexor graphically unsorted what we going to do we'll increment the delete count variable to one that means we have identified one such column that is lexor graphically unsorted in nature and we will abort the iter further iteration across this column let's proceed ahead next we have is c and e over here it is leog graphically sorted again for the next iteration this is again lexor graphically sorted this condition is not met so overall how many columns are you able to identify there was one such column and this is in sync with our expectation let's quickly walk through the coding section and conclude it up I'll exactly follow the same steps as I just talked over here I have created a delete count variable I started iterating using the two pointers I and J this is the same condition that I talked about in the presentation if this condition is made we increment a delete count variable we break further iteration across that column and once we are out of this Loop we simply return the delete count variable let's transformit this up accepted the time complexity of this approach would be order of n into M where n signifies the number of rows and M signifies the number of columns uh and space compexity is constant time I hope you guys really enjoyed it if you did please don't forget to like share and subscribe to the channel your subscription truly means a lot and I'll see you tomorrow with another fresh question but till then goodbye
|
Maximum Ice Cream Bars
|
find-the-highest-altitude
|
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108`
|
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
|
Array,Prefix Sum
|
Easy
| null |
234 |
we are looking at lead code number two three four it's called palindrome linked list and this one can be a little bit confusing but we'll go through it step by step it's not too bad once we get our head around it okay so given the head of a single singly linked list return true if it's a palindrome example one we have one two one uh and that is true example two we have one two that is false and um the constraint is the numbers and the nodes uh in the list will be one to ten to the fifth and uh the node values will be zero uh to nine and then here's the follow-up uh to nine and then here's the follow-up uh to nine and then here's the follow-up could you do it in linear time and constant space okay so if you do the brute force it's not too bad right you just throw all these values in an array and then check if it's a palindrome and you're done the only issue with that is that you have to create new space then you're gonna do you're gonna have linear space so how can we do this in constant space okay let's go ahead and take a look at our conceptual overview here so let's say we have the numbers 1 2 3 2 1. okay we have a link list here go ahead and fill in our pointers and we want to figure out if this is a palindrome and we want to figure out how to do this in constant space without putting it into an array but just do it with the linked list well we can't go backwards normally what we would do is we would check if one and one is a palindrome if two and two is a palindrome three and three we'd go from the outside and the inside and would keep on going and if any of those numbers did not equal each other then we would return false and if they did we'd just keep on moving until we ran out of numbers but with linked list the pointers only go in one direction right that's the issue so the other way we could do a palindrome is let's say we start in the middle right we take this middle value and then we move outwards we say okay is this the same that's the other way we could check if it's a palindrome but again these pointers only go in one direction so that doesn't work so what we can do here is we can use a method called two pointers it's part of floyd's algorithm and what we're doing here is we're gonna have two pointers going at different speeds okay so we're gonna have a fast pointer and a slow pointer and on each incrementation the fast pointer will move two spaces and the slow pointer will move one so here our fastpointer moves here our slow pointer moves here fast pointer moves two spaces slow moves one fast moves two it gets to the end here and slow comes here and lands on three and what we can assume through floyd's algorithm is that wherever this slow pointer ends at it's going to be the middle of the list that's going to be the midpoint of the list okay and now what we can do is if we know where the midpoint is what we can do is we can take this part of the list here and reverse it okay so we can change these arrows to point in the other direction okay and this will point to null okay and now we can return a reference to this reverse link list on this side and we also have a reference to the start of the linked list okay and now all we have to do is just increment and say okay does this equal yeah they do we move the reverse over here and we move this slow over here and do they equal yes they do and then does this equal and yes they do okay and then we can if we make it through the entire list we also keep track of the length of the list when we do this first traversal from slow to fast we can also get the length of it so we have one two three four five six 7 is our len and then we can just increment both these pointers the length of the list and if at any point they don't equal each other we can say that the link list is not a palindrome and if they do equal each other and make it through the entire uh the entire length then we can say it is a palindrome okay so not too bad so let's go ahead and code this up okay so first what we want to do is we want to have a helper function for reversing a linked list first okay we'll have a head input and reversing linked list this is one of those classic problems that always trips people up um i would highly suggest if you're in an interview situation to just draw it out on a whiteboard make sure you get your pointers right because it's very easy to get this all mixed up but what we want to do essentially is we want to create a current variable and set it to our head we want to create a pre variable and set it to null and then have a next variable we can just leave that undefined and we can say while we're at current while we have a current node what do we want to set our next variable to current.next we want to set variable to current.next we want to set variable to current.next we want to set current.next to our previous current.next to our previous current.next to our previous node we want to set our previous to current and then we want to set our current to next and then we want to return our brief this video is not about reversing a linked list um i will make a second one about re reversing a linked list and we'll go step by step on how to do this but um just want to make sure that if you are in an interview situation to not try to pull this from memory but actually do the pointers it's very easy to make a mistake uh with this method okay so now that we got that out of the way let's go over here and what did we want to do well we want to use the two-pointer technique two-pointer technique two-pointer technique it's from floyd's algorithm and we want to use a fast and slow pointer so we'll have a fast pointer we'll set it to head we'll have a slow pointer we'll set that to head going to have a start pointer okay and we'll set that to head and we are going to have a length pointer and we'll set that to zero okay and now we're going to run two while loops so we're going to say while fast and fast dot next okay fast is going to equal fast dot next and slow is going to equal slow dot next okay and so all we're doing here is we're doing that traversal where too fast every one slow too fast one slow and then we're just going to increment our length variable now we know the slow is at the mid right so we can say let mid and then we want it reverse wherever slow is at so we can go ahead and use this helper function here and pass in slow and that's going to reverse the list from that midpoint okay and now we can just say while length is true we'll decrement length and all we want to do is we want to check if mid.val does not if mid.val does not if mid.val does not equal startpointer.val equal startpointer.val equal startpointer.val then we return false and then we just increment mid and start so mid is going to equal mid.next mid.next mid.next and start pointer is going to equal start pointer.next start pointer.next start pointer.next and then if we make it through that loop then we just return true we can assume that it is a palindrome oh we want to do length i'll just call this len here there we go okay and we're good okay so let's take a look at uh time and space complexity here okay so how many times are we iterating through this input based on the size of the input well let me just go ahead and clear this one two three two one okay so we have one i'll use a white color here one two three two one so we're gonna do one pass to get the fast and slow pointers okay and then we're gonna reverse this from the midpoint and then we're going to do another pass from the end in the front okay so we're doing two passes so our o would be o of 2n okay and we can just approximate that to o of n so our time complexity i'll write it over here is going to be o of n and then our space complexity well we're not creating any new space we're not creating a new list we're not uh we're changing the list in place and so our space complexity will be constant okay space is pretty good okay so that is linked list that is elite code number 234 palindrome link list i hope you enjoyed it and i will see you on the next one
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
56 |
So hello friends, today we are going to solve a problem whose name is numbers interval and right, so what is there in this problem, we will have instruments given to us, okay what does entrance mean that entrance means any work which is Also, I started the work and what time did it start and what time did it finish? For example 325 is written, it means I started the work at 5 o'clock and it was finished at 5 o'clock and like that, what will we have? There must be one, there must be a lot of interviews in it, okay friends, so what do we have to do in this problem, we have to march all the overlapping intervals in it, how to edit and interviews. What is the meaning of example like it started at 5 o'clock and ended at 5 o'clock, it's okay, the second task is finished at 24 o'clock and ended at 98 o'clock, okay, so we can take a number from it and draw that it started in 5 minutes, it ended and the second task is Okay, the one that started at 4 o'clock, ended at 8:00, that started at 4 o'clock, ended at 8:00, that started at 4 o'clock, ended at 8:00, that's one thing, and the other one is this work, okay, so I want to know, thank you, for how long will they march, okay three. I mean, it is from 3 to 8:00, 8:00, 8:00, I will be busy, whoever will be busy, you can consider it like a school, okay, different classes are going on in it, 11 classes went on 3 From 5 o'clock till 8 o'clock from a plaster chart. Okay, so I want to find out at what time the school will be free, which means at that time no class is running till now. Okay, so to find out that, I need to What will I have to do, what will I have to do, I will finally need all the UI's, non overlapping internet, like suppose there were three to four twelfth classes, then 9 to 10:00, if any twelfth classes, then 9 to 10:00, if any twelfth classes, then 9 to 10:00, if any class is fine, then it means from Art till 9:00. If we mention that school is free, then this is the till 9:00. If we mention that school is free, then this is the till 9:00. If we mention that school is free, then this is the problem. I have to find out what else it means, when is our school free, that can be found in the next chapter, but basically, I have to march all the overlapping intervals and combine them. And look at the property of lighting interview, what is it, okay, first we have to wait that both of them are 600, okay, the smaller one should come here first, smaller, when both these works are starting, like who are you, this is starting, so when it starts. It is happening that this should come first and the pending one should come next. Okay, okay, we will keep the tasks which are coming first in the beginning and those which are starting later, we will keep them in October last. Okay, how do I know now? It will be good that they are making more profit, see that the second test has started even before it ends, now the torch has started before the end of some stars, it means that this is the end of the transformer. And that's the map of Hridaya Nagar equal to the beginning of tests End of this world this morning daily paltu stock transfer okay if it gets in condition then what does it mean we can march them okay and finally and chilli What will come to me after doing Start of Taj Qawwal is good ok and Android only kya Hindu What will come aa good ok Translate to Hello how are you Head of Transport Dubai Which of these will fail In this case so what was that 8:00 It was will fail In this case so what was that 8:00 It was will fail In this case so what was that 8:00 It was finished, but it is possible that it is there and the second one is going on, as per the chart, it should be four to five, okay, then four to four and a half, how much will the match of 104 to six and a half inches come, okay, 305, by the way, ghee. Okay, okay, that's why if I only take the troubles, then it comes to four and a half, but if I take only the trust, it's fine, but what should I do, the stars point to both, whichever is the maximum, which is finishing last. I will take that, okay, so basically what is this app to march it, now let's see that we give an example, as we have given a question, one is this intervention which you paint a hand united is a weight, so what will we give? One, two, three, four, two, six, you can understand them, one, you six digit pin, okay, then this will be my answer and tell it to you, it will be given to you in this way, okay, and the tests that will be done are not necessarily soft. Yes, it's okay, there can be any back and forth, please send me the soft, what time is the starting time, what work is starting, this year, if there is one dry ginger, then I will have to complete it first, oh, I will have to soften, okay, don't start on the 20th. According to time A, this time for intervening night will be off and what will we do in the second test, if the second pass, this condition will be checked, which condition is that I am fine, so that the time which is coming first, the task is theirs and in the morning the heart will come out to transfer. But if a condition melts then what will we do, we will march, now okay, now we will chill, and this output will give us the result, admit and now we take it as an example, so the result is, what is mine now, MTS. What will I do after this, I saw the minister come, okay if it is empty then add the product, what will happen, now I say okay, just mix it now he will ask that maybe it is only okay, there is a descendant about the result. It is already fine, now the next one will be fine, it will be the next one, so what do I have to do, whatever is the last event of the result, I have to check the last event and whatever is my current events, if I want to see this, then what conditions do we have to put in it? ok condition humne kya lagni padegi ko kill gadi condition injury 10 first start has started uska jo end hai ki uska jo end hai should be grade daily urdu starting of ka rishta half mp3 punishment hoti both will be mashed and this is our importance Hey, if the torch light comes then we will use the same approach to solve this problem that the ID codes of normal decisions are fine and if they are given then their parents are there, then we have an area called intervals inside which the interviews are What will I do after this? I will start a temporary registration. What to do now that I told you that you will not get it in short form, then you will have to set based on the starting time of your professional 200 starting time of the interval. What will be the interest that is equal to 123, put 100, okay, and we will have to define in this, the open loot of the song in the office phone, and for someone, what will happen is the name of the idea, I am zero, okay, what will you do with the lehenga, okay, every. There will be one interval, whose interval is the Minister of Affairs or Bansi and the second one is 30 to take, as if this is to shift the gas from the interviewer to the cylinder, for the sake of time, I have taken it, so I will give it, okay and this is ours first. The statement started, this work was done that I will go to America, a by-election and the idea that I will go to America, a by-election and the idea that I will go to America, a by-election and the idea in interviews is good, it is okay, that if my vote is empty, then what is the meaning of this film? Out and there is nothing simple for you, what will I do, I will end it in this period, that I Jagana interviews, I will also access the intervals of worry from the Android world that we are in the web and meaning of the complete interview, so you will be able to access that in that. I will send the interval, I will insult you, it needs to be corrected, but if there is already an interval in it, then what will I do, then it is the shoes of motivational status of the film Vikram, so we apply LCF or that the use is economic and I have made a mistake, now we will do a test in a different way, first we will check the condition whether this interview is right, whether the job interview in this center is matching with the last interview or not, okay first we We will see that the meaning of 12345 is that there should be some limit on sending photos and interval and on the petrol that has to be typed, how will the time of the examinees be known and in 130 special times one and space and time, the receiver will be the one of the interviewer. What will that be my play list exactly to find from whom automatically the last element in it is the last interview that now I am the last element is okay from the end of it where is the end on one were okay if this condition metro what will it mean food travels I can match them also, after that, first of all, what do you have to write, the option is to massage from the street, Bhojpuri film, what will happen now, okay, what will I do now, that henna is on the output, what will I have to do now? Now what can happen, write something, it is looted that there is a result in the state, then if the minister comes in the beginning and then it is six, then it is okay, then I do not want to put any ad help or interest in the result, okay, I do not want to do anything inside, I just want to modify it. Okay, how will I modify it? Okay, the name is the starting time, so its runway which is here and the pending time, what will be the marks and this has to be done at the end of Tashkent and the end of transport only, so this is what I will give you here, so how will the output be? The last interview is okay, it is in that due time, what will be the maxims of these that after that the result of the pur ki is seen, its last tip is either done with your feet, then your end is that you will get your pending time when then by taking this one's crediting time. Both of them are going to end up in the maximum period, neither is the maximum on the intervention of the interviewer love 1000 and the one is nothing, what is the purpose of the permission mails of the useful month, what should I do, the avatar is A plus 222 yes brother. That if it is not happening just like that but if it is not happening as a man that I will die, if one of the conditions is not happening, then you art the chutney in the result, now pay me that atext is fine, now sit down to write this in the court. Go, this is what I have written to explain, it is okay and what will we do after this, we will come out of the form and then we will do the time for tips to return to vote. Okay, that's the only reason I came in this question, considering the hope side as fattu. I must have thought that how will we solve this question, chocolate syrup, time complexity, WhatsApp and complexity, then this is the upper end going on and then and hill station of spring, this will be the most costly operation, okay, in the blast case, enrollment time will be available, okay, this is so. These all will work, abe tu iski jo time complexity ho jaayegi aur to inliven jaayegi in this award winners from the city express, how much have you used, ok, what is its condition, so can it be marks, if all the novels are published in all the interpresses then The full length audio of the output will be the same as that of the input, if it is there then it will also be added, in the worst case there will be complexity around it and it will be drawn in. Okay, so friends, here were the most amazing intervals. Hain Kapkot I hope you have understood this. If you like then like this video and join our channel Eat Food in Craft Korea. Okay, it can be any number of coding problems. Okay, I will try not to bathe but to doctor. And that also helps a lot, so thank you very much for watching and you next time children by.
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
440 |
hello friends happy new year today we will solve the case smallest in lexicographic order this will be the last question we solved in the year of 2020 given integers n and k find the electrical graphically ace a case smallest integer in the range from 1 to n for example if the input n is 13 and case 2 we know that the candidates is 1 10 uh 1 to 13 and then we sort this integers into a lexicographic order and finally we find the second smallest number which is 10. should we generate older candidates numbers no need if we sold them we need extra space and we needed to uh generate them so the time capacity will be larger in this case we only need to calculate how many nodes we can simply return the final result quickly let's see how to do that we should figure out that uh what does it mean the by the lexicographic order that means why this 10 is uh before this 2 because one is smaller than two so one whatever is should be uh before in a come first then the two it's just like a dictionary what that mattered is the first different characters one is less than two so ten is less than two so okay it's kind of like we first to try to get the first character the range is from one two nine and the for the one uh because the largest number is thirteen and we only have nine numbers here so we will try to generate two uh the numbers which has two characters then we have 10 11 12 because we can try to append the 10 characters here so the range is 10 to 9 and 19 but we do not need that much because the largest is 13 so we only need the two numbers here so that is the candidate range and then we need to uh get the second this actually is the index one right um this is the uh first one and this is the second one it's kind of like the pre-order it's kind of like the pre-order it's kind of like the pre-order traversal because we want to know which level we are and we just do the pre-order traversal this is the do the pre-order traversal this is the do the pre-order traversal this is the first one second one this is the third one first one and so on so forth but we do not need to do a explicit pre-order traversal we do a explicit pre-order traversal we do a explicit pre-order traversal we just need to calculate the notes but how do we decide which level are we let's see another example if the n is 123 and we also need a want to find the second smallest number well this part is also one two and the one is uh smaller than the 100 23 so we keep that first search and then we get 10 to 19 right we have actually we have 10 more numbers here but 19 is still smaller than 123 so we keep do the depth first search and then the range becomes 100 to 199 which is a larger zender and so we only need 24 numbers here how do we get this 24 well in this part we can 10 notes right 100 to 109 and in this part we also have 10 notes from 110 to 119. this part we only need a four uh 120 100 to 20 three so this part we have 24 and this part we have 10 notes this part we have one node so in turtle we counter 35 nodes and certified is you know that it's greater than 2 so we know the result is in this sub tree we do not need to go to the sub tree 2 or subtree 3 or sub 3 9. so here's the thing we first need to decide which level should we go and then we decide should we go to um we know in the sub tree and we know for example we know it's in this level should we go to the next node so here's the thing maybe let's write the code first you will understand the logical well the key idea is to calculate the code without the nodes do not need to get an explicit period of traversal the curve is equal to 1 because the first one is 1 and we let k minus 1 because actually the index is not equal to the index for example 2 the index is 1 right 0 1 2 sorry minus 1. okay only while this k greater than 0 we do something and finally we just return this curve if this k equal to 1 we just return this curve which is one because one is the smallest one okay we will call a function called count nodes and we get the nodes and uh if this case great or equal then notes that means we should go to the next sub tree because we count all the notes in this subtree it cannot fill the requirement we should go to the next subtree so that means the cursor increment by one and the k minus the nodes so for example this part cannot fill the requirement so we go to this part so the curve will increment by one if not the case that means when we find it's in this subtree but the problem that we needed to count one by one right so if we go depth so the cursor times 10 because this is 1 this is 10 and this is 100 so the k minus decrement by one because we already called one right okay now let's write the code notes we parse the long and the longer why because we always do the multiple by time by 10 so it'll it will be easier to do to close integer overflow so we just converted it to long but in the end do not forget to convert it to in int okay we call it the turtle so at the first edge equal to zero and finally we return this turtle let's call it we need the next y the next and begin equal true curve oh sorry curve plus 1 because in this part we know this at most have 10 notes because the next is uh 20 minus uh the curve times 10 equal to 10 and the next equal to 20 and this part there we have 100 and the next will also times 10 so it is equal to 200 so we know in this part uh at most they have 100 nodes so that's the use we want to get how many nodes and moles are in this level okay so while this curve less or equal than and we do this part the turtle will accumulate this mass minimum one is there a minus curve plus one is next minus curve uh this part is an right is 123 and this part is curve is current 100 and plus 1 and this is 24 so we use 24 and this 100 is next is 200 minus 100 actually 100. okay so then the curve will times 10 and next will also times 10. we go to next step it just uh go depths i will fill this part there will be an anchor sorry this part should also convert it to inked so for this problem one thing you need to know that is the integer flow problem and the other thing is we just need to calculate the nodes no need to uh do the real pre uh pre-order traversal okay thank you for watching see you next time see you next year
|
K-th Smallest in Lexicographical Order
|
k-th-smallest-in-lexicographical-order
|
Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** 1
**Constraints:**
* `1 <= k <= n <= 109`
| null |
Trie
|
Hard
| null |
208 |
it try is one of those data types you don't really get to hear too much but in this example I'm going to show you how we can use it and how it's really powerful so as you can see the imagine I was trying to store these words so I basically if Amazon amazing a poor a pain the prior application and applicant and as you can save went ahead and calculated the number of characters which I would need to store for each word so in the end I would end up having to store 49 characters to be able to store all these words supposing I was twirling them in other normal data types like an array or a hash set or anything now the idea of the try is that if two words have the same prefix then really there's no reason to repeat that prefix in fifth you can reuse it and then connect the remaining the paths which are different at the end of the prefix so this here in the middle is exactly what a child looked like as you can see the alphabet a is starting for all these words so why would you want to repeat it seven times instead you can use it once and then connect everything to this alphabet and you can implement that idea you can separate even m and a and that you can see they're shared by the word Amazon and the word amazing so basically you build on this idea every perfect which is shared by towards you right that prefix and then you continue with all the words which can like spring from this prefix now the reason why this is so cool is as you can see by using this idea we only need to store ten six characters and you see that's a tremendous reduction of the space we need and so this can be extremely efficient in memory in saving memory and also you can imagine if you were trying to like determine whether word is present and you were using maybe an array you would have to basically perform any operations to make sure that the word is not inside the away but as you can see here in this try if I'm trying to see whether the word applicant is in the Tri I all I need to do is I begin with the first alphabet I have it and I go to second one I have it I followed that path until I have the world applicant so you see it we end up taking me as much steps as the length of the word I'm looking for so instead of going through all the LA I will just be like if it's basically like traversing a tree this is the scalability so and you know it's extremely fast to traverse the tree so this is the idea of the try and now with this idea in mind we are going to go ahead and see how we can actually apply this idea and be able to you know solve some problems so quickly I have selected the question here which is called implemented try using a prefix tree and we asked you to implement a try which has these methods so they you understand to include the method in third search start with now for the method insert there lies that if you want to insert a word we share the certain prefix with the existing words we should first traverse the try until we reach a point where the prefix is finished then we can start appending missing characters now for the such method if we I ask it to search for a word like a / which will to search for a word like a / which will to search for a word like a / which will be though in yes we will begin from the first character and we Traverse with reverse which reverses service until we hit the word apron now when we the world Depot we need to be able to identify that this is the end of the world they won't be looking for because as you can say you might be thinking okay if I were elected to such weather the world up is present in this try would they return true or false now you realize that I have been marking we discard like the end of every word so this is the idea we be using to make like the end of the world so when we traverse the world and we reach its end we expect to find the Mac which tell us that this is the end of this world we are able otherwise if there is non mark it means we are still continuing so if you ask you to figure out whether the world for example up is inside this try you would say no but if there was if we initially had like insulted up in this child we would we should have incited or so a this sign at the end of the world up so basically now we have one two three four five six seven words in this try and that's the idea now for the remaining method start with I think start with this is rather easy so first start with they ask you to check whether there is any word starting wave we've maybe up what you will do is you start from the first alphabet of course and you eat servers and if you see if you wish that prefix they asking you then whether you have a star or not you just return true because you know there has to be something with that prefix that's basically the idea and to save us time I've actually went ahead and implemented these methods so that we don't have to waste too much time so I will quickly copy the code and paste it here and then we will discuss how it works okay so as you can see I decided to use a hash map for this try and there isn't why I'd like to use the hash map for the try is I can keep I can perform the membership shake it very quick and then I can mist my hash map to include additional alphabet so the idea is when I'm asked you to add alphabet age I will come I will check whether I have it first of all in my try if I don't have it and we add it I will add it as a key and I we set its value to a limped hash map so that means next time if I have to add P after a how we add P I will I create a new hash map which has a key of P and then I will nest it inside the value of a which means from a I could go to P and then I will repeat that idea nesting hashmaps as until like the world is finished that's basically the idea and incrementing heaven inside so for insult there are two paths we have to be careful here okay first of all what I take a word and then I'm asking to insert it into my try so what I do is you say this is P is like the current position I will be traversing this road and even suppose the current position of the polenta in the world and then Calvin is what I'm using to store the current data structure I mean for example if I'm starting here current will be try that's what I did he so initial P is 0 and it currently is try now when I'm inserting a word if for example I have inserted the word up and now second rent insert the word Apple you see as I traversed the word Apple from a P another P these are the alphabets which I have already placed inside my trust so I have to cross I have to traverse my try until I wish this second P and then from there and I can start appending new alphabets listing new a bit so the first part of this insert function should be traversing the prefix which as far to go as far as we can go trying to construct this word from the existing try so as long as P is theorist than the rings of world and then the current alphabet in the word wish for example is a is in my try remember at the beginning my try has a as a key and then another hashmap ossified as long as I have that alphabet a in my try what do I do now I set my current to the value of that key a and remember that key was basically another nested hashmap now after doing that I also move my pointer at word and I will move it to the next letter which will be P I really put that I repeat that until this there is no more there is no air if there was if I just added up Andre and I'm trying to add up or there is no air in my try now after he if like exhausted the existing prefix now I need to add the remaining characters from this world so what I will do is I will continue moving my pointer as long as I haven't reached the end of the world they this wasn't ranked inside and then what I will be doing is I take a character and then I created I create its key inside the current position I mean in my tried and then I will set its value to and encash map basically showing you back again to that picture if I was trying to add amazing for example if I was trying to add if I head up and I'm trying to create the word Apple I would have traversed all the way until up and then from here I need to append to keep nesting these two missing characters and every time I add a new character I add it as a nested hashmap so that's what I did here now every time I add a new character I missed it inside the previous one and then I moved my point I like that now once I finish a word I have to mark that I have completed that this word this is a true word is not just a part of some continuous string of word so when I insert a word fully I need to mark it at the end and that's what I'm doing here so at that point at that rust value I will just nest another value which is I will best calculate a new key in the current hash map and I will mark this key as a stanza tip nothing so next time when I will be like rocking whether the word exists when I'm sure passing through across this branch again we need that picture when I'm going all the way down or the way down all the way down trying to figure out without the word ever exist if I reach a star then I will know okay this is the end of the world and which word have a build up software approach then I will eat anxious so this is why we need this style not definite because if you don't have it you cannot tell whether this word is indeed the word up work or if there is something after it because there could be now the second method we ask you to implement is the such now the search is actually quite easy so you also repeat the same idea except that now you don't need to append anything so what you do is you start your pointer in the world you are searching and then you first of all you grab your you try and then you check whether the first character of the word you are looking for is in your tribe if it's in there then you will go inside the value of that first letter which will be it's basically key value and the key is always an alphabet in the value so is another Sh'ma so if the first alphabet exists and we go inside it's very if that if inside that value I find the second alphabet also to exist I will go inside it's very like that it's a very deeply nested hashmap but the whole point is if at one point my please go to the length of the world which means I have found the entire world now I need to check with I if that mark or not as if I don't have that mark then it's a problem because I just reached the end of the world they would what appears to be the world I'm searching for but it's not the end there is no market which means it's just a part of something continuous so when I reach the end of the world I need to check whether there is a Mac if there is I will turn through if there isn't a return force and also if I don't reach if I don't find that word which means if I reach a point where for example I am asking to look for maybe something which doesn't exist in this try at one point I will be like going down and see off now I cannot find the next alphabet of this world it doesn't exist in my track so if I'm cut out somewhere around the way for example suppose this branch didn't exist they append the end brush if it didn't exist and I'm looking for a word that paint I would go down all the way and when I'm at P R we look in the key in the children of P and I said there is no e now I know I have not reached the world the end of world the paint but there is no alphabet e if that's the case then I will just be knocked out of the Y rope and I will turn first and the third method which it starts with I think it's really the easiest because we had basically asked it just Traverse they try and figure out with the weekend we can reach the ask it prefix this would have a slightly harder version of this problem would be where we asked you to like return all the words which can be constructed with this prefix that would be a little bit more interesting and challenging because now you would have to scary Travis that prefix and once you reach its end you have to invoke something like a DFS to exhaust all the possibilities going down from day so you basically if you are interested rakeesha if you're asking for example to return or in the words which could start with up so what you would do is you would show us from a to P to a second P and then you would like initialize your DFS we should go all the way every time it hit a stylish record that word every time it hit a Stiles you got that word and you'll turn like an array of all the possible ways you could construct with that prefix up and the time is out actually this is the way you can build a an automatic in Auto completion system because you know when you are typing in some website that uses Auto completion you type the part of the world and then they we suggest you what to feel what could be the words you are trying to write and then you can just save your time this is basically how it runs you inside you enter your prefix and then some algorithm will quickly run and try data structure to depending which possible routes you could take from there for example just type a and web you could be trying to type Amazon or amazing or something else so those are the two words they will suggest you so as you can see the try it's really useful so for a start with we basically also Traverse we Traverse our try and keep incrementing P if P is equal to the prefix then we know we this has to be something which starts with this prefix then we can return true if we are not doubt of the wire of premature world it means a certain alphabet from the prefix does not exist in the try and that means there's no word starting with the prefix we are given so that's very time force and this would basically do it and it works cause I had like previously checked it so I will just submit it now and as you can see it's in it's faster than 90 something percent which is not that much accurate but it says something about the efficiency of the algorithm so basically this is the try if you don't understand the code go ahead and try it try to understand how we missed these hashmaps I think that's the key understanding how you miss the hashmap and then you nest another one for every data I think that's the key to writing this dry data structure thank you so much let me know if you enjoyed this video and if you like my content or if you want to encourage me doesn't hurt to subscribe or share your like just do it you really feel like doing okay thank you I'll see you in the next video
|
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
|
459 |
hey everyone welcome back and today we'll be doing another lead code four five nine repeated substring pattern an easy one given a string as check if it can be uh constructed by taking a substring of it and appending multiple of copies of a substring together so we have a string a b so if a b is a substring then we can just make a multiple copies of it and return true because it is in a manner you can say a b and this is not the case with as two example two and so we'll be running false in that case and in example three ABC four times so we'll be turning true because ABC was our substring so that's it there are many messages to do this but what we will be doing is just making a new string which will be S Plus s that will make the copy and add it to the very end and then we will pop the very first and the very last element and then we will check if not for if s is present in our new string then we can just return true in the else case we can say that it was not present and we will be returning false and that's it let's see if this works or not yeah this works so what is happening here is if we have a b then we are going to add a b at the like this and it will pop the element from the last and the very first so if a b is still present which it is present you will be returning true and for the example a b a Aba we will be adding APA yes A B A is a string we will be adding ABA again A B A we will be popping the very last and the very first so if a b a is present no ABA is not present will be turning false it in that case and that was it
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
485 |
Hello gas I am just Amrita welcome back to me channel technosys sonrly court series today bill b solving problem number four 85 date is max consecutive descent so let first understand d problem life en binary aernammas return d maximum number of consecutive once in the are so in the Example You can see they have bin Jivan Namas are which has these numbers so they have you return d maximum once correct consecutive three is maximum number of consecutive one so they are returning three so every you can see one you and one so you are d maximum Consecutive one so they can return you so let understand what approach they are going you solve this problem so let take example your date is one zero one right so they have you basically find de count of maximum Consecutive once okay so They are going to take you variables one it count in which they are going away d count of once and one more variable they need you take off date they can say d maximum count so both they bill initialized zero so they are going to travel from D First Element Let Me Write D Steps Also If Date Particular Number Is One They Are Going To Increase D Count Right So In D First Element Number Is One Yes So Increase D Count So Count Becomes One And They Have You Updated D Maximum Count Also So Maximum Count is zero no and count is one so that is maximum one right so maximum count becomes one move too d next element can number is one yes they have too increase d count counting too that is maximum too maximum count also becomes next number So date mains you can say counter initial count consecutive ones correct so no maximum counts style remains tu maximum count is style tu no move tu de next element again n is one so we are going tu increase de count is one but maximum count is already Maximum so maximum count style remains today tu no move tu d next element they have found one increase elements next element county tu so they need tu update d maximum count test on d maximum count so date mains are output is three in this how write d method So firstly what we are going to do is we are going to initialise tu variable one per d current count let take it a current count and another one would be b per d maximum count and let them we are going to travels 0 tell d last element equal to one Give what do we need you update de count sorry it would be maximum of max count and current account which ever is maximum date would be up maximum count and if number going you do we are going you reset are current count you zero turn the maximum count because it is holding d maximum count of consecutive once right so this is ho we need you solve this problem no let go back you are mean function let take d say number date was one zero one program example you can see Maximum Output Is Sorry Maximum Amount Take Some More Examples Like This No Way Have The Maximum On This Problem
|
Max Consecutive Ones
|
max-consecutive-ones
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
|
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
|
Array
|
Easy
|
487,1046,1542,1999
|
352 |
always welcome to deep codes and in today's video we will discuss liquid questions 352 that says data stream as disjoint intervals so this is the problem of the day uh and yeah I'm sorry for uh that I'm making a video very late uh usually I make the video of the daily question in the early morning but since I was traveling today from early life around 4 am so I was not able to make the video okay sorry for the late video okay so whatever it may be the reason now let's focus on the question and the approach part so talking about the question is here we are given the data stream input uh of a non-negative integers and we need to non-negative integers and we need to non-negative integers and we need to complete two function one is ADD num and second is get intervals so this ad num will tell us that this value is to be added to the data stream and get intervals is we is where we need to return the intervals in the form of vector end uh and uh so the intervals has two elements only it is the start and the end of the element and uh let's say if you have elements like this so yeah if you have data stream like this one two three five seven eight ten like this so the intervals here are one two one comma three Phi 7 comma eight and ten see it is 10 comma 10 here also 5 comma five so these are the different intervals that are possible for this data stream see one comma three y because one two three are continuous elements five there is no continuous elements from before and after it so the interval is five comma five so these are the different disjoint intervals that we are trying to find out from the data stream got it now let's take a look at the first example to get better understanding so initially we have no elements in this area then we added one uh element one so the current area is this and the disjoint set is one comma 1. then we added three here which is random uh and we call get intervals so the intervals currently are one comma 1 and 3 comma 3. then we added seven so the intervals are one comma one three comma three seven comma seven then we added two so here where so here it is when the changes come so initially it was one comma 1 3 comma three because there was a break two was not present but now we have two so we can combine it and form one interval that is one two three okay and this remain as it is seven comma seven now we added six so here one two three was already there so now instead of seven comma seven now seven has one element before it so it forms a continuous interval six comma seventh so we modified this to six comma seven so yeah I hope you guys understood the question that every time we add one integer to the stream and we try two hundred intervals after adding that integer uh and you also I hope you also understood that how the intervals are formed means what is the exact meaning of the intervals uh now one thing to keep in mind is total number uh the value is 10 is to 4 and at most 3 to 10 is to four calls will be that of random and get intervals so if you um let's say if you add all the values keep on adding the values in one vector and then try to generate all the intervals at all times at all calls then it will give you tle so here what we have to do we need to uh let's say we need to pre-compute an answer and every need to pre-compute an answer and every need to pre-compute an answer and every time if we when we are adding one new number we will add uh those that number in the previous intervals by checking some of the conditions so for this type of question about what I suggest you that see looking at this question there is no DP this is not a DP equation you can see that this is not a graph or treat this equation not an English or sorting type of question I am trying to tell is there is no definite data structure that can be used here so for this type of question what first thing you need to do is you need to generate different types of test cases that are possible so if when you will try to generate these sales cases you will get more idea of how to solve this question okay so here I have taken a few test case uh to explain you the creation mode uh in more depth yeah so starting from the first so if you have if currently in the intervals are one comma three seven comma nine and you uh and the that is one function call to add num of integer 8. so uh after this what would be the answer one comma 3 would remain as it is also 7 comma 9 would remain as it is because 8 lies in uh seven comma 9 right so we'll get answer as it is the original intervals okay now let's take a look at this example so if you have this as a current interval and if you try to add a number four then what would be our answer would be 1 comma four and seven comma 9. so here 4 whatever 4 was just at the boundary so what we did is four so four was at the boundary we just uh we made this equal to 4 right the end of this uh interval got it so this is how we read here so if this is the case where 6 is just previous of this interval and what we will do 6 comma 9 right just because it was just before the starting of element of this interval okay and if you have something like this one comma Phi 7 comma 9 and 6 is between 5 and 7 right then what our answer will be 1 comma 9. okay because see uh it would be 1 comma six and also 6 is also previous of seven command and then six comma 9 then combining both field games same one common name right and if you have let's say current uh interval is like 1 comma 3 and 7 comma 9 and you get uh add num function call with a value let's say 11. so if there is an element there is neither a part of this or not a part of this then what we would simply make a new interval so So based on this what you saw that we are either checking so if element lies in between or some of the intervals then we are checking with the previous element or to the next element right this is the previous element this is the next element if it is neither a part of any of the intervals then we simply add a new interval learn comma 11. okay so if you have let's say if you have large data stream like this one comma three two comma sorry uh five comma nine ten eleven comma 17 comma 25 29 comma 33 so if you have a large number of intervals like this based on the status stream of the previous data stream elements so now you have uh now there is one function and num function is called for the element let's say 10 okay now in order to find where in order to check this condition what we have to do we have to find that point where time will come so as you can see here the 10 will come after this ending of this and before starting of this because after nine this is the ending interval is nine software this 10 will come in the starting interval z11 so before that 10 will come this is correct right so we can find this point so this point can be fine by using lower bound that is what lower bound does right so a lower bound is basically you can say it is a binary search only some similar logic of binary search is used here so if you get a lower bound then we will get index of this and an interval the whose value is less than 10 got it so we will get lower bound with value uh with uh indexes so if you get this index then wouldn't would not it be easy to add this element so if we get this index and we would have to check for this element and this element so if it is the case like this uh let's say here uh so we are only checking this element here uh if this element only right and if a element lies between this then it is then we don't have to worry anything right we will simply return from our answer so what you understood from this intuition from this test cases is whenever you try to insert a new element you check for the where it will lies means you check for the lower bound index uh of that element from the intervals I got it so using this that so using this lower bound we try to add this element by checking this condition we will simply check all this condition and our answer would be done that's it okay so yeah uh so talking about the approach we will use a lower bound to find found the index uh if when we find the index we check for all the condition that is discussed here and uh generate or make changes as per the condition and return s but this is simple as this once you have so once you understood this logic of lower bound then why we are using lower bound here because we won't be adding 10 anywhere other place we would only have add this element at a certain place and to find the certain place we need to find the interval whose value is just less than 10 right so that's why we are using lower bound so I hope you guys understood the intuition as well as approach for this question so now let's move on to the coding part okay so now let me make here Urban Vector of vectors uh interval okay now let me take one n as a interval oh let me keep this at simple I and B for faster typing find me dot size let me also initialize one Infinity uh variable and initial S2 into max so yeah now what we need to do uh find the lower bound in index is equal to lower pound of invert intervals dot begin s dot and we need to compare something compared with the value and minus intervals dot begin so this is how we will get the index right this is a syntax of a lower part but one thing to note here is this is Vector of vectors so we can't add a directly value here what we need to do we need to make one temporary Vector we would push uh this value into this temporary vector and we would pass this here so if it was simple Vector in intervals then we would only pass directly value but here since this is the case so we need to pass one vector with uh and we inserted this value right now once we get the index we need to check something now let me take one some in uh variables like restart p and next start okay so what are you might be wondering like what are this pre-star PE and like what are this pre-star PE and like what are this pre-star PE and external next time so yeah if this is the lower bound then this is the pay start then pre and this is next that this next time for uh element 10 right now we would check for if index is less than zero okay so that means uh let's say uh if our interval starts like this from let's say three comma 5 7 comma 9 and our number is let's say one so it no so there is no intervals before whose elements or whose values are less than one so in that case our index would be less than zero and in this situation we will simply make restart equal to minus infinity and three and equals to minus infinity that's what we would do we would make pre start equals to the value that is intervals of index of 0 p and intervals of index of one correct one thing to note here is we also need to do integrals minus 1 because to make it zero Index right now for this next start and extent if index is greater than n greater than or equal to n then in that case what we would do we would make uh next start equal to Infinity next and equal to infinity and else is we will make next start equal to intervals of index of 0 and next and equals to intervals of index of one okay I think that you got till now what is our next task is to check for all these four conditions that I discussed for before not the first condition please let's say if value is greater than equal to pre start and end value is less than equal to 3 and or it is greater than equal to next start or the values less than equal to next and that means that the element lies in some of somewhere let's say for eight it lies either in the previous or in the next interval between the next interval like seven to eight like next Dot and extend or either P star and pre n it lies somewhere then what we'll do we do not think we simply return here from here because we don't have need to make any changes we didn't made any changes here because that's already included right now in the else condition in the relative part uh in the also part what we would do we would code for this situation uh let's say first let's say quick code for this in okay and what we will do it if p and equal to Value Plus 1 and next start equal to Value minus 1. that means for let's say at number six the pre and equal to uh sorry the pre and plus one equals to value and next at minus 1 equals to Value so here for this condition if let's say pre and plus 1 equals to value and x dot minus 1 equals to Value then what we do this pre-start if we make an what we do this pre-start if we make an what we do this pre-start if we make an entry it is this interval and we make interval uh with the pre-stack and next interval uh with the pre-stack and next interval uh with the pre-stack and next end so what we do interval of uh index minus 1 of 1 equal or equal equals to next and right and we it is the second interval dot it is uh What uh what is that uh iterator would be NV dot begin and plus idx okay so this is the thing we did here we it has a second iterator sorry to be it is the second interval and change now moving ahead what is our next condition remaining this condition is remaining where we simply increment our pre and here so that is if pre and plus one equal to value then in this case what we do we would make in intervals of index minus 1 of I equals to value right and there is condition if next start minus 1 equal equals to value in that case we would simply change the next start that is index of 0 and we would modify this value to value for it anywhere else condition if nothing is there then what we simply did we simply added the intervals yeah that's the same thing we are doing here find me Dot pushback where we will push we would push at the index position not let us begin plus idx comma the value is value common value right okay yes and in here do simply return aim week that's all we have to do nothing here everything is done in this add num function now let us try to run this code okay it is this smaller yeah that's it v a r u e okay the thing here is we can't make it push make we need to insert at this Index right that's the syntax okay one thing you need to note here is here it will be less than equal to zero right because we are using minus 1 here to get the previous index so if it is also zero then also we have to make restart M3 and S negative of infinite so yeah now our code got accepted now let me try to submit this so yeah as you can see our code got accepted and now talking about the time complexity would be big of n log n because of this lower bound function that we are using and the space complexity would be because of and for uh and uh for let's say n number of intervals you can say there or you can say for n number of uh this and number of values so that is the maximum possible uh space and the time complexity and log n and we go find so yeah that's all from my side today hope you guys understood the question the approach as well as the code part here uh and if you have any doubts still let me know in the comment section make sure to like this video And subscribe to our Channel thank you
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
77 |
hi this is question combinations in this example n equal 4 and k equal to and these are all possible combinations and each combination has number between 1 and n and every compilation has exactly two numbers now we will use bitmask to solve this question now n equal 4 that means the possible numbers are between one and four so we have one two three four these are the multiple numbers now assume we have value mask and this mask in its binary representation there are four bits this is Bit Zero and this is bit one this is bit two this is bit three now this bit zero tell us if this number exists or not in The Mask so if this bit is set to 1 that means this number exists if it's zero that means this number does not exist now for a bit at index one is it will tell us if this number exists so if this bit is set to 1 that means this number exists if it's zero that means this number does not exist then bit two will tell us about this value three if this is one that means three exists in this mask or in this combination if it's zero that means this number does not exist the last bit is for this number if it's one that means this number exists zero that means this number does not exist for example if we have mask in its final representation zero one zero this in decimal equals six so here we have bit one and bit two exist that means this is bit one and this is bit two bit one is for the value 2. B2 is for Value one that means this mask tell us about these two values now what we will do is iterate over all the numbers from one up to 2 to the power n minus 1. which is equal to 15 so we have 15 possible combination and for every number starting at I equal one first of all we need to check the number of bits set to one so the binary representation for one is zero one so here we have only one bit set one and that means only uh this number exists in this combination and because the number of bits sit one is one that means this combination is not valid because we need k equal to so we need two bits in The Mask to be set to 1 in order for this combination to be valid so here we check if the number of bits equal to okay if not we just continue next is I equal to a binary presentation for 2 is 0 1 0 and again we have only one bit then I equals three now a binary presentation for three is zero one now we have two bits it one that means there are two numbers in this combination and this is what we need then in this Loop we need to know which numbers these bits represents so this one at with zero present this number and this bit represent the 2 so we should return one and two and we should push to answer this one and two and this Loop simply it's red from J equals 0 to J equal n minus 1 because we have in bits so it checks for every bit J represents the best index so we start with the first bit 0 we set this bit 0 to 1 so 1 shifted to zero equal one two zero this equal one in binary now I equal three it's binary representation is one zero so ending of these two values will not be zero so this condition apply and that means the first bit is it so this is J equals zero and J equals 0 tell us that the first number exist so we push to the vector the number J plus one so J equals zero tell us if it exists or if it said it will tell us number one exist in The Mask J equal one if it sit in the mask tell us if number two which is real plus one if the bit at index 2 is set 2 is 1 shift by two is zero one zero if this bit in this case it's not set if it exists it will tell us if a value 3 exists J equals three this is the bit that industry if it exists at the last value number four exists in the number so here in this mask we have only these two value one and two so we push to the answer this combination then we move to I equal 4 the binary representation of four is one zero we have only one bit set so this is invalid then I equal five the final representation for five is one zero or uh zero and zero one four it's zero one bit so it's invalid four five one zero one here we have two bits and these two bits tell us that numbers one and three are in this combination because this is Bit Zero and this is bit two so bit 0 is for one bit two is for three notice this is J zero tell us about one js2 tell us about three this is why here we push J plus one so this is uh one and three and as you can see here we have one and the three then I equals 6 final representation 4 6 is 1 0 again this is uh two bits so this is valid combinations and the numbers are 2 and the three because we have J this J is one and this at J equal to so the numbers are zero plus one which is two and J plus one which is three so two on the three is valid combination this one I equals seven and binaries one and this is invalid because we need only two bits then I equal eight one zero this is invalid because one bit and I equals nine in binary this is one zero one this is valid combination and this represents the number four and one so here we have four and one then I equal 10 binary representation it was one zero this is valid and this represents one and three so or this is bit one so this is for the value 2. and this is for bit three J equal three so this is for value four so two and four and so on until we cover all the combination now what's the time complexity for this uh this Loop we have 2 to the power in and only um the combination that have bits hit equal to K we'll enter this condition so we have 2 to the power n minus the combination for this which is in select key multiplied by this is n so this is the time complexity and in the worst case is 20 so 2 to 4 20 plus 2 to the power 20. minus 20. K multiplied by so this is combination and 20 to the K this means 20 factorial divided by 20 minus k factorial multiplied by key factorial this is for this concentration and here we have 20.
|
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,679 |
hey everyone this is side hope you are doing good so let's start with the question so the question is maximum number of case sum pairs okay so what you are given an integer that in nums and an integer k what you have to do in one operation you can pick two numbers from the array whose sums equal k and basically you have to remove them from there so what you have to do you have to take two number at a time and you have to do the sum if the sum is equal to k you will take it and remove them from the array and you have to return the maximum number operation you can perform on the array okay so let's understand with an example okay so we have given this array and a k okay so this is our array one two three four if you can see our k is 5 so what let's say we will take two numbers so sum equal to uh 5 so as you can see this and this so basically 1 and 1 plus 4 is equal to 5 so let's take a counter variable so it is zero but after this it will become one okay now you will mark you will take this so you have removed that now you can take it from like you can take this two also so two plus three years is also five so you can't take the same element again and again you have to take always distinct element so 2 plus 3 is also 5 so you will increment your counter and you have removed them from your array so your array is empty and you got your final output as c equal to 2 so this is the final output okay uh let's see for this case so we have 3 1 3 4 3 okay one will be this 3 and this 3 so 3 plus 3 is equal to 6 then can you see for like we don't have any other operation like 1 plus 4 is also 5 4 plus 3 7 so we only have one output for this case okay so i hope the question is clear to you let's see how we can approach the question so what will be the name approach if we see the question so what we can do is basically we will go by two loops basically we will start from i start from 0 to n and your j start from i plus 1 to n okay so what we will do we will check if nums of i plus nums of j if it is equal to k we'll increment our counter and we'll also do one thing we will mark them as some let's say we will mark them as minus one this will be minus one and similarly this will be minus so we don't have to take the same element again and after this we just written our final output as c okay so if you calculate a time complexity for this is uh this will take you can see that we are running two loops so it's a order of n square okay but if you can see in the condition the length is 10 to the power 5 okay so if you submit by this approach it will not submit it let's see how we can optimize it more okay so with our previous approach we take the time complexity as n square okay so let's take the example again so we have one two three four and k equal to six okay so what we can do is instead of using two loops can we do with only like with one loop only okay so what we can do is we will use two pointer approach basically so we'll use two pointer how we will use two pointer first we need to sort the array why we sorted i will explain you in two pointer but we need to sort the array okay this array is already sorted so will not anything sorted so we will not sort it so what we'll do we'll take our start from here and we will take our end from here and we will check if the sum of basically if nums or let's calculate the sum first so sum equal to nums of s plus nums of and so if it is like if sum is equal to k what we will do we will increment our counter so we'll increment our counter and we will increment both of them okay so s will also come right here and e will come before so we'll do s plus and we'll do e minus okay but let's say if some is greater than k okay so by using this approach so if you can see your sum is greater than k okay so if we take our end basically if we increa increase our s then our sum will also increase okay so if you can see for this our sum is uh for this it is five okay so sum is uh one plus four equal to five okay right now it's matching it this condition let's say our sum is six okay so if our sum is six and if we have to move out of one point either we will move s or either we will move e okay so let's say we'll increase rs okay if we increase our s pointer if we come at here and if we again take the sum so this is 4 plus 2 6 okay you can see the sum is being uh increasing when we increment rs okay so instead of increment rs what we will do we know like if we increase this as our sum will also will increment so we will decrement our end okay so whenever our sum is greater than k we will decrement our end and else if our sum is less than k that means we need to increment our sum will move our s in that case okay so let's debug this with this example so our sum is five only for this case okay so we'll increment our c so c will become one and we'll increment our both pointer s will also come and e will also come now we'll again take the sum so 2 plus 3 is 5 again this will lies in this condition only and we'll increment our c okay so basically we'll do while s less than e and we'll then do this operation okay so if you calculate the time complexity for this is uh first step what we are doing is we are sorting the array okay so for sorting it takes order of n log n again and after then you do order of n operation okay so if you do with this approach and our constraint is 10 to the power 5 it your code will be submitted okay there will be one more approach which can which we will do in only or in order of n okay so how we'll do it let's see okay so whenever the question related to two pointer there is one more approach we can use is map okay so what map help us to do is it will solve the problem in order of n but it's take extra space also so but it optimize our time complexity we increase our space but with map approach we will optimize it so what we will do we will take a map okay and we will uh basically will take a map of int off end okay so this will be element key will be element and if this value will be its frequency so we'll start from here okay so before inserting into the map we need to check if your map contains k minus x k minus your current let's say this is thumbs of i if it is contained then do something else you just have to put it okay else you just put n map okay so it's this uh if you can see the problem is like a plus b equal to k okay if we know what is a and we need to know like whether a present in map or no how can we check we can directly check a is equal to k minus b so if k minus b is equal to a that means a is already in the map and we already got our b that is current okay so what we will do we will start from here and we will check whether k minus basically 6 minus 1 is 5 is it present sorry it is 5 only so 4 basically 5 minus 1 which is 4 whether it is present in map no it is not written so what we'll do will push it to the map okay so this is 1 and having a frequency of 1 we'll move further we'll come at this position uh again we check k minus num so 5 minus 2 equal to 3 and that is also not present so we'll push it into the map then we come at this position we'll check for this uh if 5 minus 3 is 2 now you can see 5 minus 3 is 2 and that is present in your map so what we'll do we'll increment our counter and we will remove it from the map we will only remove it when our frequency becomes zero let's say there are multiple two so we will remove its frequency first okay so this will become zero and we'll just pop out okay now you come at this position your c is already becoming one you comment this so five minus four is one and one is also present so you will also remove it and this will become two so if you calculate a time complexity for this is order of n and space is also order of n we are taking so i hope the approach is clear to you let's write the code so what we need uh we need a map okay so we'll take a hash map um because we don't need to maintain any ordering okay so we'll take a counter variable and we'll just return this counter so what we will do we will iterate over our map sorry array and first step is to check let me take a variable so let's take it like uh basically k minus x okay so let me just write it in a comment it will be x let's take x plus y equal to k okay so let me just give the y value let just one second so this will be x plus s equal to k so we want to know no value for result equal to k minus x okay the first step is to check if map dot contains key this result if it is contained then do something else you just have to put it map dot part x map dot get or default so let's say if the same element is present so increment its frequency otherwise pointed zero there and do plus one uh now what we will do first step is to increment our counter now we need to check if map dot get result is equal to one so that means only one frequency is there so we'll remove it from the map okay else what we will do we will decrement it value by one with result map dot get a result minus one okay yeah this looks good to me let's run it okay this is accepted let's submit it yeah hope you like it thank you for watching video and do join the telegram group if you're in doubt in any concern thank you
|
Max Number of K-Sum Pairs
|
shortest-subarray-to-be-removed-to-make-array-sorted
|
You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], k = 5
**Output:** 2
**Explanation:** Starting with nums = \[1,2,3,4\]:
- Remove numbers 1 and 4, then nums = \[2,3\]
- Remove numbers 2 and 3, then nums = \[\]
There are no more pairs that sum up to 5, hence a total of 2 operations.
**Example 2:**
**Input:** nums = \[3,1,3,4,3\], k = 6
**Output:** 1
**Explanation:** Starting with nums = \[3,1,3,4,3\]:
- Remove the first two 3's, then nums = \[1,4,3\]
There are no more pairs that sum up to 6, hence a total of 1 operation.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= k <= 109`
|
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
|
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
|
Medium
| null |
1,704 |
hey everyone today we are going to solve lead problem number 1 1704 which is determine if string halves are alike this problem has been asked in Amazon maybe it was asked in screen around because it's a pretty simple problem okay let's have a look on the problem statement in this problem we are given a string s of even length Okay and split the string into two halves of equal length and let a be the first half B with the second half okay as it is of even length so we can easily divide it into the two half of same length first half is a second half is B now next paragraph is two strings are alike if they have same number of WS okay and S contains only uppercase and lowercase letters what we have to return is return true if a and b are alike otherwise return false what are a and b a B and B are the first half and second half of the given string let's say uh our string is s whose value is book is given to us so first of all we have to split it into two halves of same length first one is a is B and O and the second half is B what is b o and K so this is our first work and the second in the second step we have to compare the number of in each string so in a how many vels do we have only one V and in B how many vs do we have only one if both are same we will return true from this is what we have to do okay let's take another example here our string is textbook this is a string given to us it's always of even length so we can easily divide into two half if we divide the first half will become t e XT and the second half will become b k okay we have divided it divided this into two half and in each half we will count the number of vels V count in first string is only one because e is the only wal and wal count is second string is o which is two and what we have to return is we have to return W count one comparing with W Count 2 which is false in this case uh I think now it is clear to you our first step is dividing into the same half and the second count is counting wals in each half and comparing them okay now if we are implementing the same approach that uh we are given a string and we are taking two substrings and string variable a is having the first half string variable B is having the second half and then we will compare it and count the number of vels in each half what is going to be the time complexity and the space complexity in this case here what is time complexity order of n because we are going on each character only once first of all we are splitting it and then we are counting the number of ovs so splitting will take order of n time and Counting wals will also take order of n time so the time complexity will be order of N and what is the space complexity we are taking these two variables to store our half of string in total we will be storing the same size string so space complexity will also be order of n so this is the time complexity if we do the Brute Force as mentioned in the problem statement but we can slightly improve it by not taking these two variables because we are already shared that it is of even length so we can directly iterate one pointer can go from this to this and the second pointer can go from this to this and both are having same length let's say k length so we can run a loop K times twice by and check the number of WS if I run the first time I will go from index0 to n by2 exclusive K * let's say and I will calculate the * let's say and I will calculate the * let's say and I will calculate the number of vels in the first string and after that I will loop from n by2 to n and count the number of Ms in the second string and ultimately I will compare these two values if I do in this way I'm not taking any extra variable to store the SEC uh halves of the string so here what will be the time and space complexity time complexity will remain mive same in the order of n but we are just doing one iteration we are not even um adding complexity of splitting it into the two half we are just iterating over it once so order is time complexity is order of n Only a single pass and space complexity is constant we're not taking any extra space just couple of variables to store our answer okay this is the optimized approach and let's code this problem let's start writing the code int n equal to S do length Okay now we'll capture the wal count in the first half and second half for that uh I can take a string b e i o u n capital a e i o u and I will check each character whether that character is present in this v string it means that is a w otherwise that is not a v you can also write a separate utility function for that by comparing it or maybe using IF FS or using string contains function like this and let's say for the first loop I will go from 0 to I less than n by 2 I ++ ++ ++ if vels do index of s do character at I if the index is not present in the string it means it returns minus one so if it is not equal to minus1 it means that this character is a wal and in that case our wal count for first string will be incremented for that I'm also taking two variables int vc1 equal to 0 in the starting and VC 2 is equal to0 I will also run this loop again from n by2 to I less than n WS index I here we see two will be incremented and in the end I just compare wal count in one string is equal to W count or second thing if it is false it will return false otherwise it will return true okay let's test over sample test cases here it is working fine I'm submitting the problem it got submitted successfully hope you understood the problem thank you guys bye-bye
|
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 |
723 |
hey everybody this is Larry this is me going to do week four of the August weekly challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this Farm it is a premium Farm I haven't done it before yet apparently so let's take a look Candy Crush a game that I played a little bit like I don't know how many years ago but I think my I wonder if my parents still play but anyway uh yeah this question is about implementing a basic elimination algorithm with any question given M by n integer array represent the grid of candy where portavizer is the I sub J um represents a type of candy or while you're a board of IJ as you go to zero if that cell is empty Okay so you crush question okay anyway uh this uh I finally got a lot of negative scores for some reason okay you need to restore it by a state of the game okay if three of the question more at once these positions my crushing candies according to the following rule what does that mean I don't know that I know the rules but okay seems like it's gonna be an implementation heavy problem though not much I'll go so let's uh see if we can do it together okay so this is the initial Port here uh huh where does the one come from and they give an example but it but they're just like random arrows and they don't have words you can use them it's fine okay let's see if three of the Jason vertically or horizontally customer at once simultaneously if an empty space on the board has candies on top of itself then they drop okay after the above step there may be exists is that how can I don't feel like I would I don't remember much about Candy Crush but I feel like that's not how that game works but maybe I'm just wrong it's been a long time then we turn the current board okay so basically you just try to get like vertical uh yeah you just try to remove stuff and then kind of simulate right okay I mean I think that's fine uh I don't think there's anything tricky about this per se but let's think about what the worst case scenario would be right um I don't know like it's just gonna be some expensive thing uh 50 by 50 um yeah I'm not sure that I know to be honest it just seems like a really annoying problem so we Frank um for implementation wise like I don't think it's hard I think everyone understands it but yeah um how many times I'm trying to see if I think if there's an upper bound right so if so there's 50 by 50 so that's 2500 cells if you if for whatever how each one removes was it three at a time so that means you have to do 800 iterations ish so 800 times 25 I guess that's like roughly less than a million oh roughly a little bit more than well it's about like 2 million right so I guess that's fine complexity wise if you're slick about it which I don't know if I will be but you'll see all right so yeah um so okay what are we doing uh I mean I think we just kind of see uh I mean it is what it is so uh um question Maybe and then now this is the annoying thing right I think the beauty of this three in a row thing is that you actually don't need to EXT like do anything that clever at the cost of doing duplicate work and I'll show you what I mean but we'll see if this is fast enough if we have to optimize right so basically if Board of X Y is equal to point of x y plus one is equal to Port of X Y plus two then question of X Y you're going question of X Y plus one even y plus two basically true and this works because if you go to the next space it will still be true so we have four in a row you just can't do this comparison twice there's some like overlapping logic and maybe it could be better but we'll start with because um for this particular problem I anticipate the implementation with a really annoying tricky part so I want to make sure that um at the very least you know let's get a uh given of a TL use which I don't know time limit exceeded um you know let's at least get a working solution and then we can figure out how to optimize afterwards right that's not prematurely optimized for that reason but uh yeah and now we do the same thing but for the other uh and you could probably write this like in a cleaner for Loop way but yeah but it's fine for now okay um so that's good enough for the question right and then now we have to remove stuff how do we want to remove stuff I mean we the easier way is just to create a new board but and then now for so we want to do column by column because things drop I think X and range so then now old Y is equal to zero maybe um on an ox side yeah so then here while the board of o x is um is equal to zero or uh and of course you have to make sure that it is within bounds dude and then if Ox is greater than a r then we break otherwise maybe this should be default to zero I suppose otherwise new board of X Y is equal to all part of o x y and then after that we increment yeah this should be fine I mean it may all I'm just thinking about what happens if this goes over R but then I think in the next Loop it should be fine yeah and then afterwards both as you go to the New Port and maybe that's good enough we'll see it may also just be infinite dupe because I have some oh yeah it should be infinite Loop because I forgot to uh I forgot to have a breaking condition whoops can I can't even minimize this I have to wait for it to okay yeah of course um so this breaks if nothing fell also yeah no this is fine but and nothing fell if Boyd is you got a new board I suppose but we can also if nothing got crushed I suppose so yeah uh so wearable name is tough part again uh I think I'm just gonna go ahead and done this to go to true and then if someone got crushed and then it's gonna Force we want to do one more elevation uh and then if done then we break um so we don't have to do all the other for it all right let's try again hopefully this time it actually terminates like I said I do worry a little bit about um uh you know this problem because it's implementation I don't think there's anything uh of governmentally that annoying uh it's just you know simulate and Crush but uh but it's very easy to have typos as well is that what I mean imagine so here one thing that you can do as a trick is just do it for like two iterations and then see what it gives you right and just even one iteration and see if it's at least simulating one thing correct um the problem here is that it's kind of really hard to read um seems like my output is the same as the input so that means that after one iteration it doesn't do anything uh and that may be it's true because I didn't do anything I just realized like I did stuff about crushed but I didn't um it's supposed to be here as well uh if this is true uh so we want to skip it if now this part is the one part we don't skip it if the original board is zero we skip it if it's crushed I messed up the condition on that one okay let's try again at least it should be crushing some stuff yeah all right let's try one iterations at least but you can see the reason why I was able to kind of find that and I didn't I don't know that I made a good job showing it is that I saw that nothing got crushed right so that's why it was an issue uh here oh I see I messed up the X Y or I messed up what's on top and what's on the bomb though they tell you on example one so I think I crushed upwards almost but that's fine that's an easy I mean I don't know if it's easy but it is there's definitely a way to fix it and I don't really have to even change these parts because that's a metric so I just have to change this point so what are we doing instead so we start at all minus one so while this is greater than zero if this is less than zero we break and then we just subtract it hopefully this is good enough uh like I said we're a user make mistakes so I'm not super confident about it uh yeah still um am I throwing this way maybe um I think this should be okay but what am I doing well so the reason why I'm a little bit awkward is that um you can see that there are zeros here at the bottom right so at the way Lisa should crush down does that means I'm doing something really well um is it this part I'm starting uh yeah I'm starting at a zero so of course this is gonna be one whoops I forgot to change this as part of my fixing the bottom thing okay so this I mean it's not a final answer obviously but I can see that at least the top like some stuff fell down uh this is very hard to see to be frank uh so we'll see uh I mean I'm just being lazy so uh if this doesn't still it's not going with the right answer I'll just write another visualization uh it seems like it's taking a long time so it is probably not uh so yeah so let's visualize One Step then and sometimes it's easy it's worth um writing a helper function so yeah so we put it a row at a time is what I want to do so that you kind of see them like align them a little bit better yeah it's again like this but okay so you see stuff for sale so after one iteration it seems to be what we expect so maybe our simulation is right I'm looking at the uh I'm comparing to examples so it seems like we're right but maybe my Loop isn't done my Loop isn't good oh I know oh that is silly I have to check that I mean that this isn't zero that's why so yeah report of X Y is not zero because that's just empty and it will always match some say well I guess this is why um foreign so let's add that check okay there we go a couple of silly mistakes or just uh you know we'll keep this just in case we need it later uh just uh ah there we go cool uh yeah what is the complexity here um I figured it's gonna be in the worst case it's going to be N squared or I don't know if it's easy to generate that case I'm gonna say n Square I mean the size of the input squared right quadratic so technically it's the size of input is 50 by 50. um because that's all times C so n is equal to all times C in this case kind of and so it'll be that square um I don't know that I mean I don't know if that case is reachable so maybe you can prove a title upper bound but off my head that's what it would seem like to me in that like every iteration you remove three elements or something right and then like Cascade three day and then so forth I don't know how to construct that I'm not gonna lie but I mean you probably could construct it the other way but uh I don't know yeah I don't know but in theory that's what I would think uh yeah it's an editorial today tell you about the worst case uh yeah that's my complexity I mean in place is fine yeah I'm not gonna look over it in place uh yeah uh that's all I have for this one there are a couple of silly mistakes but otherwise I think we actually did pretty okay like I just kind of confused up and down uh and also just forgot about this case bit but it's hopefully it showcase my debugging skills a little bit as well so yeah um that's all I have for this one stay good stay healthy to good mental health have a great week everybody I'll see you uh I'll see you soon anyway bye
|
Candy Crush
|
candy-crush
|
This question is about implementing a basic elimination algorithm for Candy Crush.
Given an `m x n` integer array `board` representing the grid of candy where `board[i][j]` represents the type of candy. A value of `board[i][j] == 0` represents that the cell is empty.
The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
* If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty.
* After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary.
* After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
* If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board.
You need to perform the above rules until the board becomes stable, then return _the stable board_.
**Example 1:**
**Input:** board = \[\[110,5,112,113,114\],\[210,211,5,213,214\],\[310,311,3,313,314\],\[410,411,412,5,414\],\[5,1,512,3,3\],\[610,4,1,613,614\],\[710,1,2,713,714\],\[810,1,2,1,1\],\[1,1,2,2,2\],\[4,1,4,4,1014\]\]
**Output:** \[\[0,0,0,0,0\],\[0,0,0,0,0\],\[0,0,0,0,0\],\[110,0,0,0,114\],\[210,0,0,0,214\],\[310,0,0,113,314\],\[410,0,0,213,414\],\[610,211,112,313,614\],\[710,311,412,613,714\],\[810,411,512,713,1014\]\]
**Example 2:**
**Input:** board = \[\[1,3,5,5,2\],\[3,4,3,3,1\],\[3,2,4,5,2\],\[2,4,4,5,5\],\[1,4,4,1,1\]\]
**Output:** \[\[1,3,0,0,0\],\[3,4,0,5,2\],\[3,2,0,3,1\],\[2,4,0,5,2\],\[1,4,3,1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `3 <= m, n <= 50`
* `1 <= board[i][j] <= 2000`
|
Carefully perform the "crush" and "gravity" steps. In the crush step, flag each candy that should be removed, then go through and crush each flagged candy. In the gravity step, collect the candy in each column and then rewrite the column appropriately. Do these steps repeatedly until there's no work left to do.
|
Array,Two Pointers,Matrix,Simulation
|
Medium
| null |
307 |
hi everyone my name is contributor i'm trying to solve the zero liquid challenge problem the problem is ransom query mutable so the problem is that given an integer add a number and handle the multiple query of following tabs there is an update of that element and there is the index has been given and all up to uh another function which is the ransom so basically that i calculate the sum of the element nums between that indices left and right so which has been given so basically the three function uh basically the two function has been given that is ransom and the update so uh whatever i'm trying to do that first make dragon and then after that i am trying to solve through the solve my approach as a coding interpretation so what is happening that basically hold on i just missed to add my riding pad just give me two minutes not two minutes some second yeah i just added so basically what is happening that um suppose 1 3 5 has been given suppose uh there is an update call and update function there is an index value and the value so whatever i'm trying to do that uh first i will take that all the sum one plus three plus five there is nine and after that when the update function has been calling that so what i'll try to do that there is the total basically there is the total and total minus of uh the index value that is the nums which the area has been given there that is the index so what is that suppose that is i've been trying to check that 1 and value will be updated to 5 so what is happening that 9 minus so 9 minus 3 that is 6 so after that the nums of index numbers of index will be the value that is 5 so after that the total will be updated plus is equals to the value so what is happening that 6 plus 5 there is the 11 so what is that 5 plus 1 that is the 11 so that is the wave and the range sum what is what i am trying to do that 1 3 5 and the ransom query first i will try to check that the left value or the right value is which is given and right minus left if that is greater than uh the i mean that the size of the array of half in that case i will taking that the number of majority i mean that uh so zero one and two so basically the size uh two minus zero that is two and the size is three by two there is one so two is greater than one yes so in that case what i'm trying to do 0 1 2 for the left value is equals to 0 i am trying to for that is uh taking an example that is from 0 to left i mean that left minus 1 and after that the right plus 1 to the n up to that will be directing from that total value directly from the total value in that case and when that is not been possible in that case i will take that the left to right value so that is how i am trying to implement biology basically that i am traversing uh one time basically that i am not taking any nested loop so basically that the order of end time complexity has been required there and for updating there is an order of one basically after updating case order of one because i have been changing that value of that array and for such increase that is also an order of one and after updating that value i'll be adding with the total uh so basically that is the order of one time complexity for the updating and the and thus for some case ransom query there is no order of in uh time complexity has been needed there and i am taking the um not yeah i am taking an extra space um num and as well as that and because the value will not be changeable for there so i'm not taking that basically there is an auxiliary space and the i'm taking that the total value so in that case auxiliary space if i've been taking there is the order of n and uh if i'm not taking the auxiliary space in that case the order of one is the space complexity also so right now i am trying to solve my logic as a coding interpretation what will do that first basically that for numbs i cannot change that the main value basically so that is why i am taking an extra space at the though if you called as uh the auxiliary space basically so right now that is i will check there as a private function basically i will do that private picture of integer num an integer total is equals to 0 and right after that i am initialize that vector as in nums and after that i adding that all the value has been present in that array into the total value auto i num and that will be added to qut plus of i so what is happening that it will give me as the uh total value and update what i'll say that there is the total minus of num of index and after that num of index is equals to val and total class is equals to bell so that the value will be updating totally and right now i am trying to do that the ransom so integer tmp is equals to the total so what will happen that if right minus left is greater than is equals to the nums the num of size divided by 2 in that case for integer i 0 to i less than left i plus the tmp minus of num of i and after that i will detecting after the right part so for integer i is equals to right plus 1 are less than numbers of size i plus and tmp minus in terms of i and after that what will do that if that is wrong in that case i will return the for integer i is equals to left i less than equals to right i plus and after that tmp plus is equals to the uh norm of i so far in adding before that we'll have to uh make initialize that as a zero because i am adding there and in previous i will be i am deducting there so when the all the procedure has been completed then after that i will directly return tmp so right now i am checking that if my logic is right or wrong what is happening it is taking too much time maybe we need issue hold on i am doing the page refresh now hold on yeah it's giving me wrong answer there hold on okay numbs plus num plus let me check you had given me wrong answer there hold on now of i okay i'm missing that semicolon there yeah it is accepting in the run code i am trying to submit there yes got accepted thank you so much you
|
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
|
426 |
hello guys now I try to solve the convert binary search tree to Sochi the doubly linked list this is our frequently asked question by Facebook convert the best teach you are so heater circular doublings the same place think of the left and right pointers at the till trick is the next point of in a doubly linked list let's take the flowing base theater it's unholy may help you understand the foreman better give my bestie in the day i which will occur in an ordered so the problem statement may seem complicated at first glance but when you think these double links careful UFC then actually the so leader sake Tomlinson and the this is the in order traversal of the given PST it shall be in order traversal 1 2 3 4 5 so basically we justice similarities in order traversal over the ESC is enough and do not forget to get the hater note in deserve laughter no dough in the metal hey the left to the last northern lands de yeah tell note right in which with a hate note so let's do it interactive if you can check it you know what is tree you should keep it a tree note of current order because we should answer tree no the writer to Colonel dandekar them know that left to the pre note we also need hate finally we will return we need to simulate you know traversal and in the end to renounce that tail no it's so pretty right should point to the hate yeah okay thank you for watching happy coding see you next time
|
Convert Binary Search Tree to Sorted Doubly Linked List
|
convert-binary-search-tree-to-sorted-doubly-linked-list
|
Convert a **Binary Search Tree** to a sorted **Circular Doubly-Linked List** in place.
You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
We want to do the transformation **in place**. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.
**Example 1:**
**Input:** root = \[4,2,5,1,3\]
**Output:** \[1,2,3,4,5\]
**Explanation:** The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
* All the values of the tree are **unique**.
| null | null |
Medium
| null |
537 |
Loot Hello Everyone Welcome 24th After Speaker Channel Lotus Press Complex Number Krishna In This Question Veer And Complex Number To Subscribe The Answer Will Be Complex Numbers In Excel Video subscribe and subscribe A Much Better Solution By Giving Us Can Sit Alone Without Peer Wants To Basically Real And Imaginary Tube Screen subscribe Video to a Complaint Number Modification David 578 Other Electronic The Multiplication of Complex Numbers in General Should Be Given Number in the Form of A Plus B A Part of Report Subscribe Now Two Plus B C D A B C D 2 H Hai Are Online Without Birha By So Led Aaye Plus Deep Into Being And This Key Report Subscribe Must Subscribe 4,320 Video subscribe and Under-22 Is - That Plus Key A Plus B C and Under-22 Is - That Plus Key A Plus B C and Under-22 Is - That Plus Key A Plus B C Into It 210 Par Kam Serial Part Number And District Comes A Marginal Deposit Udhar New Number Hai Hua Ki A Lips Talk About How Abhi Ignore Builder Path Vikram Problem Life In Passing Distic Not Indian Mathematical Calculation Subscribe Button Minus Plus Minus 980 What Do Subscribe My Channel Subscribe Button Dab School Subscribe Channel Subscribe Our Do Subscribe My Channel Subscribe Button Dab School Subscribe Channel Subscribe Our Do Subscribe My Channel Subscribe Button Dab School Subscribe Channel Subscribe Our Video That Tubewell Round Time That Don't Intercept Plus Side Marks The Real Vid Oo Ek Sandesh Again Will Take Another Guy To Restore Issame Departed Now That Madhuri Path Native And Such Natives Can Give One Position Of A Great Actor Will Update Vidru Its Strength Is A Very Big Then Not Able To Understand This Test Will Be Clear Record Infection 108 Number Serial Number In The Original Part And Number Use This Tours To Update Your Jo Effigy Of The Real Numbers Idly Information Will Be Updated To My Channel Subscribe To In knowledge given to infection with the most interesting part problem let's talk decoration for complex numbers class do and provided for creating page number 90 subscribe to subscribe and subscribe the Channel to pain and tweet and tarf vutu volume number one impatient and depression the number one Real Numbers * * * * * * * * Subscribe To Clean Up Problem Lies And Writing This 5 Minutes Will Do 16656 Amazing How To Build To Shoulder Real Part Office Contact Number And Newly Appointed Tips Must Subscribe Real Numbers subscribe And subscribe The Amazing Updated On Ignorance Increment The Point When Skin Subscribe A Similar Thing Again For The Mid Point Of Just Check Subscribe This Negative Thought Of The Day Is Vansh Rudra By Simply Check Africa Test Imaginary Nay Updated In Number 2 - In Number 2 - In Number 2 - Incident Contact Number is Shubhendu Accepted and Time Complexity of its Order Length of Number is A Plus Length of Number is Two is Space Complexity School St. Beds College and Tuition is Feeling Answer is Thanks for Watching Video on your Android Tomorrow with another expression And Don't Forget To Like Share And Subscribe Our Channel Like This
|
Complex Number Multiplication
|
complex-number-multiplication
|
A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_.
**Example 1:**
**Input:** num1 = "1+1i ", num2 = "1+1i "
**Output:** "0+2i "
**Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i.
**Example 2:**
**Input:** num1 = "1+-1i ", num2 = "1+-1i "
**Output:** "0+-2i "
**Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i.
**Constraints:**
* `num1` and `num2` are valid complex numbers.
| null |
Math,String,Simulation
|
Medium
| null |
92 |
hello everyone let's look at reverse linked list 2. if you didn't watch the first question for this series feel free to go back and look at it first that's question 206 and for this question we come up with a very easy solution and for this question we will refer to that solution let's look at the problem statement we need to reverse a linked list from position m to n we want to do it in one pass here's an example the input is one two three four five m is two voice and is four so the output becomes one four three two five from two to four that's from two 3 4 we reverse them become 4 3 2 and here i have copy and paste the solution for 206 to reiterate if you didn't watch my 206 solution then feel free to pause this video and look at the solution for 2 6 first and then you will understand why we have this statement here to solve this problem let's first look at an example so we have one two three four five m is two and it's four so we're gonna reverse all the variable from two to four that's two three four two reverse two three four we can run the previous solution for the problem two or six that's these lines and then it becomes four point two three point two and then we simply need to concatenate this one to four two to five you might already know how to do it that's right before we even reverse our two three four we need to first reserve the point for one and five and then after the reverse we can concatenate them back so if the flow is not clear to you feel free to go back and watch it again but i can confirm it will be clear in our code base let's look at the code implementation like many of our other linkedly solution we have this dummy list node and then in the end we always return diameter next and then let's create our prefrontal then we need to move our brief and curve to m and then before we reverse in the middle between m and n we need to first preserve our front and back connection and then let's run this and after this we have reversed everything in the middle between m and n and then let's concatenate them back we have front on axis proof back down next is curve that should be the whole solution let's submit i'm sorry there's a problem here let's get this space here and here let's sum it again this time it passed let's look at the complexity space is still constant for time it's all n we do this in one pass so although we have this two for loop but here we move from start to m and here we from m to n so we didn't go back it's still one pass if you have any questions please leave a comment below thank you for watching
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
233 |
hello friends today let's solve number of digital one give an integer and count the total number of digital one appearing in on all non-negative integers less than or equal non-negative integers less than or equal non-negative integers less than or equal to an if an equal to 13 will output 6y because there is 1 10 11 12 13. you may wonder there are only five numbers why we output the six the reason is there are two one in this eleven so we call it twice uh so how to get this six actually we can try to put the digital one in each place from uh this place to uh this place we just call the how many valid uh integers when we set one in each position so if we set the one this position as one then we have two valid number there is one and eleven now when we set this position to one then we have four valid integers that is 10 11 12 and 13. so that's our strategy let's see the algorithm in details we just try to put each position as the integer one the digital one actually so we set from the smallest to the largest so when we set this place to one how many integers are valid we will count now when we set this place to in a digital one how many integers we will get and we also sum up we set this position as integer the digital one how many integers we'll get let's see if we set this position as digital one then we will have 11 valid integer y let's see we already set this place at the one then the in the place before this one can be 0 1 2 10 so that means we have the number 101 and 91 to 21 and 11 and the one so that's what does this 11 min so this 11 essentially is this 10 plus 1 times 1 y with times 1 because currently the base is 1 and then we move forward then the base will equal to 10 because we're already in this place so the base is 10. in this situation the current num digit is 0 which is less than 1 then we can only get these possible possibilities here we put this place at as one then we have 10 11 12 to 19. so in total there are 10 possibilities so this change we time this left under 10 because current base is 10 so we have 10 possibilities and then we move forward we go to this one at this position we put it as one then we can only have five possibilities there will be 100 101 204 because we can only because the current base is 100 but there is nothing on its left we can only sum up is right actually is four so from zero to four there are five integers so we sum up five so that's how we get this result if we using already outstanding then let's see another example we also start from the four to one so we first fill up this current digit then it's left is when we at this current dj4 on the left is 11 and when we here the on the left is one here on the left is zero and when we here on its right is zero when we are here on the right is four here the right is fourteen so we fill up this table and the base as the pre previous example based from 110 to 100 so the same thing if the current digit is 4 is greater than 1 so in total we have left plus 1 times base we have 12 possibilities when we set this place at 1 and then we go to here currently it is equal to 1 so it should be sum up front left and the right so let's see if we set it this place in the one yeah we already set it the one as on its left it is one so we can set a zero or 1 here if we set it as 0 then we can put all the possibilities on its right there will be 10 11 12 to 19. if we say left to one then we only have five possibilities because it is already one at the last at the largest it's already one so we have 110 111 214 so in total there are five possibilities we sum these two number up we have 10 plus 5 equal to 14. so that's when the current digit equal to the one we should sum up left times base plus right plus one okay so when the current go to this place we have 15 possibilities what is that actually it's 100 215 14 so it's 15 possibilities here so actually this is a sum up formula when the current digit equal to one we should sum left times base plus right plus one when it's greater than one then we should sum left plus one times base otherwise is to then one we only needed to sum up left time space okay let's write the code we should be careful because uh we first do a h case check if n equal to zero we just return zero and we need a base as we always need two times it so we would better write it too long and when the condition is when the base is less or equal than um we do the things and we also need a sum right we need the final result so in the end we just return sum so here we should get the left and the curved digit and the right digit so how do you get it um first thing we should convert it to yint because we use long here convert it to yint so how do you write things the left this is the left the current digit and the right so let's see the left there should be un divide the base and the divided 10. the curve will be an uh sorry the left okay the curse should be undivided base and maybe we will see some example the right will be base module base why because at the very beginning it's one and a four so we mold your base which is one so we'll get zero so that's correct so how to get this four that means we um divide the base then we have 104 and then we module um we module 10 so we get a four so here we will module the 10. is that correct we have 104 and we divide the 10 oh sorry divide the base we have 104 and we divided 10 again so we get a 10. so that's correct okay so then if the current digit greater than one what should we do we should be sum up the left plus 1 times base else if curve less than 1 actually if equal to 1 which will be sum up the left times base plus right plus 1. if it's less than 1 we only need to sum up left time space every time the base should return up 10 okay that's it thank you for watching see you next time
|
Number of Digit One
|
number-of-digit-one
|
Given an integer `n`, count _the total number of digit_ `1` _appearing in all non-negative integers less than or equal to_ `n`.
**Example 1:**
**Input:** n = 13
**Output:** 6
**Example 2:**
**Input:** n = 0
**Output:** 0
**Constraints:**
* `0 <= n <= 109`
|
Beware of overflow.
|
Math,Dynamic Programming,Recursion
|
Hard
|
172,1068
|
1,071 |
I lead code 1071 greatest common divisor of strings for two strings s t we say t divides s if and only if s equals t plus whatever Plus t i e t is concatenated with itself one or more times given two strings string one and string two return the largest string X such that X divides both string one and string two so essentially we're looking for something that'll divide both of these in this case for our first example we've got ABC which will divide into this twice easy ABC divides into either one of these no problem so our output is ABC in this case here we've got a b and a b what divides into both of these is a b you know sub string of string two or string one divides into this three times divides into this two times therefore we output a b um but for leak code for example there's nothing that we can divide into this that will you know wholly divide into both of these and therefore we output nada so if we go to our coding window we are looking at doing this like this so first we got to make sure that um string one is not short to the string two and how do we do this we use an if statement so if string one dot length is not great ah sorry it's not as less than string two dot length oops on messing it up today then we return gcd of strings uh string two and string one right uh else so now our second case is if it doesn't satisfy that then we sorry then in our second if statement we're going to be checking if the shorter string is not a common prefix of the longer string so in this case not string one starts with string two so this can essentially be red as string one does not start with string two right so in this case if string one does not start with string two then we know it don't work it ain't there's no con there's no common divisor in this situation because string one don't start with string two simple as that don't they don't connect uh so then we're gonna do another else if statement in this one I don't know why I keep doing this uh I'll just keep it a bit uniform um in this case we are checking if string two is going to be empty um and if that's the case then let's type it in correctly here string two uh sorry is empty then we know that um we've there's no Grace coming uh divisor to be found because string two is empty anything can divide into the other one so therefore nothing can be found and we return string one and then our final else statement which is uh we are going to return oh I messed that I've done a return gcd all strings string one substring of string two dot length and string two and then that should compile so in this case then we find and cut off the common prefix of string one and therefore this is our last else statement this runs let me submit this if I check the full this is you know as fast it can be decent memory all good uh please like subscribe
|
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 |
344 |
our question is the reverse string question specifically the question asked the store versus string that is array of characters so this is a easy level question but this question asks us to reverse the string simply put when we think of a string as a data structure we can think about it almost as it can be broken up into smaller parts a string is essentially just like a sequence of characters or an array of characters if you want to think about it in programming terms the great thing about this problem is that we don't have to convert a normal string to a list or an array of characters that would involve an extra step the input is already an array of characters or um yeah or a list of characters in python so the specific patterns i'd like to point out for this problem are two pointers and swapping so i'll write that down a different color so two pointers and swapping so swapping is something that could happen with uh different patterns if you will different languages so in python and javascript there are actually some quick hand ways for you to do that um you can actually do it in one liner and python and javascript but typically for languages like java and c plus there's going to be a three-step process three-step process three-step process now one of the steps is that you've been able to create a temp variable let's just say that it's an int for example you processing the array or the string let's just say that you have like a variable called left and then you've got to swap it so first you take the first value that's going to get changed and then the second value is going to be applied to this first value at left or start so let me just call that as start and then you're going to have an end index swapping there then the last step you are going to change the end one by applying that temp variable so why is this important if we actually look at our inputs hello and hannah and we think about our indexes and equals zero so the first index and end equals the last character in the string or array so for example in python that would be length s so let's just say that's the list of characters minus one so let's apply two different colors so this first one is going to be the start and for the next one we'll make that purple or purplish pink we'll make that end so essentially what we're doing with these two pointers is that we're pointing to different parts of the array and then swapping them so you can imagine that every step we're swapping this so if we were to process this in a while loop we would say that this step right here is going through and that at the end of this being swapped or processed then we just increment oops we just increments we just increment the start index by one and then we decrement the end index by one so okay this zero will be right here and this h will be right here then this arrow right here goes right here because and is decremented by one and this yellow one is moved to the right by one and then the same process happens so then we get l swapped of e so l goes right here oops l goes right here and e goes right here and usually we'll have that end um on an odd number so how this actually looks like in code is while start is less than end this swapping portion right here and then obviously this ending portion right here and by the end of it um all your code is going well all the characters in your race can be swapped and essentially the string is going to be swapped so um the other thing to note is that for the time space complexity we are going to go eat every character at least once the time will be on time but since we're not creating any additional data structures it'll be one space so this is actually pretty efficient and now we'll be able to solve it in java python and javascript all right guys this is going to be the java solution so um as we discussed in our conceptual overview essentially what we're going to be doing is creating two pointers a start and end with a while loop we're going to be doing a three-step doing a three-step doing a three-step process in order to swap the elements and then finally incrementing the first index that goes from left to right and then decrementing the end index or the right index going uh from right to left so let's get started so first we're going to instantiate a start uh index at zero and then we're going to instantiate an end one so we can do that s dot length minus one uh we don't use the length of parenthesis open and close which is a string method but if we were to have a question that imported the actual string we would be using uh dot length parenthesis open close so we do our simple start is less than end another important thing to notice here is that with the these types of swapping um questions and your gnosis and the palindrome question as well um you're not going to want to do equals it's because it'll be an unnecessary process or step if you're to swap start and end if they were equal to each other it would essentially do nothing so we're printing that step so that's why we don't need a less than equals for this uh while statement so yeah let's just create a temp variable um where s at the start so the reason we do this is because we're going to change start first and we want to keep that value to change end eventually so s start is going to now have the end value then this end value is going to get that temp variable so you'll notice this with c plus and java but this is just the way to do it and then um at the end of this transaction process of swapping these elements in the array we're going to increment the start index uh so it moves from left to right and then decrement the end index until they both cross paths and then this whilst uh statement uh breaks and then you'll have reversed every character within this uh this array so let's run this and see if we succeeded oh let's make sure i got this right in temp oh it's a char okay perfect so i just didn't mister the type so we'll just change that really quickly and that should fix everything okay let's submit this all right guys that was a java solution um it runs in o n time and 01 space thanks guys all right guys uh now we've done the java we go to the python one so it's gonna be the same structure that we talked about in the conceptual overview but for this uh python you can do a lot of like one liners or python idioms in order to swap elements so you can actually swap python elements in an easy one-liner just using indexes and one-liner just using indexes and one-liner just using indexes and swapping the places which i'll show you right now and then one other thing is with python just knowing the actual built-in just knowing the actual built-in just knowing the actual built-in functions so for the length of an array or a string is simply the len or lang function so first we create our start index which equals zero and actually you can see a little bit of java uh showed out so um there are no semicolons there's no typing in python because it is dynamic so now just do the length of the list minus one and then while start is less than end here again we can just do the simple one minor so s start s and equals s and s start and then start plus oh wait again a little bit of the java here and then end minus one so again this one liner is how you swap um elements in an array in python it's really clever so you're basically just changing the position from start end to end start and that swaps these elements and uh yeah we'll run this and the code should work all right guys uh we are going to be reversing the string in javascript um so there's multiple ways to do it the swapping action so the other way is like kind of similar to java where we do like a three-step java where we do like a three-step java where we do like a three-step process where we create a temporary variable um apply the second variable value to the first indexed place in the array and then the ending index placement in the array is assigned that temp value but also in newer versions of javascript um there's a way to do a one-liner so um there's a way to do a one-liner so um there's a way to do a one-liner so we'll try the one-liner and if not we'll try the one-liner and if not we'll try the one-liner and if not we'll go for the three-step go for the three-step go for the three-step uh um element array swapping process so again uh with this we are just going to create the start variable that starts at index 0 which is the first elements index and an end is going to be the length of this process so s minus 1 while start is less than and then we're going to create a temp variable so for this bar temp equals s start s o and actually yeah that would be the three step process but i'll do that and then convert it to um the one liner but yeah let's just do that so s start equals s and then s and equals that temp variable and then we increment it by one for the start or left index and then we decrement by one uh for the end index and then they eventually cross paths or meet in the middle and that breaks out this while loop start less than end so let's see if this processes okay so i'm mistaken uh the length function so let's see if it's just line two all right back guys uh so i was a little confused on the length thing but yeah simply in javascript you just do a dot length and uh that returns uh for whatever object or data structure you're using so let's see if that works okay so we're going to now convert this three-step process into a one-step three-step process into a one-step three-step process into a one-step process so let's start with that right now so you can do a one-liner similar to java you can do a one-liner similar to java you can do a one-liner similar to java with swapping elements by uh putting those um elements that being swapped within its own list so start s end and then just sweat uh swap the positions and right here so let's see if that's this works and okay yep so yeah this is just kind of a faster one-liner to do it with faster one-liner to do it with faster one-liner to do it with javascript anyways thanks guys for joining and see you guys next video cheers
|
Reverse String
|
reverse-string
|
Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
**Example 1:**
**Input:** s = \["h","e","l","l","o"\]
**Output:** \["o","l","l","e","h"\]
**Example 2:**
**Input:** s = \["H","a","n","n","a","h"\]
**Output:** \["h","a","n","n","a","H"\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
|
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
|
Two Pointers,String,Recursion
|
Easy
|
345,541
|
1,498 |
hey what's up guys uh this is chong here again so this time uh it called number 1498 number of subsequences that satisfy the given sum condition okay so you're given like a ray of integers right and the integer target so your task is to return the number of the non-empty the non-empty the non-empty subsequences from these nums right such that the sum of the minimum and the maximum element in this subsequence is less or equal to the target so and since and then do a modular by this 10 to the power of 9 plus 7 right so now this product this one is about the subsequences and it's about the number of subsequences right so for example right so we have these numbers 3 5 seven six seven right and the target is nine so the answer is four so the reason being is that you know there are like four subsequences right who's smart minimum and the maximum number that sum is smaller than nine so we have three five six and three six right and notice that you know five is not first five six is not this one is not a valid answer because this one the smallest is five it's the biggest six this one is eleven right which is greater than nine and also 5 is not it's not the outsider because for the number itself the small the minimum and the maximum it is the number itself right so this one is also greater than 9 that's why the total subsequence from for this one it's like it's four sorry let me change this one to okay and another example right so this one uh if the answer is six because as you guys can see we have six subsequences so notice that you know uh same numbers on a different index we can't we treat it as a different as different subsequences right and here are some constraints right so 10 to the power of 5 something like that right cool so you know at the beginning you know when i saw this kind of problem you know because i see this kind of number of subsequences you know i was trying to solve this one with uh with the dp concept but you know but then i started thinking about you know for as you guys know right so for each dp problem we need to define like a dp state right and for this one you know i'm trying to define like a dp state you know something like you know if i can use like uh the current index plus the current minimum and the current maximum right as a state can i calculate the uh the valid subsequences right starting from the current index to the end right but that's i think that's um because that's going to be a weird state you know because even though we define that state you know it's hard for me to come up with like a very clear uh dp state transition function you know because with the current index and the and this current minimum and the maximum right i mean later on we might have like the uh we may have like a smaller or a bigger number than the current minimum and the maximum right so which means the current state cannot represent everything starting from the current index to the end right and then i was like maybe we can sort this numbers right and then we know okay so it's all the later one is also it's always greater than the current one right that actually that's a good start you know but if we sort it right i mean then we don't even need to use the dp right because the uh because we know the current one is the smallest index sorry the smallest is always the minimum number for all the subsequences starting from the current number right and then we all we need to do is that all we need to know is that we just need to know the ending uh index for all the index for all subsequences right who is starting from the current one so what does that mean means that you know for example if we have three uh five six and seven right you know so we have a left let's say we have left and right pointers you know we have left and right so at the beginning you know left is equal to zero and the right equals to n minus one so this is left and this is right so basically we can use this kind of two pointers you know things oh so first we sort this arrays right i mean we never the left one plus right one is greater than target right then we know okay we need to move the left the right pointer to the left right so now the uh the point the right pointer is here now three plus seven because you know so the reason we do this is because you know since the left pointers it will always be pointing to the minimum value and the right point will always be pointing to the maximum value for the current subsequence range right so let's say we have three five six right so now we know okay so three six it's within the range in target so which means that you know this with this three number with this kind of uh numbers right we can get some subsequences out of this right but what's up what's going to be the strategy you know so i ideally you know i think you guys all know oh no that you know the total number of subsequences with three number is what is 2 to the power of three minus one right i mean this is the none empty subsequences right so basically we have like seven total subsequences seven non-empty uh subsequences seven non-empty uh subsequences seven non-empty uh subsequences right from this one but like i said we cannot use all of the subsequences so our restriction here is that you know we have to include this three here because otherwise you know so the reason being that you know so the precondition we can use this three number is that when is that we have to have like a minimum number as three right we have to fix this one because otherwise you know like i said if we only have this five right and then the minimum number will be 5 because you know we're saying that you know we have we need this minimum number to be three right and if we have a if we have fixed the minimum number to be three then i don't care about the maximum number starting from six starting from this six it can be anywhere between these three and between the left to the right but we have to include these three so which means that you know instead of three here right so we need two right because you know this one is fixed so we only have like two numbers left we can do like full subsequences of these two numbers right and in this case right actually it's going to be a we don't need to do a minus one here because we could have like empty subsequences here because like i said you know three is also like three itself without any of those two numbers can also be a subsequence by itself okay right so now i think it's pretty clear right i mean we have our logic then basically you know oh and a little bit about this 2 to the power of 3 right so let's say we have no we have 3 here and now we have a lot of numbers here so this is like you know nine something right so basically you know this is the right this is l this is still the same right it's going to be a 2 to the power of uh right minus left this is going to be the total number total possible into uh subsequences uh for this kind of in this range right cool and after this right basically after calculating the subsequences from left to right then what's next then we need to move the left to the right left but to the right by one so basically now left is pointing to here because like i said you know so this one is for all the subsequences that's including these three here right so now we need to consider we need to check is there any other subsequences available valid subsequences that's in uh basically starting from this number right so basically in them we just go back to our original logic after moving left we also check if that the left one plus the right one is using the ring of target if it is and then we use the same like uh formula here otherwise we keep moving the right to the left right because the reason we can use like two pointer is because like i said you know every time we move the left pointer to right so the left numbers will always become bigger right so if we have right here you know so the right pointer will always be moving to the left because since the left one is always uh becoming bigger and in order to make in order for the subsequences you know for the minimum maximum is less than the target we every time we can only move the right pointer to the left if that it doesn't make sense to move the right pointer to the right because you know whenever you get a smaller value that's why how this kind of two-pointer that's why how this kind of two-pointer that's why how this kind of two-pointer logic works right i mean a little bit so for this one i know for this one it's pretty straightforward right i mean basically you know the way how can we get 2 to the power of this one because if we have 5 and 6 right i mean how many totals subsequences we have here we have like 5 we have 6 and then we have 5 six right and now of course you know we have we always have an empty one right that's why you know the formula to calculate all the subsequences given like uh like with n numbers it's going to be a 2 to the power of n right and since um actually minus 1 but since we're also including the empty one that's why it's just a two to the power often okay cool so let's uh start coding then so the coding should be pretty straightforward right so first i sort this number and then i have this kind of a length of nums right and then we have left starting from zero write n minus one and i have the answer equal to zero right so we have two pointers at so while the left is uh equals the right so if the nums of left plus nums of right it's within the range of target okay then we know uh we can calculate all the valid subsequences right this is uh within the range for the range uh from left to right where uh the left number the pointer left number is always included right it's going to be a 2 to the power of r minus left okay and then we increase the left by 1 right else we shrink the right pointer and then we because only by shrinking the right pointers we could possibly get like a smaller sum for these two numbers okay and then that's it right we have a mod gonna be a 10 to the power of nine plus seven and then we simply just do a mod in the end okay so that's it okay accept it if i run it cool so this one is like pretty it's kind of slow but i guess this is as good as we can get from this one you know as you guys can see the time complexity for this is like uh of unlock and write okay because we have sort and here just like often right so what else yeah i think that's pretty much it is right i mean so again right i mean the reason we want to approach from left and right is that you know let's say we have three again right we have three this kind of thing you know after sorting we have nine here right so the first time this one this condition is satisfied right which is uh three and nine right this is the left and this is right since we have already sorted you know the first time this one is satisfied and the left and the right is the maximum basically it's a boundaries right for the for all the subsequences uh who is who includes this three number so which means that you know for other subsequences who is who includes three here you know we can only go as far as nine here okay and because anything after nine here is going to be what is going to be a going to be 10 right let's say the target is 12 in this case right so and every time we have a if statement we go into the if statement and then we know okay so the current the right is the boundaries of the range for the current subset subsets the subsequences that's how we can uh how we can make ensure right we can use this formula to include all the possible sub number of subsequent subsequences right who is who includes this three num number three here similarly right once we process this one and we move to here and then if this one still if this one is three another three here right and then we see okay three is this one and then we know okay so it's again right every time this up this r is pointing to the boundary right to the furthest number this current subsequences can go um yep i think that's pretty much everything i want to talk about for this one yeah okay cool and thank you for watching this video guys and stay tuned see you guys soon bye
|
Number of Subsequences That Satisfy the Given Sum Condition
|
find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
|
You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
298 |
one welcome to Leo's Channel let's do some lead code today so this question is a binary tree longest consecutive sequence so now we were given the root of a binary tree return the length of the longest consecutive sequence path what does it mean by consecutive sequence path so a consecutive sequence path is a path where the value is increased by one along the path as we can see here the longest consecutive sequence path is this three four five uh let's take a look at this node is two so this will make a two three four five but in this case you can start at any node in the tree and you cannot go from a node to its parent in the path so that's why it doesn't count this 2 in it all right so this is a pretty normal tree traversal problem so let's take a look at this given this tree the longest consecutive path increasing path is this and this one since it can only come from the root pair of the parent to the children so this is the longest increasing path instead of this one two three okay so how do we approach this so first we need to Traverse the tree right and typically we're thinking of a recursion solution so let's think about what do we need to do at each node so first let's do some sanity check if root equals to no then return zero because there's no consecutive sequence path since there's no node in it and we need a global Max to record the longest executive sequence path so since we only need one integer number I'm going to use an integer array to recorded main value okay and also during the way I'm gonna do a recursion function I'm going to call it helper so we'll get the tree in it and update the global Max then we'll return the number and the max integer array okay so now how do we write the uh the recursive function so we are going to return the integer and uh whatever we're going to return the consecutive sequence longest consecutive sequence path of the current node okay so of each node say for this node the longest consecutive sequence path that it returned is 4 5 which is two okay and when it returned at this node the node who caused this recursive function it will add the maximum of this path to itself okay and this is going to be the tree node root and it's going to have the integer array Max so first edit check if root equals to know zero okay and for the recursive function we're going to make a left which calls the helper function for the left subtree and we're going to have a variable that calls the right subtree okay so this left subtree gives us the longest consecutive sequence path for the left side and the right gives us the right side okay so what are we doing now we're here at this node current node we are going to update whether it is a valid path from here right so let's see left next equals to um if you don't last doesn't need to know which means there is a left subtree and the root the left the value equals to root down value let's see plus one right this is the truth that means we can connect this node to the subtree so that's left plus one else there will be only this one node okay for the longest consecutive sequence path so the same thing works for the right subtree so if the red subject isn't all wrote the right of value equals to the value plus one that's it right if it's right updated then no okay so that's the what we need to do now okay now we have the longest consecutive sequence path we can update the uh Max which is Max zero and what else since we cannot go through the current node right we cannot form something like this we can only take the value from either side so we're going to use the maximum of the lap Max and the right Max okay and we're going to return what we're just going to return which is the longest path to take okay here okay this should be it and the type of complexity and space complexity should be and whereas the total number of nodes and with the space complexity the worst case there are n nodes in the stack okay so let's try this yeah it worked fine and does it pass okay I'll see you next time thank you for watching
|
Binary Tree Longest Consecutive Sequence
|
binary-tree-longest-consecutive-sequence
|
Given the `root` of a binary tree, return _the length of the longest **consecutive sequence path**_.
A **consecutive sequence path** is a path where the values **increase by one** along the path.
Note that the path can start **at any node** in the tree, and you cannot go from a node to its parent in the path.
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,null,null,5\]
**Output:** 3
**Explanation:** Longest consecutive sequence path is 3-4-5, so return 3.
**Example 2:**
**Input:** root = \[2,null,3,2,null,1\]
**Output:** 2
**Explanation:** Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-3 * 104 <= Node.val <= 3 * 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
128,549,1416
|
1,802 |
hi guys welcome to algorithms Made Easy my name is khushboo and in this video we are going to see the other approach for solving the question maximum value at a given index in a bounded array in the previous video we have already seen how we can go from Brute Force to a little optimized approach in order to solve this question but we also discussed that is there another way another better way to solve this question or not and yes there is another way which was binary search so let's go and see the binary search approach to solve this problem we have discussed the basics of this problem in the previous video so if you haven't watched that video I highly recommend you to go and watch that video the link to it is somewhere in the top so go ahead check it out and so that you understand what the sum is how the array looks like and what are we going to do with the question one thing that we know is that we are going to search for the answer in a linear space of number which is from 1 to the max sum that is given to us why till the maximum because the entire sum of the array must not exceed Maxim so if there is only one element in that array the answer will be Maxim itself so our answer will go from 1 to maximum also we cannot have 0 in the array as well so now that we know that we want to retrieve the answer or we are going to see whether our answer is a correct fit or not we are trying to search for that in a sorted space of numbers which is from 1 to maximum and that's the reason why we can apply binary search to it for applying binary search we need to keep two things into mind which is third space and the second one is the condition in which we either discard or keep a particular left and right half of our answer so that we are reducing the third Space by half in each iteration so what is the answer to the first one our third space lies from 1 to maximum and what are the conditions to discard the half of the array or the half of the numbers is line with the relation of my sum of the current array taking into account that I am choosing a particular number with my Maxim because if the sum of my array with the particular number is exceeding the maximum which means that I am in the wrong half I need to go to the lower end and vice versa now that we know these two answers we only need to find a way to find out this particular sum of array so for that let's see an example suppose we are taking this example over here we have this index that we are trying to maximize and I have plotted a graph of it so you see that this is the peak element and this is going down and once it has reached 1 it is same plateau of 1. so let's divide it into two parts one is the left part and other is the right part now the sum of the entire array would be the sum of left sum of right and the element itself now what is the sum in the left is this and what is the summon right is this over here I have divided into two parts we'll see why I have done that now let's take a look what this depicts left is the sum of three to five right is sum of this 5 to 1 or we can say 1 to 5 plus these two elements which are forming a plateau so this can also be given as sum of x to n and sum of 1 to n where n is the value we are taking minus 1 also we are going to add this Plateau part which is a or in this case we can also have the same thing in left as well and that can be B so let's first take this example and we'll formulate same formulas for left and right both we know that sum of 1 to n is given by n into n plus 1 by 2. this is a basic mathematical formula so now if we want to find out the sum of x to n which is this 3 to 5 we can say that is equivalent to sum of 1 to n which will be 1 2 3 4 5 minus the sum of the elements that we do not want so minus 1 to x minus 1 because we are taking it from X so sum of all the elements still x minus 1 needs to be subtracted from that basic mathematics no rocket science so now let's go ahead and see what are the variables that we are going to use for this question and what are the values that will get filled in those variables while we are coding it so here are the variables one is n which is nothing but this n or this part second is the x that we saw when we have a sum that is required from a number which is not 1 but some middle number similar thing can happen on the other side as well then we have this a which we depicted here as the plateau on right and the same thing can happen with the other side as well so now let's go ahead and see what are these variables going to depict n is nothing but V minus 1 which is this part the numbers till which we are going to find the sum second is the value of x now how do we calculate X is going to be V minus index 6 minus the index at which it lies because there are these many more values that are filled and this is the starting point so if you see over here 6 minus 3 which is 3 the third value is y now Y is going to be the same case but in the right side so let's take this array and now this will be value minus over here we had index the right index can be found out by n minus I minus 1 so this is value minus n minus I minus 1 which is going to be 4 here is the basic calculation for that so value is 6 and this is 6 minus the index 3 minus 1 which is 6 minus 2 which is 4 now what is a is going to be n minus I minus V now I have used this brackets in order for you to be clear with this what is n minus i n minus I is the number of elements that are present starting from this index at which PR and value of this is the number of elements that are being filled by the sum 1 to n so if we separate this out we'll get the remaining Elements which is two elements that is nothing but this plateau and here is the calculation for this so the size of this is nothing but n which is 11 I is the index which is 3 and 6 is the value of this element so eight elements are there if we see from here and from that six elements are going to be occupied by the sum 1 to 1 so this two elements are remaining which are going to be occupied with once that's about a same thing will happen with b as well so for B let's take another example for B the formula is going to be I plus 1 minus V how this formula came let's see these are the two elements which are filled with Plateau so for that this I plus 1 is nothing but the number of elements that are there because this is a 0 indexed array so these are the elements till which I am calculating and the sum is nothing but V this is 3 2 1 this is three number of elements or three elements are occupying this sum 1 to n so if I do I plus 1 minus V I will get the remaining Elements which are filled with once so this is the substitution for that and here is the basic calculation for this particular equation that we formed so I plus 1 is 5 and 3 is the value so 5 minus 3 2 elements are filled with ones so that's about how we are finding out the values for substitution and formula now we need to formula is a formula and when which formula is going to be used so for that we are going to have two formulas for left two formulas for right with some condition so in a condition wherein we have a plateau as well we are going to Simply have summation of 1 to n plus sum variable A or B and when that is not the case we are going to have this formula which is summation of x to n that is nothing but summation of 1 to n minus 1 to x minus 1. same with the other side and we'll take X since we have taken X and left we'll take Y in right now we have these formulas with us let's just switch this A and B so that we have X and A in the left and Y and B in the right and similarly we switch this formulas here as well now what are the conditions in which we are going to use one of these formulas so those are these conditions for left we see that if value is less than or equal to I plus 1 I'll have a clear summation of 1 to n plus some Plateau which can be either 0 or greater than 0 I plus 1 is nothing but 4 if I go from 4 writing down 4 3 2 and 1 in the boundary condition I will have a plateau of 0. similarly in my right then my value is less than or equal to n minus I which means 11 minus 3 which is 8 I'll have the elements to be 8 7 6 5 4 3 2 and 1 with a plateau of zero in all the other cases I'll have sum which is going to be from some x value to n value in both the cases so that's the condition so this is the slide that you need to keep in mind which is the final slide wherein we have all the formulas with us and all the conditions with us and all the substitution values with us now that I have all this I just need to apply a binary search from 1 to maximum and see the value which is going to be maximum while keeping the sum of this array within the bounds of my Max sum so this is the induction behind the logic that we are now going to code so let's go ahead and code it out so there are a few things that we are going to do with this now which is write the binary search code over here and we'll have a few methods one is to calculate the sum of array and 1 we can take a utility method to apply summation formula so let's start with this so this is going to take n and it will return the sum from 1 to n which is simply n into n plus 1 by 2. second thing is finding the sum of the array in your what we need is the value the index and the length of array and we'll try to find the sum so for that let's take a sum variable in this we'll add the left sum the right sum and the value so now we are going to add the left sum into it so we are going to have the conditions and these conditions are also going to be there for my right sum as well now what the condition States is whether I am having a plateau or not so in the left we are going to have a plateau if my V is less than equal to I and in the right we are going to have a plateau if my V is less than or equal to n minus I now let's try and fill in the condition for left we have variables X and A is for the plateau so in a is I plus 1 minus V and my sum will be otherwise I need to find out the X which is the starting point of my range and that is nothing but V minus I so my sum now becomes summation till V minus 1 minus summation till x minus 1. similarly we are going to do it for right as well over here my plateau is n minus I minus V and my sum therefore becomes V minus 1 plus b and my Y is B minus n minus I minus 1 and my sum now becomes B minus 1 minus summation of y minus 1. once we have this we are going to return sum Plus V because we need to add the middle element as well now that this is done we are going to write the code for binary search let's first take the base case if my array is of length 1 I can simply return my Max sum apart from this I need a left which is one right which is Maxum and I'll run a while loop and in this while loop I'll derive my mid and then I'll be calculating sum for this I'll pass the values for which V is nothing but mid I is the index and N is also given to us if my sum is now less than or equal to maximum I am going to move my left otherwise I'll move my right finally I am going to return left minus 1 why because over here my left is going to cross the answer by 1 that's it let's run this and it's giving a perfect result let's submit this and it's got submitted the time complexity over here is O of log of Maximum because we are reducing the maximum by half every time in our iteration and the space complexity is of 1. so that's it for this question guys I hope you liked it if you did don't forget to like share and subscribe to our channel to receive the notifications of the new videos that we post thanks for watching and I'll see you in the next one till then keep learning keep coding foreign
|
Maximum Value at a Given Index in a Bounded Array
|
number-of-students-unable-to-eat-lunch
|
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions:
* `nums.length == n`
* `nums[i]` is a **positive** integer where `0 <= i < n`.
* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`.
* The sum of all the elements of `nums` does not exceed `maxSum`.
* `nums[index]` is **maximized**.
Return `nums[index]` _of the constructed array_.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** n = 4, index = 2, maxSum = 6
**Output:** 2
**Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions.
There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\].
**Example 2:**
**Input:** n = 6, index = 1, maxSum = 10
**Output:** 3
**Constraints:**
* `1 <= n <= maxSum <= 109`
* `0 <= index < n`
|
Simulate the given in the statement Calculate those who will eat instead of those who will not.
|
Array,Stack,Queue,Simulation
|
Easy
|
2195
|
456 |
hey guys welcome back to another video and today we're going to be talking the lead code question 132 pattern all right so in this question we're going to be given an array of n integers called nums and a 132 pattern is a subsequence of three integer numbers so we have nums i nums j and nums k such that i is less than j and less than k so i j and k as it is over here they represent the index values and this over here actually represents whatever value is there at that certain index of i j and k so nums i is the smallest value nums j is the biggest value and nums k over here is going to be the middle value so what we want to basically understand is num's i basically refers to the one over here numbs j refers to the second number which is the three and nums k which is the middle value represents the last number all right so we want to return true if there is a 132 pattern in nums or else we're going to return false okay so over here uh we're given a nums over here one two three four and we don't have any pattern so we return false over here we do have a pattern which is 1 4 and 2 and how does that make sense so 1 so between in a pattern so in this case it's 1 4 and 2 the first number has to be the smallest number and 1 is the smallest number uh okay and by the way by smallest i mean smallest in the pattern and four the second number has to be the largest number which it is and two has to be with the one in between and two is in between of one and four now one thing that i really want to point out over here is that a pattern is not only when uh the numbers are right next to each other and it's always going to be true as long as i is less than j less than k okay so as long as this condition is met we can have a valid sequence they do not have to be next to each other and the perfect example for that is this question over here we do not have a single sequence where they're all next to each other but for example we have one over here negative one three and two so that's a valid sequence so over here we have the numbers negative one three and two and that also makes sense three is the biggest number negative one the smallest and this in between and another sequence that we have is negative one then we have three and then zero and that over there also makes sense because negative one is the smallest three is the largest and zero is in between negative one and three so hopefully you understand how the question works right now and now let's see how we can actually solve this and before we actually see how it's solved so a very simple solution to this would be to use three for loops the first for loop would be to get the uh whatever is at the i index then the second for loop for the j index and third for loop for the k index and without me explaining why it takes up a lot of time it's not a good solution okay so now let's see a better or more optimized solution which is possibly going to work all right so this over here we're going to consider this list that we have to be our nums area and before we actually go through how we're going to go through step by step i will real quickly i just want to go through the i j and k so uh simply i is going to be the first number j is going to be the second number and k is going to be the third or the very last number and j over here which is in the middle of the sequence is going to be the maximum in terms of value when compared to i and k so between i j and k j has the highest volume similarly i has the minimum value compared to i j and k and while k is going to be in the middle all right so how i'm going to go through about solving this question is going to be to kind of go through it step by step so first let's see how can we actually come up with a solution for i and before we do that real quickly what we're going to be doing in this question is we're going to be iterating through our nums list in reverse so we go here then here and then here so on and so forth all the way up to the beginning and the reason for we're doing that should be apparent uh pretty soon and one more thing is that while we're iterating through our nums so the value that we're currently on for nums is going to be referring to the j value okay so now let's go down to the question of how do we get i alright so i will just call this uh a list over here and it'll be called our mints list and the reason for this mints list over here is to find the value of whatever i we have so this list over here is going to have the same length as nums so let's just draw that out and let's just go to the first number and for the whatever's at the zeroth index it's going to have a value of whatever is at that index and yeah i'll go through why we're doing this okay so now the reason for this means list like i said is to find out what our current i value is and in this case like i said earlier the number that we're going to be going over so if let's say we're at the number six we're going to consider that as our j value so whatever the i value is it's going to be before the j value not equal to but before and the reason is going to be before is because the index of i is always going to be less than the index of j so in this case let's say we go to 12 and what are the possible i values once we go to 12 well there's only one possibility which is the number six and well that's what we got to choose so now let's go to three again over here we have a possibility between six and twelve and which one are we going to choose again remember i has the minimum value so we're going to end up choosing the minimum which is six so that's pretty simple and now let's say we go to four so we have six twelve and three and the minimum year is three so that kind of continues overall because everything to the left of the numbers like 11 26 and 4 are all going to be three and notice this has the same length as nums um that we have there all right so perfect so this over here is our i value we got that taken care of perfect now we also know how we get the j value so the j value will be iterating through nums now the question is how do we get our k value so for getting our k value we're gonna be using a stack and this approach is pretty interesting because basically what we're going to be doing is we're going to be going through nums i and each time we go through nums i we're going to look at its equivalent value at the same index for the min's list and we're going to add that current value into our stack and if we add it to our stack what we're going to basically be doing is we're going to assume that the current value that we've added is the k value okay and the reason that we're assuming is the k value because it's less than the j value and it's going to be greater than the i value that we go over here i know i said quite a bit of stuff at the same time so let's just go through this step by step it should be a lot easier to understand so while a stack is obviously just going to start off as empty i'll just draw it pretty big just so it's easy for me to draw around that okay so what we're going to do first thing we go to 20 again like i said we're going through it in reverse so at 20 what our plan or what we're going to do is we're going to assume that this over here is our j value simultaneously we go to the same index but we go to whatever is at the min's list so that's three and we're going to assume that this is the i value and now for the k value we actually don't have anything so for the first iteration we're actually not going to end up doing anything so we're just going to end up adding 20 to our stack over here so we just have 20 and this is just for the first iteration because our stack over here is empty so now we go over to the next iteration so we have 11 and then three again this is j value i value and now we want to check do we add this to our stack so 11 over here is actually greater than three but before we do that we want to check do we have a possible correct answer and the way that we check if we have a possible correct answer is we're going to get the last element in our stack so in this case that's going to be 20 and we're going to assuming we're going to be assuming that's k and finally we're going to go to the i value which is currently 3 so we have 3 and the j value over here which is currently 11. so 3 comma 11 comma 20. so in terms of index this makes sense but if you look at the actual condition this should be the minimum which is correct but j is not the maximum so over there we have a small mistake so since this was not a valid solution that means that we're going to uh we're going to keep going through our numbers so in that case we're going to add 11 to our stack since that is a possible candidate for the current uh k value okay so we add 11 and i'm not gonna go through this step by step in the sense that uh each time what we'll actually be doing is we'll be making this i comma j comma k comparison but i will be doing it right now so just assume that it's happening okay so now we go on to six and then three and again this is not going to give us a valid combination so we add six to our stack same for four and three so we add four as well now things over here start to change and the reason they change is because now when we go to three what's happening is that the mints list over here actually has a value of six okay so before we actually go through this what that basically is telling us is that everything to the left of three actually the minimum value everything to the left of three has a value of six since we want to stick with the rule that the i value is going to be whatever is at the least index so in this case in the first position so in that case we have to change the minimum value that we're referring to and in this case we're referring to 6. and keeping that in mind we want to also change up the k value so remember that k over here is going to be the middle value in terms of uh maximum and minimum i'm not talking about position so in this case in order to clean it up we're going to go inside of our stack and we're going to pop out everything for all the values which are less than or equal to 6 and that makes sense because 6 over here is supposed to be the smallest value and k cannot be greater than the smallest value so in this case we remove four and we remove six so now our stack just has the number 20 and 11. okay so now we'll go to the next value over here so this over here would be the j value that we're on then after that we're going to have this over here as the i value and again this is going to be the middle or the k value and again we're taking the last value inside of our stack okay so over here let's just arrange them real quickly so first we have i which is 6 then we have j which is 12 and then we have k which is 11. now if you look at this over here actually satisfies our condition and the condition is the fact that 12 is the maximum so that's good 6 is the minimum and 11 is in between and besides that 6 is actually going to be to the left of it since we actually made sure of that in our mints list the stack over here so the stack is ensuring that we get the right most value which in this case is 11 and that's what we actually ended up getting and finally 12 over here is greater than 6 and 11 so in that case we're also going to have that as a valid answer so that should be it for our explanation of the solution okay so now let's see how the code for this looks like and yeah all right so over here i'll be going through the code real quickly and so over here we basically have two steps so step one is going to be creating the min's list so let's just focus on that part for now so over here we define our main list as an empty list that we have for the zeroth index value what we're going to do is we're just going to take care of that over here so min underscore list and we're going to append nums 0 to it directly and that makes our for loop over here a lot easier so we're going to start off at the first index and go all the way up to the ending and while we're doing that each time we're going to go to the min list and we're going to append the minimum of everything to the left of that certain element and to get everything to the left of it what we're going to do is we're going to go to nums we're going to start off at the zeroth index and we're going to go all the way up to index i okay so that's what we're doing here and we got take we got we took care of the mid list so now we want to take care of our stack which in other words is the k value and again minimalist refers to the i value so we just created an empty stack and we'll refer to it later so now we're going to go inside of a for loop and the reason we're doing this for loop is to get the j value and that's because each value that we're currently on for nums while we're iterating through it in reverse is going to be whatever the j value is so in this case we're going to start off at length of numbers minus 1 that refers to the very last index and the reason we're doing minus one is because uh length starts off at one and indexing starts off at zero and then we're going to be stepping by it by negative one and we're going to go all the way up to negative one and the reason we're going up to negative one is because that means we're going up two and not including negative one so that includes it basically goes up to and including the number zero which well is the first value all right so after we do that we're doing a quick check over here is we're checking if the j value so nums j is greater than min underscore list j okay so in this case one thing that might happen is that they might be equal to the same thing and in that case we're just going to ignore it all right so we have that over there and quick reason about why we're checking it is because if they are equal to the same thing then we're never actually going to get an answer so if they're equal to or less than because nums j refers to j value and minimus j refers to the i value and like we talked about earlier i value has to be the smallest all right so now we're going to go inside of a while statement and again this while statement the purpose of it is to remove everything which is less than the current min uh or i value that we're referring to so this uh upholds the positioning value and the maximum minimum of rules not values okay so while the stack exists and the last or the topmost value inside of our stack is less than or equal to whatever the min list uh current min list value is so the reason we're doing this is we're gonna and each time if this is true we're gonna pop it out and by doing this what is going to happen is that the stack refers to the k values and all the k values less than the new i value are going to get removed all right so we took care of that and after that we're going to have a check so we're going to check if the stack exists and if it exists we're going to go and go to the top of the stack or in other words get the last value in it so in this case we're going to go stack negative 1 and we're going to check if nums j is greater than it and if it is we can just directly return true and why exactly are we doing this over here and the reason that we're doing this over here is because if nums j is greater than min list j so this over here is already taken care for so we know that the current j value is greater than the current i value so we have that and over here we're doing the other condition we're checking if the current j value is greater than the current uh k value and if that is true well that means we have an answer and we can just directly return true and if we don't end up going inside of here and returning true well and then in that case we're going to append the current num state value to our stack as it could possibly be a value for the k value right and we're going to go through our for loop like that and if none of that actually ends up becoming true well the last option we have is returning false outside of our for loop all right so now let's try submitting our solution and it should get accepted so thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
1,673 |
Loot hello late think that arvind c point most competitive most software alliance photo interior and interior's and that strat andher properties subsequent software details example latest 12345 v5 subscribe number two a for better understanding wicket on that vikram seth subscribe to consider all subscribe to A rhythm of the day the five kama 250 montex hai ki and tuk malik sudhir certificate after all the question not in ascending order for example 5252 subscribe now to the number stree subscribe to subscribe and subscribe the channel subscribe screen ki ardas ke unauthorized short form competitive Subscribe Number Subscribe Vikas Vihar To Audit Lexicographic And This Suggestion Subsequent Order In The God Of War Is To Select Photo Next Example Change Only One Element Us Subscribe To Subscribe Our Numbers Between Us That's Anger Weeks Terminator 2 FOO C And Jalpari Lesson Install 245 Studio Software On Number Come And Subscribe To The Number 2017 Subscribe To Subscribe Our Channel Subscribe And Subscribe Kare Is This Point Swayam Wedding To Indian Wedding Servi Not For Subscription On E Vent From Free Subhiksha Before Them All elements and will be getting free am so entertainment coffee extract settings example close loop control notes22 the current location software testing to understand what problem election not going to implement used to call a is so inch technique herbal tools push for subscription album fix Subscribe to Benefits Length Size Then Screen Size Main Pramod Element Posts Tagged Me Elimination Size Also This Number Interest On This Number Se Right 200 Luck Up Try Run Batore Plunket Court Sentences Are Always With U The First More Than 160 Into This Number Six Click Subscribe button on number subscribe button the most connection number this fight electronic voting team 65th number five two 9 subscribe to that bigg boss sentence greater than 9 and want to check number this element 500 on this Award to * * that take 17th from start now and shyam sunao and elements subscribe no matter what is the value of the subscribe and assigned the responsibility of pure previous element reversal meerut city greater than to my tab Explain with example so directly go to 400 acid and go into initial aspect on loot lo loot tomorrow morning navigation shampoo * hydrate may tomorrow morning navigation shampoo * hydrate may tomorrow morning navigation shampoo * hydrate may dance are o MP3 ka Saubhagya and declared in available can go to that Rajasthani Sabse Bade Akar Do and Sunao Inside My Photo how to set up subscribe slu ki bihar to poochta album take talk to oo loot time hai MP3 loot so's beloved flower hibiscus first flight courier tracking weather the number and subscribe to this sample checking this strat this note MP3 vacancy increase numbers job Drip Proper Timing Seeing His Condition Step Is Not Empty And A 9th Number Also Appoint Point Is Lesson Is So Bluetooth Phone Number 10 Top Updated On The Effigy Tasteless Send Tank Refill Elements From A Stand Still Not Enter Number Is [ __ ] Owl And Number And Like And subscribe to and super dad I am checking hai mein santosh talent of are till now for mini elements of world a plus size step hai hua tha is greater gunj ke ego me ek hospital ki pendant hidden hai the same time e check raho mere Alarms Looting And Output Tax Set Up Output Soft Smooth Step 4 That Changing That Tattoo And Once Declaring Work In Tears Are You Size Future Into A Stroll And Elements Subscribe To And Listen Na That And A Caring Printer Scam - 110 That And A Caring Printer Scam - 110 That And A Caring Printer Scam - 110 Sarika's Number 102 What is Loot and Started Practicing Austerities and Develop Back Problem to Hey, There was Loot 200 also, Time removed from it Loot Criminal Issue 101 I am still writing Boxer Kushwaha people here also Atal Difficult Shetty and Index-2013 Loot Atal Difficult Shetty and Index-2013 Loot Atal Difficult Shetty and Index-2013 Loot size and equal to one Person Audio Knowledge Sharan Loot Ko Hai OK Nuskhe Pura Kept On Loot Take One Time Police Arrested Jhal Thank You
|
Find the Most Competitive Subsequence
|
find-the-most-competitive-subsequence
|
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`.
**Example 1:**
**Input:** nums = \[3,5,2,6\], k = 2
**Output:** \[2,6\]
**Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive.
**Example 2:**
**Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4
**Output:** \[2,3,3,4\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `1 <= k <= nums.length`
| null | null |
Medium
| null |
938 |
hello hi guys good morning welcome back to a new video in this we're going to see problem range sum of PST although I have to hide the company Tax because Li could might strike it so for you it is my imagination again you know I know that uh it has been asked by Facebook Google and Amazon especially by Facebook in the last 6 months and quite a lot let's see what the problem says um given the root node of binary search tree and two integers low and high return the sum of values of all the nodes with the value in the inclusive range of low to high so again the fact is this is a binary search tree now what the binary search tree is binary search tree says that if we have a node then all the values on the left side are less than or equal to node and on the right side are more than or equal to node but we are given that uh we have the constraints that the number of the nodes in the range is actually this and all the node values are unique so we can easily say that all the values on the left side will be less than the node and all the on the right side will be more than the node it will not be equal to okay that's great that's simply cool now comes the great part that uh byya okay so we wanted to know the sum of the values of all the nodes so for sure if it is my tree I'll start off with the root node now I just have to go on to all the nodes which are in this range so let's remember this range it was 7 to 15 and I we'll just keep track of where we are going okay 10 for sure it is between this range so for sure we can go so what I can simply say is I can go onto this number 10 so when I say I can go onto this number 10 so I can just say okay in my sum I can simply say it will be 10 plus I can go on in the left also now and right also now because 10 is something I know okay it can be in the middle so for sure I can explore both left and right areas so I'll just say explore basically solve for left like left area and also solve for the right area considering it is in this range the number 10 was in this range okay but that's great now when I say solve for left it will come to left and try to solve for left let's for get for now I am solving for right so now I'm solving for left which means my root is here now again I'll ask is this in this range no by five is even smaller than the left which means five is smaller than the low itself low was a number seven it is smaller than the low itself now if it is smaller than the low then which means this is not the value for sure and all the left values are also not allowed I should go on to right so I have got the case that if my value is actually less than my low value then I should go and try for the right portion okay I'll go and try for the again I'm saying it is less not even equal to if it would have been equal to I would have used that value and then tried for left and right both but now I'm saying it is less than value is actually value it is five which is less than seven so I have to go on to my right and try for the right itself okay I go on to my right and I can try for the right itself okay that's great now um if I am at the right again number seven it is in between 7 and 15 so I can just do the same stuff I can just call this sum with the value of 7 and I can again go and solve for left and solve for right again when I go and solve for left it will go but oh by it is null okay simply return a zero because you want to add the sum of the values n will have no value so I can just have one more condition that okay if my value obviously if my root because it's a pointer if that is a null PTR then I can simply return a zero because that will not add anything in my answer okay that's great now it now left and right both will return a zero it will return a number seven so from right I have solved and get added my number seven and now this right will come to this particular number 10 who called left so left will actually add and number seven now it's the chance to go to right because right was not yet explored okay I'll go to right but that's true so my root will be here is it between my 75 yeah it is okay if it is then I can simply apply same thing okay I can simply say that if I just move this okay if I just move this entire stuff down uh then I can simply say that now I can simply say that 15 plus solve for left right so again I can just solve for left okay it's null so it will simply return a zero solve for right again right it will go and try but 18 is more than my 15 value okay so I'll just say if the value is more than my right which is the high value which I have if it is more than my high value which I have which means okay I can never for sure go right I cannot try this I should go and try for left if maybe it could have some left so I could go and try it for left so I go and try for my left itself and that's how you can simply get this solv okay but that's nice uh which means we are simply using our recursion and it will be a three four lines of code itself now let's dry in quickly on my this portion this is specifically binary search tree again uh let's remember that our low is a six and our high is a 10 I am at this value this is between a number 10 like number six and 10 so for sure I can explore both left and right I can also add in my answer when I exploring my left I'll say five is again oh five is less than my six which means I should not five is less than my six right so I should not go here which means I should never go on the left part I should switch to the right part oh now number seven is between left and right yeah that is true so I should add that number and Al also should try for left and right both right is a null so from there I will return a zero left is a again it is between left and right so I'll just add a six corresponding to that and I'll again try to go for left and right both are null so corresponding to both of them I will add a zero now okay this entire thing is done this is done these are ex these are like ignored entirely ignored now coming on to the right part which we had explored again it's a 50 which is oh but it is not in this range oh great so try for the left which means it is not in the range which means this value is more than the right itself soti the entire sorry it is more than the high itself so exclude basically ignore the entire right part I'll go on the left part 13 but it is again more than the right okay cool ignore this part right part go to the left but left is null oh it if it is null simply return as zero so I'll simply add a zero for that so that will be my answer and that you can see your answer is 6 + 7+ 7 that you can see your answer is 6 + 7+ 7 that you can see your answer is 6 + 7+ 7 23 so the code will look exactly the same that first base Cas is if your root is a null then simply return a zero now simple case if the root value is left low than like less than the low then you can try for the right portion don't go on the note you can try for the right portion if the root value is more than the high then simply try for the left portion if the root value is less than the low then try for the right portion if the root value is more than the high then try for the left portion if not which means if my root value is in between low and high and when I say in between I mean inclusive in between then you should add the root value try for the left value and try for the right value and that's how you can simply get the solt again the time will be o of n but by it's a binary surgery no so it should be l no in the worst case it can still be o of n when the tree is entirely skewed and space is also o of n because again if it is skewed so it will go on and try for the entire recursive stack in deep and that will take o of n space and that's how we simply get this solved cool I hope you see bye-bye
|
Range Sum of BST
|
numbers-at-most-n-given-digit-set
|
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`.
**Example 1:**
**Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15
**Output:** 32
**Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32.
**Example 2:**
**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 2 * 104]`.
* `1 <= Node.val <= 105`
* `1 <= low <= high <= 105`
* All `Node.val` are **unique**.
| null |
Array,Math,Binary Search,Dynamic Programming
|
Hard
| null |
703 |
hey everyone welcome back and today we'll be doing another lead chord problem 703 K's largest element in a stream so stream means that the input is coming and we have to return the output likewise and this is an easy one design a class to find the kth element largest element in the Stream note that the case largest element in the sorted order not the distinct element basically saying that there can be duplicates and implement the K class The Constructor with the K and the nums and we have to add the values uh function which can add the values to our uh data structure which we are going to use to solve this problem and give us the eighth largest element in the Stream so that's it so what they want us to do if we have an example where 3 is the K largest element and this whole thing is going to be our array and nums list in which we are going to return the kth largest element if it is 3 then we are going to return the third largest element which is 4 and the other which other functions which other you can say operations which we are going to do and we can use an array which in which we can just sort at and then sort but we can also use the Min Heap which is more efficient in this problem because we can just let's say self dot mean Heap I call it alongside the self K so the mean Heap will be equal to the nums and the K will be equal to the K which we are being provided with in this case is three so we will just convert this mean Heap into our actual Heap so Heap dot e p 5 self dot mean here self dot mean if okay so now length we will take the maximum length of Min Heap and just pop it a pop it until we reach the K element because if we have the K element for example in this case 3 then we know that we are going to have the third largest element at the very top at the zero index so mean if it is greater than k self dot k uh we are going to Heap Q Dot keep pop another p okay in the self mean Heap okay we are done with our Constructor at this point we have to have you can say a three uh three elements in this you can say in this specific case in our minhip if it is if there are more elements so now we have to add more elements uh which we are being provided three five ten nine four and we will just push them so hip2 dot Heap push them with self cell dot mean here alongside the value and now we will see if the length because at this point we do not want to pop because there can be less element than K we have to check and there is no if we are going to I just saw it there is going to be a while because we have to pop until there are less than or equal there are equal to elements left equal to K elements left in our minute so if the length of the self dot mean here is greater than K only then we are going to pop so he Q Dot keep dot pop with a p okay so self Dot if and after that we can just return the self dot mean Heap at the zero index because we are sure we have uh K Elements which in this case are going to be 3 and in any case we will just have the minimum animates at the very top and it will be like access by zeroth index because at the very top we have a zero index foreign yes this was the class instance so let's use self okay this works and let's submit it and then we will see how this whole thing is working so we have the input like this in which this is the K this is the nums and all other remaining part is just add this whole thing is just the elements which we are going to add in our here so starting from four eight two yeah so the K is 3 K is equal to 3 and now we have said that if we have elements more than k then we are going to pop it so basically we are going to pop 2 at this point because 2 is neither our you can say the third largest element and it is you can say exceeding our limit which is going to be 3 in this specific case so part three uh part 2 and now we are going to add 3 like this three so these three will be added to our here so our heel will at this point is like 4 5 and it has it so we can see that this 3 is neither our great third greatest element and it is just exceeding the uh you can say the limit which is the k so we will just going to pop it and it is never going the only element which we are going to have at the top is the element which is going to be less than 4 so this is just basically at the very first in our Heap in our he but we are going to pop it because uh obviously again I'm saying it again like this is exceeding our limit so at this point we are going to return our four uh like you can see here if we add three we are going to return 4 because 4 is our greatest uh third note the third greatest element but it is also our kth greatest element which can be K can vary so we have four uh five eight in our Heap now and we are going to add five so if we add five then this five is going to be at the location here now the Min Heap will reset itself because it will become like five eight and we are going to pop if we have more than K elements so we'll be removing 4 in this case and the head will become at the very first you can say we are going to have four so we are having five a and now we are we have the case greatest element in our stream which is equal to five now we are going to add 10 so 5 8 it is then 10 being added so if we add 10 then it we know that it is going to be uh be at the very last because it is the greatest element and then we are going to pop the very you can say the very top element and which is in this case is 5 so we are going to return 5 in this case also because the greater element still is 5 the greater K element is still is 5 and we have to update our which will look like this at this point so and now if we add 9 so our mean Heap is like this and if we add 9 then we know that this is going to be added at this place okay uh I just messed up like okay nine okay so the length is going to be increased by case so we know that we are going to pop the very top so the file will be popped and now at this point we are going to return it because 8 is the case largest element so our mean heaps will look like this eight nine then now we are going to add 4 so we our mean Heap is like nine eight nine ten four so this will be just added at the very first and it is also going to be popped because the length is going to be exceeded by K so and this in this specific step we are going to be also returning it because 8 is the case largest element in our mean Heap and that's it you can say four five eight this was our whole output and this was like you can see in this part this is going to be our Ola output so that's it
|
Kth Largest Element in a Stream
|
kth-largest-element-in-a-stream
|
Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
Implement `KthLargest` class:
* `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`.
* `int add(int val)` Appends the integer `val` to the stream and returns the element representing the `kth` largest element in the stream.
**Example 1:**
**Input**
\[ "KthLargest ", "add ", "add ", "add ", "add ", "add "\]
\[\[3, \[4, 5, 8, 2\]\], \[3\], \[5\], \[10\], \[9\], \[4\]\]
**Output**
\[null, 4, 5, 5, 8, 8\]
**Explanation**
KthLargest kthLargest = new KthLargest(3, \[4, 5, 8, 2\]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
**Constraints:**
* `1 <= k <= 104`
* `0 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `-104 <= val <= 104`
* At most `104` calls will be made to `add`.
* It is guaranteed that there will be at least `k` elements in the array when you search for the `kth` element.
| null | null |
Easy
| null |
1,288 |
hey guys welcome back to another video and today we're going to be solving the leakout question remove covered intervals all right so this question is pretty similar to some other questions that we sold such as teemo attacking and a few other ones which i'll link down below if you do want to check out anyway so in this question we're given a list of intervals and we want to remove all of the intervals that are covered by another interval in the list so for example over here we have the interval a comma b so a is going to be the starting point and b is going to be the ending point of that certain uh interval and uh it's covered by the interval c comma d so this is another interval and over here the reason c comma d is covered by a comma b is because the a value is greater than or equal to the c value and the d value is greater than or equal to the b value so in simple words if you have one comma a six right so we started one and at six and for something to be covered it has to be in between one comma six so for example if you had two comma four it would be covered so let's just look at this example real quickly and one more thing that you want to notice is the number that we're outputting over here is going to be the number of remaining intervals that we have so for example let's just look at this over here so we have 1 comma 4 3 comma 6 and 2 comma 8. so the values 3 comma 6 actually goes inside of the interval 2 comma 8. so three is greater than or equal to two and six is less than or equal to eight so keeping that in mind three comma six is going to be removed and now removing three con six we cur we before uh before removing it we had a length of three and now since we're removing one number or one interval we're now going to have a length of two and that's what we're going to end up outputting we're going to output the value too so i'm going to use the same example to kind of see how exactly are we going to solve this question over here okay so over here as you can see it's the exact same uh example one comma four three comma six two comma eight now what we're gonna do the first step that we're gonna do is we're gonna sort this and the way that we're gonna sort it is that we're gonna sort it according to the start value so the start value is one three and two respectively right so now that we sorted let's just do that real quickly one comma four since one is the least and then after that we have two so now we have two comma eight and finally we're going to end up having 3 comma 6. so this is going to be our new intervals now why did we sort it so by sorting it and we want to make sure that we actually sorted it according to the starting value so 1 3 and 2. so by sorting it by the starting value what that's telling us so let's say that we call this interval one interval two is always going to start after interval one and that's true because we sorted all of them right so that is going to hold true and since we actually sorted it by ascending order for our first starting element what that's going to tell us is that the next value is always going to be inside of the closed interval since the let's call this value over here a and this over here b has to be greater than or equal to the value a and that is always going to be true since we sorted it okay so now that we got that out of the way how do we account for this ending value over here so to do that what we're going to do is we're going to have two variables a variable that we're going to use to track what the global ending value is so the maximum ending value so i'll just call this variable over here called ending and we're also going to have another variable for our results so obviously our result is going to start off at zero or one more thing that we could do is we can start off our result at the length of our area over here so we can start it off with three and we can decrease it as we go but what i'm going to do is i'm just going to start off at the number zero okay and our ending value is also going to be zero now what we're gonna do is we're gonna go iterating through our list over here and we're only gonna be looking at the ending values so the first value we have over here is the number four and what we're going to do is we're going to compare so is the number four greater than our current ending value and it is so in that case we're gonna do two things we're gonna make the new ending value over here four and we're also going to increase our result by one so now our result is going to end up becoming one okay and uh now let's just go on to the next step and see how this actually happens so basically what this is telling us is so far the maximum ending that we have is at the fourth second or whatever the number time is and now we're gonna go on to our next number and again we're not worrying about our start value since we already considered that while sorting it so now we have the number eight and eight is again greater than four so since it's greater than that becomes our new ending and we again increase our result by one so now our result has a length of two but now what happens is so now we go down to the next number so we have three comma six and over here the number 6 actually has a value less than our result here and what that's telling us is this interval 3 comma 6 lies inside of our previous intervals that we had so over here it makes sense since 3 is greater than 2 and 6 is less than 8. so we're not going to account for this inside of our final result in other words what is happening is that this over here is getting cancelled so let's just get rid of that so in that case our ending stays the same and our result stays the same and since we reach the ending we're just going to end up returning the value 2 since that is going to be our answer but now what i'm going to do is let's just add one more interval to see why this might not be right and i'm also going to change this value over here so this over here i'm going to make this 3 comma 9 and let's add one more interval of 3 comma 10. so this is going to be our new intervals and what i'm going to do is let's just start off from the beginning so everything over here is going to start off at zero result is zero ending is also zero so let's just go through this real quick so over here our ending is now going to be four our result is going to become one then uh at eight so now it becomes eight and our result increases to two and now at nine is greater than eight so this becomes nine and this becomes three and then we go to ten and ten is also greater than nine so this becomes ten and this becomes four now the problem is our result actually ended up becoming the number four but that's actually not correct if you look at this the num at the interval three comma nine fits right into the interval three comma ten so actually what should be happening is our result should actually be the number three and this over here should get cancelled off but that did not happen why is that so to understand that real quickly what actually would be our optimal answer so our best answer is when everything goes inside of one interval right so that's what's going to happen if everything goes inside exactly one interval and the best answer for that is if we have negative infinity comma positive infinity in other words what all we want is we want this over here to be the smallest value and this over here to be the greatest value in order to be able to accommodate for most of the intervals which are enclosed inside of it so keeping that in mind we've already sorted everything all the starting values uh in ascending order but we never considered the ending values over here so in the case that we have two values so in this case with the same starting value so we have three and we also have a three over here in that case what we want to do is we want to sort the second or the ending value in descending order and the reason for that is we want our starting values to be in ascending order and the ending values to be in descending order so instead let's just get rid of this over here sorry it's a little messy so we're gonna have one comma four two comma eight and this over here is going to be three comma ten and after three comma ten we're going to have three comma nine okay and now let's say we do this all again so until your word is going to be the same but instead so we have these two over here currently our ending is going to be eight so over here we're going to be at eight and our result is going to be two so now what's going to happen is now we're going to go to 10 and act 10 our ending becomes 10 over here and our result increases but now that we go to the next value which is 9 is going to be enclosed inside of 3 comma 10 which is why 9 is less than 10 and in that case our result is not going to change and that is why we're going to end up outputting the number three so that's the other condition that we want to look for so now let's go into the code part of this question and let's see how that looks like all right so let's start off by actually preparing our intervals list over here by doing what we did which was sorting it according to the rules that we had so to do that i'm going to be using the sorted function and uh we want to sort intervals so let's give it that and over here we're going to give it a key so lambda and so what we're going to do over here is that we want to sort everything by the first index so x0 and one more thing that we want to consider over here is if we have the same starting value for uh one or more two or more intervals then in that case we want to make sure that the ending values are in descending order so in order to do that we can just do a simple technique and all we're going to do is we're going to change the ending value to be negative and we're going to sort it that way and the reason we're making it negative is pretty simple so basically what we're doing is let's say we have the numbers nine and ten let's just go back over here so we have nine and ten and let's make this negative nine over here and negative ten obviously negative ten is smaller so in that way what's happening is that negative ten is going to come first so it's a pretty simple way to actually get that in descending order okay so now we have our intervals ready and over here we want to get our two variables so we have the result which is going to start off at zero and we're also going to have the ending value that we're talking about which is also going to start off at 0. so now all we're going to do is we're going to iterate through our intervals so we're going to have our start value and we're going to have our n value in each of our intervals but one more thing that we want to notice is that we don't really care about the start value since we already took care of that by sorting it so over here i'm just gonna do underscore which just basically tells us that we're not actually gonna consider or do anything with it okay so over here we're gonna check if the current ending value we're on is sorry is greater than the global ending which is this value over here so if the current end is greater than the global ending value then in that case we're gonna increase our result by one and one more thing that is going to happen is the ending's value the global ending value is also now going to become the new end value which we're currently on and this is just going to be the maximum end value that we're on and that's really it so at the ending of this our result should uh we should be getting our result and that's all we're going to do is return that result that we have over here so submit this and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
|
Remove Covered Intervals
|
maximum-subarray-sum-with-one-deletion
|
Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**.
|
How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.
|
Array,Dynamic Programming
|
Medium
| null |
383 |
That Welcome back friends today we are going to solve liquid problem 2017 currency note Please subscribe to the Channel If you are looking for material for laker java j2ee interviews where asking solutions for on this channel you have created a lift co dog solutions for the problems S Well S Computer Science Related Videos Life is Dynamic Programming and Great Data Structures subscribe our Interview Preparation for the Problem Notes and Letters from Write Function Thursday A string can only be used once in the pension note Example for the question Interesting aspect can Very From This Ransom Note From The Magazine Streams Bright Light Magazine Character Set For The Question Is Yudh's Last Tweet Android Phones So You Can See In This Example For Example Chhod This Trick Can Be Formed By Using Distich That Bigg Boss Is Website For This Year Hindi Example Hui Don't Have A Good Only Does But One Is Not There Can Be No One Will Solve This Problem For Example Clear and Serious Problem Is So Common What Will U How Will Be Creating This War Not Hui Kaun Kuch Ek From This Magazine Streams Will create frequency are of middle latest frequency everywhere and frequency are two is for magazine ad and both are size with 6 character because in english movies only twenty six character so you can see like for example the physically is equal to a great swadeshi Actually point mintu exit like that one will be appointed to be like that so this is the area of that the area of that the area of that a characters and you will go alone and finally hai maximum 2823 ponting * read a letter show the 2823 ponting * read a letter show the 2823 ponting * read a letter show the British how create very frequency rs.100 S you can see a good this late so I will create an rs.100 S you can see a good this late so I will create an rs.100 S you can see a good this late so I will create an entry 401 is 140 will have two entries for nd Mr one B & C & DS ID proof just one B & C & DS ID proof just one B & C & DS ID proof just one person basis of three then in there should I will have one Android this is for Frequency everywhere similar you will create are frequently are to for magazine show in frequency are 2017 sickling is zero is later for electronic have to player you can have to for later to your grand have to intellect is one in this hare auspicious again will have to frequency And you will have frequency 250 acid 380 plus two plus seat and three meanwhile leave is two frequency right solve opposite do there's no what will give oo will get rid from zero 225 letters and what will oo will check efficiency one entry for every letter Of blessed this frequency too late and equal to class Jain and equal to frequency too right day online form and handsome not for example share it's too sorry year disputed acceptable 2012 to retail store 34 that this fruit depend four digit is to share so this is Active Table Per This Is Less Than Or Equal To Different 1991 Want To Do So In The Soul Will Go For Through This Very Urgent And Will Check Your Best Friends Unsatisfied For All The Letters In Which Means The Question Form Ransom Note In That Case Will Return True for example in this case s you can see dil le entry for later play store here swadesh to is less than no renewal to ₹10 dare and when they reached senior to ₹10 dare and when they reached senior to ₹10 dare and when they reached senior dso again entry decide one here and reduce dasha distributor shown is less than or equal to Solve will return rupee specifically for that is the idea of how they can check difference not idea of how they can check difference not idea of how they can check difference not candy fonts soiled war any liquid soap is created in the river constructed that in this is created frequency 126th 12.6 letters in english from the 2g and 12.6 letters in english from the 2g and 12.6 letters in english from the 2g and they are going to it Rudra handsome look spring and they will update the frequency of cheese character Indra and Sunlight and you will read The Amazing String and will after the frequent use the frequency to here for the frequency of letter for magazine spring tide and after you are done with that will Just Read Through Our Frequency One Here And They Will Make You Rich Non Actors Frequency Is Loosening One To The Frequency To Write Only They Can Form Become Sub Note 31 On This Side That Is Not The Verdict Agree Not Satisfied With Just A Constructive And Wooden table spoon the beginning 530 frequency of character that in the field in the frequency one here is not less daily want to frequency tools frequency day will just make this for your site which they can not form per mention not for example if you Have Bullets Say Egg Fried Desi Revolver Rate Silencer Notice Dushwar 1.30 Friends Hum Log And Ya Magazine Have The 1.30 Friends Hum Log And Ya Magazine Have The 1.30 Friends Hum Log And Ya Magazine Have The Let Us Play And Beat It And E Saw In That Case How E Can Not Form And Submit It Is Only Available For Not Finding Any If Here Fall described in clear 200 seedhi its working of word it given a b etc state of being taken from this data so e will form the one dead to injured discuss radhe-radhe sunao this is fixed hui discuss radhe-radhe sunao this is fixed hui discuss radhe-radhe sunao this is fixed hui one places where you can see and used Oil Switch Correct Now Is Updater Now It's A Our Magazines Tree In His Office And To 20 Days In This Case Which Can See For The Handsome Not Right Surdas Ronit Sweet Roop Sapna British Coming Through Right Correctly On 24th June Can See It's True Solid XX X pet so let's submit this I am so stuck getting more mukut 93.8 mukut 93.8 mukut 93.8 percentage so this is pretty good boy generator 1628 wanted to show you how you can shoulder and no problem pin code swift Please subscribe The Channel Solution 806 Problem Solve Along With Examples and Explain in Details Videos To A Telephonic Screening Interview Jewelers Interviews How To Solve The Problems subscribe The Channel thanks for watching
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
713 |
hey what's up guys think white here I detect encoding stuff on twitch and YouTube check the description for all my information I explained these algorithm the data structures problems for people that don't get them so I do them on leak code hacker Hank I got playlists maybe I'll do more platforms in the future this is subarray product less than k pretty good problem this is medium you're given an array of positive integers okay so we have an array of positive it's positive numbers count and print the number of contiguous sub arrays where the product of all elements in the sub array is less than K so basically we're giving this some array and we're given some number so like in this example 10 5 to 6 is the array and then we're given a number hundred we want to find all of the sub arrays meaning part of the array so like 10 5 4 5 2 or 5 to 6 or 10 5 to you know or just 10 or just 5 you know these are sub arrays and they have to be contiguous meaning the elements they have to be next to each other it can't be like 10 and 6 then elements have to be next to each other we want to find the number of sub arrays where the elements are next to each other where if we multiply all of the values together they are not greater than or equal to 100 they're less than the value that we're getting here like K so if we have 10 that's a good sub array 10 is less than 100 okay if we have 10 and 5 10 times 5 is 50 so the multiple all multiplied all the values that's less than 150 is less than 100 10 times 5 times 2 is 100 that's not less than 100 so that doesn't get included so we just want to do this for all of them 5 + just want to do this for all of them 5 + just want to do this for all of them 5 + 2 is 10 5 times 2 is 10 those so we do that for all of the sub arrays right and we return the number of these sub arrays where the multiplicate if we multiply all the values you know that total product is less than the K value that we're given right so what is the intuition what's the you know how do we approach this right so product I remember the product thing that we did in the other problem we actually had we set prod so we set if we set some variable like prod equal to 1 and that's just to start off because the first number that you're gonna look at you're gonna just multiply by one so we use it we use some variable to keep track of you know the overall product that we're looking at right we're also gonna just have some variable called result which will just be the number of continuous subarrays that just the number we're gonna return what we're looking for right so this is gonna be the number of subarrays that you know there's some there their product is less than k right we could also have like a little base case here right first of all just like thinking about this like you know if k is less than or equal to one all right if k is less than or equal to one then there's not gonna be subarrays all the like we're looking at positive integers right so you know if it's positive integers there's not going to be any sub arrays at all that have less than you know 1 in value there's nothing we're gonna see nothing so we're just gonna return zero okay the approach we're gonna take here is a sliding window approach and I'm just gonna code this out and explain it afterwards so sliding window right I just did that in one of my last videos you just have a left and right boundary usually and you move it along the array as we go expanding the right boundary and then when we want to pop things out of the window we expand we move the left forward so rights gonna be the one getting to the end of the array left you know what I mean a window it's like a window it starts here and then it expands the right boundary is the right side the left is the left side and then it expands and basically when we hit this limit of K we're gonna say oh we can't do this so we're gonna move our left boundary over and then we look at this and then we say oh this is fine and then we expand etc so you'd loop through the array and when you hit this limit you'd start moving your window across the array it's actually a pretty elegant solution so basically we're just gonna say ok well rights this is usually the loop is you know less than the end of the array so well write is less than num styling because it's the ending boundary right then we're gonna do what we're gonna do in the end we're gonna return result that's just the variable we're using here - you know the variable we're using here - you know the variable we're using here - you know return the number of contiguous sub arrays and then we're just gonna do some you know some of those stuff that we have to do to figure this out so product is going to be multiplying by the current elements so by the right elements right so the products gonna keep track of the current product of that sub-array we're currently looking that sub-array we're currently looking that sub-array we're currently looking at in the window we're also gonna want it now we're gonna want to check right like I said in this window we're gonna you know it's ten right and then it's 50 and then it's a hundred so one that once it hits that limit we have to make sure we start you know what if it went up to a thousand maybe we have to pop out multiple elements on the left side so we have to do a loop inside of here right so the loop is just gonna be okay if the current element we multiplied puts us way over that limit we have to say okay while prod is greater than or equal to K we got to reduce that limit and to reduce that limit all we're gonna have to do is prod divided by equal numbers of left so pop divided those numbers off the left side right because we're doing multiplication so we got to divide when we remove xylem elements from it and then just increment that left boundary right it's a left plus boom so this will you know when we over passed the limit like right here when we hit 100 we're you know pop and I left off and you know moving here we divide it off and then it's back to ten now how do we calculate our result how are we gonna calculate the number of contiguous subarrays right so this formula right here is basically helping us you know find these you know getting the product of a sub array moving our window across making sure it's not over that boundary so this is the formula right here result is equal to right minus left plus one and we can go over an example here really quick to you know kind of show you how this works basically what's happening is the right is the ending boundary and left is the beginning boundary so the indices you know the length of it is obviously going to be right minus left right and look just let's just look at an example so basically what's happening is when we expand so we start at the beginning right we're at zero right when we expand we're adding one for the new elements and the size of all of the elements together so let's just look at an example now so 10 5 to 6 K is 100 right so we look prod is gonna be you know zero it's gonna be 1 times 10 which is gonna be 10 right then we're gonna look at result is going to be it doesn't it oh sorry we have to increment right missed that while I was looking so result is right minus left plus 1 0 minus 0 plus 1 so we expanded we saw an element so we always add 1 when we add a new element to our window so what +1 we're adding a new element to so what +1 we're adding a new element to so what +1 we're adding a new element to our sliding window so first element we add is this boom our window is like this now our window is gonna expand into 10 and 5 right because we loop forward right gets incremented so 10 times 5 is 50 so you look at that 50 boom okay now we look at this it's not over so results is equal to okay right is bigger 1 minus 1 so 1 minus 0 so you actually now that we've increased the length we always add that increase in length plus the new elements as well you know what I mean so it's 1 right now the result was 1 and then we expanded the window so what we do is we're adding a new element to the window so that particular element right here 5 is gonna be its own sub array so like we added 1 because 10 is its own sub array right that's less than 100 and multiplication value now we're expanding it so this 10 + 5 is 1 sub array so that's 1 and this + 5 is 1 sub array so that's 1 and this + 5 is 1 sub array so that's 1 and this 5 is also suffering so that's 2 so when we expand we add 1 this plus 1 is 4 that individual sub array so that's plus 1 there but we also expanded by 1 so we incremented right so that boundary is going to be bigger so we added 1 for that you know when we expand the window there's also that addition there and that's just how it keeps going that's like the pattern hopefully that makes sense to you guys so when you expand again the right got expanded again and I mean in that case we do this you know thing where we pop off but let's say we expand it again here you know we add another one for that just that individual 6 but we also you know this is already on right like you know when we're expanding the you know the number of sub arrays is already there cuz we're doing oh dude plus equals sorry we're doing plus equals so I was about to say result already has you know the number of sub arrays while we expand like result stores this and then it plus equals again it plus equals another two when we do this and then we go again and it keeps storing the number of sub arrays while we loop through that we've already seen so it stores it and it's good hopefully that makes sense to you guys I think that explanation was okay maybe it is a little bit confusing but if you look at it I promise you know you'll understand I mean I thought I did my best you know so let me know if you don't understand it I could try and answer your questions and discord please like and subscribe to promote the channel and yeah that's pretty much it very elegant solution pretty straightforward here I really like the solution and yeah thanks for watching I will see you in the next video alright peace
|
Subarray Product Less Than K
|
subarray-product-less-than-k
|
Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
\[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\]
Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k.
**Example 2:**
**Input:** nums = \[1,2,3\], k = 0
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `1 <= nums[i] <= 1000`
* `0 <= k <= 106`
|
For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.
|
Array,Sliding Window
|
Medium
|
152,325,560,1083,2233
|
35 |
hello everyone let's look at search insert position the problem statement is we're giving a sorted array of distinct integers and the target value we want to return the index if the target is found if not we want to return the index where it would be if we insert it in order for the first example 1 3 5 6 target is 5 we simply return 2 that's the index for 5. for the second example the input is one three five six target is two it's not in the input array we wanna insert it first where should be the index that should be index one that's between one and three i guess this is a typical question for us to use binary search let's jump into the code base straight away so we have our left right pointer here we first handle all the edge cases if target is less than the smallest value in the input array we simply insert all the way in the beginning so we'll turn zero if the target value is larger than the largest value in the input array then we need to insert all the way in the end let's return non-stop length and then let's return non-stop length and then let's return non-stop length and then we can write our standard binary search and all the way in the end we can simply return left here i want to quickly point out that there is also another common expression to get this mid value that's to use bitwise operation to shift right one bit and these two should do the same thing let's try to sum it first it passed let us look at the complexity the space is obviously constant but high is o log n because we use binary search i also want to discuss why in the end we want to return left why not we return right to discuss this we can first look at the last iteration for this while loop that condition would be left equals right and when we get in we get the mean we get this mid value will be the same as left and right so three of them will pry at the same position and then we do the check if e equals we return mid if not so if target is less than this value is less than this current position where do we need to insert we just insert at this position that's our left if target value is larger than our current position it's at the right side where should we insert we should insert at the right side of this mid value that's left equals mid plus one so all the way in the end we simply need to return left if you have any other questions please leave a comment below thank you for watching
|
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
|
96 |
uh discussions is unique binary surgery so you are given the integer answer return a number of the structurally unique PST so once again this question is really challenged and I'm going to just try my best to explain so when n equal to one you can have what the node for itself right so it could be a node one for the tree in that for the entire tree right and equal to 2 or equal to 2 you can have one flow root two on the right or two follow root one on the left so this is equal to two and let me to the include three like three is example one and I'm just going to explain what happened over here so what happened over here is what when y equal to root right when y included root just look just to get one three could be on the right and two could be on the left when there is a sub uh subtree of one right so this is what PST and one two three this is another one and then two for the root is what uh one on the left three on the right and three for the root is three to one or three one two this is also work but look at this I'm gonna just zoom in a little bit closers so look at this under the on the root of one left is zero the right is two right um this on this tree right this is left is zero and then Y is two and then when you go on the uh go down the next level right this is one this is zero when you go down the next level this is zero this is one right so there are two way when you're going down right one zero one and this is what this is a little bit tricky so for this one is one all right so one is only you only have one way and this one is what two zero so two zero right this is also two zero right so we're going down this is one zero and zero one right so the number of a possible uh generate right the subtree it determines how many left and left or right subject you have right so uh once we know the logic we can probably use in the memorization uh just using a DP for 1D array and we can just keep calculating the current left for the current n right turn left for current and the current right for the current because your end will increasing right and then we're starting from one all the way to the end and then once we reach from the bottom up right we can actually calculate uh the current number for the future and you are trying to get so this is the idea so let's just start holding for the uh for first solution so this solution is going to be using an unscrewed time complexity so you will be able to know what happened and they just stop talking so I'm going to give you what M plus one space for in the red APA this is because I need to store the index 0 right so I'm going to say the default index 0 is going to be uh one and then when I want to return DPN all right so uh once again I Traverse the entire phone one two and right so just imagine one to one is what it's pretty much like this kind of sub tree or this one right and then we need to calculate the left and right based on the number of no right so I will have to create another folder but in this for Loop I'm going to just paste some uh calculate list sub uh sub three note based on the I so I'm going to say J equal to one J less than equal to I and then J plus right I would definitely get a number uh the number of a node based on the I right and my current DPI is going to be what plus equals three plus equal because you will just keep adding right keep adding your current in index DP uh follow what follow left and right uh possible com uh you probably have to say a combination right combination of uh three and then this is going to be DP J minus one times DP I minus J all right so what this means is What dpj minus one J minus one um and DPI minus J so imagine that I equal to n and then earn uh so n minus n is going to be zero and M minus 1 is going to be what um it's going to be like the tree you have on the left so this is going to determine like what the left and this is going to be on the right so um how do I explain so imagine that I and J equal to one first I equal to 1 comma J equal to one and then uh this will be what DP this is going to be what 0 times DP 1 minus 1 is actually zero right all right so now you in you increase your J by one so J equal to two but I is actually one right you'll break out of uh J equal to two for so your increment I by one which is I equal to two J equal to one you're starting from one again right and this is going to be a DP one minus one is actually zero times DP 2 minus one is one right and then we already calculate the DP one equal to dp010 DB is 0 right and db0 we Define is one times one is one right so DP one is also one right uh if I equal to one there's only one uh there's only one possible three right if n equal to two if one equal to two you have what two right so this is DP to but don't forget we need to plus equal y because we'll increment our J equal to two later right so DP zero times DP one times one is one plus I'm going to change another color DP 2 minus 1 times 2 minus two which is zero so plus one times one so one plus one is actually two right so and so on right you're going to keep calculating right so uh again I'm going to just submit Michael and submit yes all right I'm gonna just set a breakpoint right over here right and uh you will pause it at any second if you want I'm not going to explain but just probably look at the power right and going down foreign so this is a solution and then you'll definitely uh get more familiar with this kind of question I'm going to say this is going to be hard all right so this is one of the solution I'm going to uh talk about the next solution so the next solution is going to be using a recursion and then you only have one folder but you are going to use it using a recursion to code the left and right subtree so the idea is pretty similar right so I'm going to say DP equal to what equal to new end and plus one and I'm going to create a helper function probably and I'm just using the same function and I'm going to put in my I mean pass in my DP array into the function and also the one and also the end and now when I want to return this one DP and come on sorry so yeah so this is the helper function I'm going to just overload the function name doesn't matter right so it will initially become what becomes 0 right and then if I is actually less than equal to 1 right you're starting from one and then you should you just return one and then what if your DPS already have numbers so DP at what DP and if dbn is not equal to zero you will what return DPN so you actually decrement your end from earn to one right it will decrease into one so I'm going to have another uh let's sum so which is going to be called total so I'm traversing from one two and right so now I Traverse him uh the one to earn and calculate my what calculate my current total for left and right combination something like this right so it's total plus equal what a num time sorry uh I'm gonna pass in while I pass in the DP and passing overpassing the I minus one times this one DP and what do you think for the right this is going to be what the exactly the same thing for what and minus hi and then when I want to return I need to set the current value which is n equal to total and return what you can say total or DPN all right so now uh this is the left right just I mean just imagine this is a left and this is a right so when I equal to one like n equal to one I'm going to say DP angle one so it's still going to be DP zero so we pass in dp0 into here and then we already know dp0 is what is should be one right so less than equal to one should be one and then you will assign one uh back code here right and this is what DPM minus I A minus one is what uh if n equal to three then it's going to be what uh two so you just keep recursive call this function so uh but you only go once because you'll break out the like infinite Loop when there is a memorization on a recursion you will know that this is not equal to zero and then you'll definitely uh break out so uh I'm going to just quickly draw the idea so I'm going to say uh this is going to be what uh zero and this is two right and then uh since you cannot go deeper for the zero so you break out so you're going up and this one will go what go to what two minus one right uh sorry uh this is gonna be you okay what uh and N is coming out too so on was three and then you call you Call zero two and then let me just draw a little bit bigger so one was initially three and then you call uh one minus one is actually zero and then three minus one is actually two right now n is now two right and then one minus one again is actually zero and then two minus one is actually one right and this is one oh sorry sir uh the left is going to be zero then right uh one minus one is actually zero so you actually hit like the base case when there's a zero right and this is the entire memorization for the recursion so I'm going to still commit and then submit all right so let's talk about the time and space so in this one the space is all open right and the time is going to be all open right here but also all of them right here and the worst case for this one is going to be all of N squared the time and this is all of them for the space right and uh if you remember the first solution is like this is earned for the space all of n Square for the time so they are the same but one is using a recursion to find out the solution uh and this one is using a two-fold to uh and this one is using a two-fold to uh and this one is using a two-fold to find out the solution so this is pretty much the idea and uh it's a little bit long and just make sure you know like you need to peel from bottom up and because we want to know like when you go to one we calculate for n equal to two which is DB DP uh so this is dpz right and this is if you want right and then uh wait dp0 is actually zero DP one is one db2 is what is two tp3 is five okay so this is what I just I mean I just made a mistake dp0 for default value dp1 for uh you know include one db2 we calculate db2 based on dp1 we calculate or include the three based on what db2 so we get dp3 so we need to build from the bottom up we cannot go from top to bottom this is not work it I mean this is not working right so uh here's my solution so if you have any question leave a comment below subscribe if you want it and I'll see you next time bye
|
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,624 |
Hello and welcome to channel again this is Shaur Awasti and today we will talk about easy level problem of lead quote which is largest sub string between two equal characters so basically what we have to do here is we are given a string in the input okay so we have to Taking that input string, we have to tell that the length of such sub string in it is the length of the largest sub string which lies between any two same characters. Well, like here, if we take an example, then there are two same characters, here P is A. The substring in the middle is of zero length. Zero, like here A, there are two same characters. What is the length of the substring between them, it becomes two. Similarly, there is no repeating character in it, that is, no same character can come out, hence -1. So no same character can come out, hence -1. So no same character can come out, hence -1. So we will take this one extra condition that if in this case, if the max variable we will maintain to find the length of our maximum largest substring, if the max variable we will maintain remains constant, that is, it will not be touched by that change. If it is not there then we will return minus i.e. none of our minus i.e. none of our minus i.e. none of our repeating character was found. Okay, once we understand the white board, what is the approach we are taking in it, so basically we are using the map on Y. Okay, I have made it quite big. Took an example so that it can be understood a little clearly, what will I do, I will enter a fud loop on the entire string, ok and one by one, I will keep adding the characters in the map with their index and with the help of this map, what will we do, we will find the maximum number of a character. We will maintain the first index so that we can find the length. Let's take an example between two same characters like here we have a, so we have a and its index a is ok, again here we have b, second here what is how much b is b 1 c 2 a Now see a is already existing, we have crossed out these three and entered ya already existing, its index is three and this is already existing, so we have in maxi i.e. in maxi which is so we have in maxi i.e. in maxi which is so we have in maxi i.e. in maxi which is initially our There was zero store, how will we update it? A is here and we have the index of the previous one stored, so the current we have here is a pointer to that index minus previously stored index plv i.e. 3 previously stored index plv i.e. 3 previously stored index plv i.e. 3 my 0 p 1 = 4 i.e. How many my 0 p 1 = 4 i.e. How many my 0 p 1 = 4 i.e. How many elements are there in total? This is the total number of elements: F A elements are there in total? This is the total number of elements: F A elements are there in total? This is the total number of elements: F A B C A. We update this maxi and write this as four simple again. Let's move ahead. Now our A was already stored here. Now we update the new index of this A. We will not do this because we are storing the previous index of any one character, that is, the earliest index, okay, let's move ahead, came G A G F and in this we took the three, otherwise this is done and this is done. F then came I R G I sorry I take I R from six I R became six again okay after that we take G and G is already doing fo P and here G came P Okay this is the index 8 Okay, now here it is already existing, here it is 8 - 4 + 1, the total has come to f, here it is 8 - 4 + 1, the total has come to f, here it is 8 - 4 + 1, the total has come to f, so now we will update it with five because f is bigger than four, so we will update it with five, look here once 1 2 3 4 5 We are getting this one of five length, this one is fine, let's see further, we will not consider it, again h comes in the map, we have written h, what is the index of h, then again comes our g and g's last. What index did we have? The index of g was f and what is this index? 10 So again what comes to us is 10 minus 4 psw total becomes 10 minus 4 6 psw 7 so we update if it is greater than 75 then let's have max here. Gaya Se is fine, will we consider it? Then came J, so we write J and what will be its index? 11 J is done, our 11 P is done, then our D is done, 12 P is done, D is 12. P 12 ok then comes our A and A was already assisting and this again A comes ok so how much is it 10 its was 11 12 13 so this index becomes 13 and already is assisting its index is 13 My 0 PW becomes 14, which is bigger than this, okay, 14 is updated, so again we will consider A. No, then came A, we stored A as A and its index became our 14, okay, so this is our map also complete. Iteration is complete. Now if we look here, we will find the value of the largest which is max i.e. the value of max sub string length i.e. the value of max sub string length i.e. the value of max sub string length is 14. What is 14 which is from here to this A. If the length is then A middle element and A is taken into consideration and what is its total length. What is the length of the total? 14 But here we see that the substring that we have to return is what is the length between these two same characters. If we want to return then we will simply remove these two i.e. whatever maxi we i.e. whatever maxi we i.e. whatever maxi we return i.e. whatever maxi we return then return i.e. whatever maxi we return then return i.e. whatever maxi we return then what will we return, in normal condition we will return maxi minus two and if maxi remains unchanged, when will maxi remain unchanged? If the value of this maxi will remain zero, if the value of maxi will remain zero or the maxi will remain unchanged and in which case the maxi will remain unchanged, when no repeated characters will come and till the repeated characters will not come, we will not interrupt our fast. If we do this, then the value of maxi will remain zero and in this case, if the value of maxi remains zero, then this is a normal case, if the value of maxi remains zero, then this is a special case and what will we return in that. Okay, so this is our complete approach. Let's try coding this first of all we store the length in a variable named int n, okay s is the dot size, after that what we do is we do a for loop, we take a map of comma int and in it we give Let's take a for loop okay and what we do in this for loop is we will check if add find if map dot find s of i if already exists not equal add first ser est then what will we do Maxi one minute, let's treat maxi first, but it's in maxi equal to 0, okay that maxi is equal to max of maxi comma, if it was found, that is, if that element was already present in ours, like here when A came. Here A is already existing, so what we used to do is that current i is our current i minus the value of its previous i.e. the value which is in the minus the value of its previous i.e. the value which is in the minus the value of its previous i.e. the value which is in the map, we used to float here, so what we used to do here in maxi is i - so what we used to do here in maxi is i - so what we used to do here in maxi is i - m off. s i + 1 will do this ok this will be done else i + 1 will do this ok this will be done else i + 1 will do this ok this will be done else what were we doing in the else case we were simply pushing into the map ok we will simply insert it into the map and keep its value its index ok after that we What we are doing is we are checking if maxi is unchanged then if it is zero then we will return minus and else we will return maxi minus mit. Sorry, okay, let's run this for a minute. Okay, so all three test cases pass. Once done, submit it and see if it is ok then it is successfully submitted, so thank you so much for watching this video. If you like the video, then like the video, subscribe the channel and press the bell icon to see such daily PTD solution. See you in my next video till then bye
|
Largest Substring Between Two Equal Characters
|
clone-binary-tree-with-random-pointer
|
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "aa "
**Output:** 0
**Explanation:** The optimal substring here is an empty substring between the two `'a's`.
**Example 2:**
**Input:** s = "abca "
**Output:** 2
**Explanation:** The optimal substring here is "bc ".
**Example 3:**
**Input:** s = "cbzxy "
**Output:** -1
**Explanation:** There are no characters that appear twice in s.
**Constraints:**
* `1 <= s.length <= 300`
* `s` contains only lowercase English letters.
|
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
133,138,1634
|
116 |
hi guys hope you're doing great our today's question is populating next right pointers in each node so the question says you're given a perfect binary tree where all leaves are on the same level and every parent has two children so that's what the perfect binary tree means the binary tree has the following definition so each node of the binary tree would have a value a left and a right pointer and in addition a next pointer as well okay populate each pointer to point to its next right node so here the right node does not mean the right child it means the node that is in the right of that particular node in the tree right if there is no next right node the next pointer should be set to null initially all next pointers for all the nodes are set to none you may use constant extra space recursive approaches fine you may resume implicit stack space does not count as extra space for this problem so for example we have this tree right and this is the output that we need so here as you can see that one does not have any node to its right in the tree that is why its next pointer is pointing to null but for two we have three so twos next pointer is pointing to three and since three again does not have anything on the right that is pointing to null and then on the last level also you can see four points two five points two six points two seven and seven points to none right all right so let's have a look at the approaches we can take to solve this question so whenever there is a question on tree it's basically around how you are traversing that tree right you might have to use a combination of the collections or some variables to be able to accomplish that but it's basically all around how you traverse the tree and there are four traversal techniques for a tree which are listed here so please pause the video have a look and come back so I think this question is just an indirect implementation for the level order because if you see in level order the way the elements are obtained if you do a level order traversal for the tree they are in exact same order in which we want the next pointers to be pointing to the next elements so eight should be pointing to null because that's the end of the first level then if you see five and four form one level so five should point to four and then four should point to null and then four nine seven eleven and then so on so we will be doing a level order traversal here I think but we just need to find a way to tweak it in some way that we take care of managing this next pointer as well okay so let's get started so we're already given information about this node we know these are the fields right well left right and next okay so talking about the level order traversal the idea behind it is that we make use of a queue okay and we start traversing the tree from the node root okay and initially we push root to the cube okay and whenever we finish a level in the tree we also add a null to the cube right so initially since root is the only always is the only element at its own level we insert the route and none to the key now we basically have to keep traversing until our queue is empty so what we will do is that we pull the element which is in the front of the queue which will initially be rude and then we do a certain number of checks right so if we if that element which is at the top of the queue is a null it means that we have reached the end of a particular level in the tree and that means that we have so the previous level is over and we have traversed like we have inserted all the children of that node in the queue so we want to mark that as well in the queue by inserting under the null okay now if at the same time the queue has become empty then it means all the levels have been traverse and null was the only element so then it means that we can return our answer or what do we want to do after the travel solid is done and then the third and the last option is that we actually get a node right which is a node of the tree so we just check it for a left or under right in the order left and right because that's how we want to traverse it in level order traversal and we insert a left and a right into the queue because that is how they will be retrieved given the property of queue so what we will be doing here is that for each element whenever we all that element whichever is the current element in consideration we'll just do a peek okay and the P could be null if that level is ending so we will still just point the next pointer to that and it could be another element for example four five and six so we is still pointed to the neck the element that is in the at the top of the queue after we have done a poll so I think that's how we will try to attain this task let's get started and I think the code will make it clear okay so just a simple base check always good to do it if the root itself is nothing then there's nothing that we can do we just return up now this one right now let's create a queue of nodes right and let's just call it this it's an implementation of linked lists in Java and hence we are like doing this right and as I was saying we will just add the root to it and we will also add narutimate right so this basically covers the first level in the key right now so unless this is not empty the queue is not empty we want to keep traversing because as long as the queue has elements it means that the tree traversal is not done yet right so while the queue is not empty what we want to do is that let's just get the current so the current which is Q dot all right so that's just the element at the top of the queue okay now as I was saying that there could be multiple cases like we could have you know the current would be null right so first of all let's just check if all elements of the tree are done and this was the last null of the last level in the tree so that would happen if current is equals to null and queue is empty right because there wouldn't be anything else left in the queue so if that's the case then we are done and we just return route right because ultimately that's what we have to return right we just have to populate the next pointers and return the route again so we just return the route else okay if that's not the case then is Curren none then it means that we have reached the end of some level in the tree and we would be basically just putting another nun into the tree okay so we just that's right otherwise okay and we just want it to continue but we don't want it to do anything else we just wanted to continue with the other iteration otherwise it's an ode right so what we do is that if our element so with that element what we do is that we have to update its pointer that's the next pointer so it's called next equals to Q dot peak right so peak will not remove the element from the queue it will just read the element at the top of the queue so and that's what we need to do right so we just set this okay and then we check if the left is not equal to null right we just insert that so we just say that you don't add current dot left okay and also if current dot right is not equal to null because we want to continue traversing the area so this is a part of the level order traversal current dot right okay yeah so I had gone way too much with this so that's all right that's all we want to do basically and once we are with this we just return the route okay right so let's see this works mmm looks like let's try submitting great that works so the time complexity for this would be off n because we have traverse all the elements just once and the space complexity would be constant of one mix we have not used any the collection or rather we if we take into consideration the queue then it would be off n but if for example the question say is that if you are using a stack it does not count as any extra space then we can call it both one so I really hope that you find this video helpful and understanding the level order traversal in a better way for trees and if you do please like share and subscribe keep coding and take care guys you
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
40 |
hey guys how's everything going let's take a look at number 40 combination some tool actually we just finished 39 combination sound so there this is just like a slightly different version of the comp problem we're still given a collection of candidates numbers and target find all unique combinations blah but this is different the previous problem the any number could be used in any times but in this problem we can only use the number in a candidate for once but these comes at a cost that the numbers are not unique we means that the candidates are not unique yeah with their you can see that there's double one in these problem in these candidates and actually we can do the same as what we did in the last problem so if you haven't seen that video if you want no mud no more about the details please refer to my last video about 39 combination some it's very I think it's pretty straight it's pretty simple to understand and it has a good explanation there I'll try to add a link this on the screen you can also click on that okay so I'll just see four here I just copy pay the coast code okay this is actually for combination someone the first thing we also we the first thing is that we need to sort these are this doesn't change and the prop that the changes are it says each number in the candidates may you only used ones in a previous example when we try to add new numbers to the existing temporary we start at the index right we're given index we start with index so actually the next time we the next I we should pass it to I plus one it means when we have puts one in a number we should have put next while number so this avoid the duplicate but the other problem it becomes that there's a problem that like one if all ones if there are all ones for this one it will traverse all the possibilities of all ones right so for this one he doesn't need to check for all cases that are possible it for all cases that be the ones above this one after this one are already checked and we are at the round of this one so we have to avoid this also if that least one plus a 1 and then we check here with suka 1 so that's not cool right so we need to avoid wait a minute avoid duplicate results by checking if they are the same numbers in a consequence their consequential same numbers duplicate so if can ok here if num equals the previous one then we should ignore it but the problem is that when we are checking like some 2 3 we check this one and this one actually these 3 could be one possible solution but if we just do this it's what can it well skip this one because the one here equals to the previous one so we need to keep the first number add in a valid and it and just escape the other numbers so the first index is okay so if I it's bigger than index we only skip for these ones yeah so which means that for we checked the first one and then go to next one and good next one we find three right so we go to this one I know it's already three so we just skip this one and go to next number move this one a forward but it's the one it's the same so we just skipped all the way ones skip all ones yeah just please draw to draw some cases on your on a paper and you will understand that better this is actually is a common cases I think I've read that in the threesome I think in other in another problem that's similar to this and I've done the same so keep the first one escape the consequential same numbers or keep the consequent sequential duplicates I'm not sure whether I say I express it in the right English mmm but you know what I mean okay so yeah let's run the code except it so let's submit yay accepted and the time and the space complexity doesn't change too much from the previous problem so I just leave it to leave it in there and that's all for this problem thanks for watching see you next time bye
|
Combination Sum II
|
combination-sum-ii
|
Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30`
| null |
Array,Backtracking
|
Medium
|
39
|
376 |
welcome to march's leeco challenge today's problem is wiggle subsequence given an integer array we turn the length of the longest wiggle sequence a wiggle sequence is a sequence where the difference was between successive numbers alternate between positive and negative in other words the difference from the previous array is going to be first positive and then negative now a subsequence is obtained by deleting some elements from the original sequence leaving the remaining elements in the original order so we could skip numbers if we'd like and we want to try to solve this in oven time now generally i like to solve these problems from the brute force method all the way up but if i'm being frank i found the brute force method even more confusing so i'm just going to go straight to the greedy approach and see if we can figure that out uh you know going with that so the first thing we want to do is let's figure out how do we calculate like this array of differences and to do that it's pretty trivial we just need to go through the entire array from the second element check the previous and get the difference and just add that to an array right so what i'll do is create a dp array and this is going to be 4i in range of 1 to the length of nums what we'll do is get the length of nums from the previous one and subtract that with the current one and we'll put that into this array here so first thing i want to do is let's make sure this looks okay and it looks right so once we have this it kind of just becomes a matter of iterating down this dp array to calculate what's the longest number of like flipping right so we can easily do that by saying start check the previous element and say if this is negative and this is positive then increase our counter or if this is negative and this is positive increase our counter otherwise just continue and that would be it but there's a problem here and the problem is we have some weird situations where we could have differences that are the same but require different answers so here with like this one the answer should be one here with this answer with two this should be two so what's going on here um because with our algorithm we would just you know never increase our counter for both of them uh and if we started with a total of two this would be wrong right um so the issue here is these zeros like if the difference is not zero uh then we could at least increase our counter or not increase our counter but we know we at the very least the length of this thing is going to be two because you can imagine like one two three four uh well this technically counts right as a wiggle sequence but here this would not uh because there's no difference going on so it's these zeros that we that's kind of a problem so uh ultimately like one way we can think about it is well we should pop off these repeats like in order rather than doing that why don't we just get rid of these zeros let's just get rid of them we'll say look if this is zero just don't even add it to the stp array okay so if it doesn't equal zero then add it to the dp array okay so we'll do that and what that's gonna allow us to do is say okay look if this dp's empty then we should just return to one immediately otherwise we can start with two and then just count up and see what our longest thing is so let's go with that we'll say look if not dp then immediately return to one otherwise we'll start with a two and then we'll just iterate down our dp for i in range of one to the length of dp we'll do the same um now we'll do our check here we'll say look if dp i minus one is let's say positive and current dp is negative or the other way around we flip it then we can increase our current save this one otherwise we just continue and at the very end we'll return our current so this should give us our answer it looks like that does let's go and submit it there we go accepted so this is o then we do use of in space because of the stp array now you could write this algorithm so that we can avoid that by storing like the previous and the current uh but i just didn't really want to do that because i didn't think it was very intuitive it just messes up the code a lot but the logic would be exactly the same so um yeah like all those other approaches i found more confusing like the top down dps and the recursive solutions so this seems much more intuitive to me um yeah so i think it's one of those rare cases where it just makes sense to uh start off with the greedy approach all right okay thanks for watching my channel remember do not trust me i know nothing
|
Wiggle Subsequence
|
wiggle-subsequence
|
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time?
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
2271
|
822 |
today i'm gonna do uh lead code 822 it's called card flipping game i'll be given uncards with a positive integer printed on the front and back of each card uh the front number and back number of each card could be different or could be the same and we'll try to flip any number of the cards and after the flip we will pick one card so the number x on the back of the picked card if it's not on the front of any cards after the flip then we call this number x is good we will try to output the smartest number that we consider good if there is no such number we're optimist zero and the input is front and backs represent the number on the front and back of the card a single flip will swipe the front and back number uh so the value on the front and the value on the back will be swapped in the vice versa we have the example for this one say five cards uh front number is one two four seven and the bex numbers are one three four one three as the initialization uh if we just flip the second card so the second card front is two back is three and two and three will be swept so the current front we have is one three four seven and the current backs we have is one two four one three uh if we just pick the second cards from the current backs numbers and the current pack of this second card is two because two is unique among the current france numbers so we call this 2 is actually the good number because in this case 2 is the smallest we can get so we're output 2. let's just have a breakdown of this example basically we can find that um there are just two types of cards the first tab is the front number equals to the back number so we can consider this kind of card are bulletproof to the flips because no matter how you flip this card um the fronts will always the front and backs they're not changed right you make no difference um and this numbers simply cannot be the good numbers to choose to pick because um the back number can never uh be unique among the france number we have because we have the uh this particular car's front number is the back number right um so we can actually traversing through the front and backs to find out uh what kind of numbers that we considered the numbers we can never pick and we can have a hashmap headset for it and another type of the number sorry another type of the card is the card that with a different front number and back number so the flip can actually really take effect with such cards so for this particular type of cards we just want to make sure that the front number or the back number um whichever is not uh in the cant peak set that we already have so if the if such number is not in the set um then we can make it a good cat good number candidate uh so for example four one like this card uh the first card of the uh of the cards we have um the back number is one and the front number is four so if we pick the back number of one is actually uh in the count peak set that complex that includes one right so um it cannot be selected uh for example like this two and three uh for the second card it has the front number of two and back number of three neither two or three in the account peak set so two and three are all good number candidates um but we'll pick two because 2 is the smallest one right so let's just write this the solution following our classification strategy let's do that so first let's start with the account pick set make it set and for range so if front i equals to text i or just add this number excuse me all right so we already have the config set and then let's just traversing through the front number and back numbers first make sure that the number is not in the current peak set and or just uh have a result starting as sorry actually me so return price if price is not equals to vote just simply return zero so let's see how it works okay past and submit all right there you go so that's our solution for this one okay
|
Card Flipping Game
|
unique-morse-code-words
|
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).
After flipping the cards, an integer is considered **good** if it is facing down on some card and **not** facing up on any card.
Return _the minimum possible good integer after flipping the cards_. If there are no good integers, return `0`.
**Example 1:**
**Input:** fronts = \[1,2,4,4,7\], backs = \[1,3,4,1,3\]
**Output:** 2
**Explanation:**
If we flip the second card, the face up numbers are \[1,3,4,4,7\] and the face down are \[1,2,4,1,3\].
2 is the minimum good integer as it appears facing down but not facing up.
It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.
**Example 2:**
**Input:** fronts = \[1\], backs = \[1\]
**Output:** 0
**Explanation:**
There are no good integers no matter how we flip the cards, so we return 0.
**Constraints:**
* `n == fronts.length == backs.length`
* `1 <= n <= 1000`
* `1 <= fronts[i], backs[i] <= 2000`
| null |
Array,Hash Table,String
|
Easy
| null |
1,002 |
find the common characters now the question says given an array a of strings made only from lower cases so our string is going to be made of lowercases return a list of all characters that show up in all strings within the list including duplicates so you want to find a character or a letter that occurs shows up and all of the strings in our array for example if a character occurs three times in all string but not four times you need to include that character three times as our final answer so let's say that we have our array and our characters are something like a aaa a and a b so we have to look for a character that occurs in all of these strings and we want to account for duplicates so first letter is going to be a and a occurs in all the strings so we have our a next is another a because a occurs four times here four here and three here and it's going to be another a and now we have one a that's left over here and one a that's left over here but since our first string doesn't have a another a we're going to count this only three times not four times so this is what the question is saying over here now let's look at our example one and our example one has e l as common characters so e is over here so we add it to our result l is here for bella l over here and l over here so we have our one l we have our second l and we have our last l so we were able to account for duplicates over here now let's look at example two well all of the strings have c we have our c the first one has two o's second one and third one has two o's but since second one has only one o we have to put only one o in there even though string one and three has two o's the key point is that you have to account for duplicates now how can we go about solving this problem well first thing i that just comes to my mind is how about we create a array and each array is going to have an object and in the object we're going to have our characters as keys are going to be the characters and the values are going to be the count of each characters so depending on this what we can do is we can then literally do all the characters in one string so let's say the first string and iterate to all the characters and check if they exist in our object if they do we want to decrement the count by one because we have to be able to count for duplicates and if the count is zero we just ignore it or we can delete it that's totally up to you but as long as all the objects have that character and as long as the count is greater than one we want to add it to our result variable which is going to be an array of characters if you guys find this helpful make sure you guys like and subscribe thanks our solution is going to have a time complexity of all n squared and space of o of n now remember that we talked about how we're going to go through each letter for each string and get a count of each characters right so we're going to have an array of objects and each object is going to contain each character as keys and count of each character as values but we want to do that for only two strings the first one we're gonna use it to iterate through our characters and check if each character is in the rest of our string or not so if you want you can actually just make a count of this too it doesn't matter but that's just extra space that really we really don't need but regardless it shouldn't make too much of a difference so let's first create our map and this is going to be storing all the kpi pairs for our object so for the first object is going to be label second roller now let's create a output variable to store our result and let's just return that over here now we need to initialize our map so that it has an object with all the key value pairs where again key represents the string and value represents the count of each character now let's implement that so i'm going to make a for loop and we're going to irri through all the strings in array and we increment by one each time now i'm i want to push in an object to my map array so that's going to be map push and object so let's just console log our map and this should be a dot length let's comment this one out right now you can see that we have a array of objects and remember that you can we said that we can just skip this one so let's just start at index one and we have two objects for our label and our roller constraint now we need to be able to iterate through our string and then add in those key value pairs now to do that i'm just going to create another function and i'm going to call this map string and this is going to take two things it's going to take an index and a word now this is also going to be entering through the word that we're going to be given so for let i is equal to zero i is going to be less than word that length and we increment by one each time because we want to iterate through all the characters in our word now what we have to do is well we have to check does the object have the current character and if it does we want to increment the value by one if it doesn't we want to set it to one so i'm going to make a variable named char and this is going to represent the character current character and let's just well we can't actually cause unlock our character yet but let's just keep going actually i just put my causal log here so that we can look at it later and now we need to be able to check if our current object has the current character and if it doesn't we need to add it right we need to increment by one so in order to do that we need to access our map array and we need to pass in our index and our index is going to point to which object we should look at and then we have to check if the character is there what we'll do is we'll do map index character or zero plus one and now let's go back down and after we add in our objects what we need to do is we need to either do our characters and then map our string so we'll call map string over here and then we'll pass in two things well first thing is going to be index of our character right so that's going to be i minus one because we have two objects here and second one is going to be current word and as you can see we have our two objects so label and roller now why do we pass i minus one well we have to pass it i minus one because if you were to pass in just i you can see that we are getting an error and we are getting an error because our map has only two objects and when this increases to i is two there is no index two for our map so we have to subtract one over here and a index i is our current word so label and roller and now we're passing in our index of zero and our label for the first iteration so that calls this function takes index and a word and character is more than index i which we have over here so let's delete them now and what we're doing over here is well does our map at our given index so right now our index is zero have that character which for the first one is going to be l if it doesn't it's going to return zero and then add one if it does it's going to return that value and then add one so how does this statement evaluate well we have our value which is this right map index character if we don't have a value or if there's no key at all what we're going to do is we are going to return zero and then add one now let's say that we have two else for label right so when our label has a value this is going to evaluate to one so it's not going to return zero so this is again going to evaluate to one and we add one to that so that we set our value for l to two and we do that for all the rest of the characters in our object and if you want you can actually just iterate through the whole thing you can just make this zero and then just make this eye so you have bella label and roller but the reason i didn't do is because well i want to iterate through my first string in my array to check if all the other characters have each and individual character so that sounds confusing but this is just extra work that we are not going to use so let's just leave it here for now later we will delete it and see if that makes an impact so now i want to be able to irritate all the characters and remember that i'm going to use bella the first string in our array to check against other strings so let's use a four of look so cost let's do character of element or string at index zero and if i were to just console log my characters so console log character and you will see bella each character so b l a now i want to check if the rest of my elements in my array has that specific character so to do that i'm going to use a method called every so if map dot every so if every word has a character it's a word at character so if it does have it what i want to do is i want to decrement the count by one because i need to decrement it because i need to be able to account for duplicates so i need to decrement it otherwise i'm going to return null and you have to give a parenthesis in front if that evaluates to true what i'll do is i'm going to push my current character to my output and here you can see that we do have our result right but how did this work well you're eating through all the characters in our first string and we are checking we're running every method on our map and this only evaluates true if all the words have the current character and if it does it's going to decrement the count by one so that we can count for duplicates later and we don't want unwanted duplicate over here otherwise it's going to return null so if it doesn't have that character it's going to return now if not it's going to just decrement it and then just evaluate the true and then run this line where we add our current character to our output result now let's clear a few things up well we mentioned that we don't really need this first string object right count of the first word and the reason is because we're just using this loop and we're using the first string so element at index 0 to iterate through all the characters so that's console log character and we should get bella and if i were to just get rid of bella object we do that by subtracting by one here and then we start at index one we have only label and our roller and still we are able to iterate through our first string which is bella and still get the same result so that is a extra work that we don't need so that's why we took it out it doesn't really matter if you keep it's not much of a difference but still now let's delete that and check if this worked and you can see that we have co for our second result which looks good now let's go through our code one more time now first thing we did was declare a variable for map which is going to store the count of each characters as an object where key represents the character and values represent the count of each character we created an output variable for our result now we iterate through our array of strings and we start index one because we don't need a count of characters for our first string so we do that for all the rest of the strings in our array initialize an object so we push it in and then for that current word and index we push in index minus one because well our map starts at index zero and then it's going to have up to index one it's not going to have index two and you saw that if you were to just start at zero we would have a error so we pass in our index and our label our index is going to evaluate to i minus one which is going to be zero and we pass in our label so zero and label over here and we're iterating to all the characters made a variable for current character and if our object has a value it's going to evaluate to whatever that value is so this and add 1 to that and if it doesn't have that value this is going to evaluate to false and then we return zero and then add one to zero after that we are saving that value or overwriting the value we are overriding the previous value with the new one so at first this is going to be invalid it's false we don't have a value for it at all so this is going to evaluate to false not a number and we want to return 0 and we add 1 to that and we save it as one if it does have a value let's say two this is going to evaluate to two so we don't hit the rest of the statement so two plus one is going to be three equal we set the value equal to three now we go down here now we do that for all the strings in our array and after we're done we go down here we re do all the characters in the first string and we go to our map which is an array of objects and each object is going to be checked well does it have the current character if it does i want to decrement by one and then add my current character to my output variable if all the words have that character so if any one of the string doesn't have this current character it's going to evaluate the false and then it's going to go out and get the next character and then check again and again just one important thing is that after we check we decrement the count of the character by one because we want to be able to handle duplicates correctly and finally we return our output now let's implement our second solution and our circuit solution we're able to use a lot of array methods to implement this one so it's going to be more compact and if you're good with array methods i think this should be easier compared to the iterative approach now first thing what i want to do is i want to get my first string in my array so that's going to be input array at index 0 and what i want to do is i'm want to split this so that i can make it into an array and you can see that we have our array of the first character right and on that array i want to use a reduce method and our reduce method is going to take two things our output so our accumulator the current value which is going to represent the character let's now give an initial value of an empty array and let's just console log our character and you can see that it's printing bella which again is the first string now same as before i want to have an if statement to check if the current character is in all of my strings in my array so same as before we're going to use every for each element if it has the current string i want to return true so to do that let's use includes now what this is doing again it's running every method on all the characters in our array and if any one of them evaluates to false this whole thing is going to fail so it's not going to run the inner statement which we haven't implemented yet but just know that this is going to evaluate the true if all the characters have our current character otherwise it's going to evaluate to false so if the evaluation is true we want to obviously add that current character to our output so let's do output push our character and right now it's just returning undefined because we haven't returned our accumulator here yet so let's return our output so it should be good all right and now is the most important part so what we want to do is if it does evaluate the true you want to get rid of that current character from our string so for instance well does b exist in all the characters or all the strings no it's not right but how about e is here and e is here well if that happens i want to get rid of e here and override my original input array so it would be b l a b l and r o l r for the last one so to do that what we're going to use is we want to override our initial array or input array and we want to use a map to return a array a new array so for each word you want to replace our current character so word dot replace our character with an empty string now you can see that we have a result right but how did this actually work so let's just console log our input array and let's just console log in one more time up here what we have is our regular first initial input array bella label and roller now b is going to fail because it's not in rest of the strings so that's if segment evaluates to false now it's r e well e is in all the strings in our array so what we did was here we are getting our current word and replacing the current character which is e and we're replacing it with an empty string so that's why we get array of strings without any e's now we do that for rest of the characters and keep deleting characters that's common and all of the strings and when we're done we just return our output and we get our result so let's go over this just one more time just really quickly first thing we did was we splitted our first string bella so that we can iterate through them using reduce our output is first going to be an empty array and this is going to be what we are going to return and we have our current character which is the values and we get our values from this array but that's bella right and we check if all the words have the current character so char if all the words have it we want to add that word to our output array which is this and override our input array with the new array our new array isn't going to have the current character so it's going to remove the common character one at a time until we have no common characters so we do that over and over again and finally we turn our result and let's just uncomment this and you can see that this one worked well too if you guys find this helpful make sure you guys like and subscribe thanks
|
Find Common Characters
|
maximum-width-ramp
|
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters.
| null |
Array,Stack,Monotonic Stack
|
Medium
| null |
349 |
hey everyone today we'll be solving lead problem number 349 intersection of two arrays in this problem we are given two integer array nums one and nums two and we have to return the array which is intersection of these two and each element in the result must be unique and you may also return the result in any order okay it's a pretty simple problem that we are given two integer array let's say nums one and nums two these are two inte array and what we have to return is return another integer array which is having element which are intersection of these two arrays so what are the common elements if we check for two is a common element two is also common element three is also common element and we are but we are also given that we also have to include unique elements so to make it unique we have to include two only ones so 2A 3 is going to be my answer for this problem I hope the problem statement is clear to you and this question has been asked in many companies Amazon Apple Microsoft LinkedIn JP Morgan Google Etc so how we are going to approach this problem the first approach came to my mind is like why don't we just directly sort these two array and check in check from the starting maybe using two pointers what are the common elements then those common element I'm going to add in my uh answer if we directly do the dry run these two are the our array 1 2 1 3 let's say it is a and what is b 2 3 if I sort these two array it will become 1A 1 2A 2 and 3 2 comma 2 and 3 these two elements are these two arrays are sorted now I can directly iterate over these array using two pointers let's say this is I this is J 1 and two is not uh equal it means I have to increment I so I is coming here 1 and two is also not equal increment I two and two is common so these two common element I can add to my answer but here we have to consider this constant as well that all the elements in the answer should be unique to make all the answer all the elements unique what we can do is we can keep track of the previous element let's say the previous element I let's say if I have the previous element I can see whether the current IG are equal if they are equal but not equal to previous element only in that case I'm going to add it in my resultant array otherwise I will just skip it okay so this 2 and two has been added to my answer now I and J both are incremented and both are having value two but two is our previous value Val it means two has already been captured I'm just going to skip it if skip it I and J will reach to three these two element are equal also these two are not equal to the previous element it means these two will also be added to the result and we got to our answer so what did we do here what is the time and space complexity first of all A and B are given to us I sorted a sorted B let's say n is the length of a m is the length of B so time taken to sort this array sort these two arrays are n log n plus M logn plus uh n which is this iteration so that we can skip n log n plus M log M so this is the time complexity for this approach here we are utilizing sorting on this array and what is the space complexity is nothing space will be taken by the Sorting algorithm that's all or we are um requesting integer array as a resultant answer return an array so but we cannot say directly that what is the size of our array so if we are using in like list that will also be added to the space but uh you can skip that for now the time complexity is depending upon the Sorting of these two array but uh we can further uh reduce this time complexity if we are taking set or you can say hashing if we are taking just try to think in terms of H hashing using a set because what is our ultimate aim is to finding a set aim our ultimate aim is to finding a set that is having unique element which are common among A and B so let's say first of all I just check all the elements in the a I have 1 2 3 this is the set from a now we already know that these two these three element are the unique element from set a from uh you can say integer array a if I further iterate over B and C what are all the elements present in a that I can directly add to the B now if I'm iterating over B first element is two is present in a that I can get to know using this set and that I can get to know in order of one time and I'm iterating over this B in the order of M time you can say just uh processing every element once so two is present in this set it means two can be a part of my answer it means two is already present in both the array as we have already captured two we don't need to capture two again so we can directly remove two from the set next element is two is not present in this set ignore it next element is three is present in this set if three is present it means three is present in both the array include three also in the answer and we have got the answer what we did is from the first array we prepared a set that we can do is in order of end time and after that we are iterating over second array and checking whether that element is present in the first uh first array set or not the presence of the element in the set can be checked in order of one time and iteration of the second array is taking order of M time so ultimate ultimately the time complexity is going to be order of n + be order of n + be order of n + m which is better than the Sorting algorithm and also in the problem statement we have given that we can return the result in any order so the order does not matter if it is 2 or 3 or two so using set we can achieve our solution in a better time complexity so we are going to approach this one so this is the code for this approach where what I did is I took a set this set is going to have all the element from nums one so now this set is having 1 2 3 this is our set and B was my second array so now what I will do is I will iterate over my second array and I will see whether that element is present in my set or not if that element is present in my set I will just remove that element and add that element to my answer two is present in the array remove the element from set to add two in the answer and now three is present in it add and add three to my answer and remove three from the set this is my answer and here I'm just I have just taken list in the end I'm just converting list to the array because we are expecting integer array as the like resultant type okay now we have our solution resultant uh array we can return and the efficient time complexity is order of n + + + m that's all but here the space is also introduced because we are taking in an extra set here so this will contribute to our space and in the Sorting stuff sorting plus two pointer we were not introducing any extra space okay I hope the problem statement is clear to you thank you guys bye-bye
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.