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 |
---|---|---|---|---|---|---|---|---|
718 |
hey guys let's take a look at this seven one eight maximum length of repeated sub-array I've seen this problem before sub-array I've seen this problem before sub-array I've seen this problem before but I don't remember how it can I solve it I remember just something like dynamic programming okay next okay let's look at example one two three two one two three one four seven so the common longest common substring maximum is three so the first one is we have to do it in a brutal way I just use loop so the first we find like for one we find the leg start Queen one and then compare okay so for its I equals zero I smarter than a then I plus four net j equals 0 J smaller than B dots then so if they are the same we can continue right let k equal zero so Wow a I plus K equals b i+ k if they keep a I plus K equals b i+ k if they keep a I plus K equals b i+ k if they keep the same k plus equals one so okay let max equal zero so max equals max my max K so finally the return K max it's done well actually it's time limit exceeded USC to relock hmm oh sorry there's a typo here okay should be J no sorry BG and here is J yeah time to exit it so when the case for all zeros we just a 0 up about zero ba zero blubber but so it's actually a waste of time problem is that we compared to much like one and then compared to four but it makes them we're searching for two we also compared to 4 so this comparison is not necessary right yeah for three yeah three to two okay and we fruit compared to two again there's no need because to the common I just longest string start with three two it's already calculated to two will be carried by three this must be it could be done with dynamic programming let's look at the formula first let's define optimum IJ this is a result equals so light lights for this two array what does it mean it should be max optimum and i j 0 j is 2 n right what do you mean so n by here must be n to be three and wait to end with one an optimal end I J equals 1 equals 2 actually very simple equals 2 Optima end I minus 1 J minus 1 if a when AI equals B J or 0 that's the same they cannot be so we can do this from bottom up okay let's define that array matrix result this is map it's math working you array 8 min Matt you are a beat so this should be a matrix so for I cause still need I smaller than a tool in for a let j0j smaller than B that lend Jade puss-puss I think that if I equals zero matrix I J equals a hi equals BJ if they are the same then each one if not 0 for J it's the same or J equals 0 yeah that's right so for the other case matrix I J equals a I equals V J matrix I minus 1 J minus 1 yeah I already calculated so if not zero so and then we can at last quick turn matrix I a and then B and mother one on a goat it's not a constructor I'll ship hmm unexpected for unexpected this doesn't work how could these be possible neither I need to return okay can I set a pretty zero of them define what is this matrix rate 3 t minus 4 cannot set properly 0m define ah hi feel I don't remember what's the sine axis ah cannot see proverbs and what the heck is five empty Titans smarty or we see it's empty times four mm-hmm ah whew ah my bad why you three ah I see he came at my bad so matrix equals the new already hey that's them tricks for you for that's equal zero i smother that man matrix I of course new array but the answer is 0 we see ah you should return that max this is one three it's three zero two zero okay now we've got 3 1 3 this is 3 please more because we are the same so I plus 1 that's matrix hi J then minus 1 it's the same cannot read probably symbol not number ah ok its roots reduce console.log a matrix and matrix hate of console.log a matrix and matrix hate of console.log a matrix and matrix hate of length reduce the current result its serial results returned ah math.max it's serial results returned ah math.max it's serial results returned ah math.max it's okay one is not symmetric B is the same so this one is the same yeah I think there's a max that's my x equals zero if matrix hi James bigger than max who's this one so we just returned max oh yay yeah we passed it so it's much faster now the key for this solution is that we cannot just say the last one because we last number because we have to check if they are sub-array they must be consecutive are sub-array they must be consecutive are sub-array they must be consecutive numbers so we use a matrix a 2d array to store the common sub array which is which ends at the specific indexes indices and with the same and we will update the max at the same time and together with this with also just to get the string itself I'm not sure whether it's a other solution this is a dynamic programming yeah it's accepted its whoo amen yeah space yeah we use that another matrix it's a baby risk uses for honeymoons are equal mean yeah space complexity what is this fakes complicity this is a pool forcible force perforce before space complexity so n I don't think there is space time use oh one right this could be garbage TC these SARS what is B starts our anxieties are typical cases most of the time he is not equal to BJ we could instead keep a hashmap up he starts oh ah yeah such as PJ calls a I and we only loop through those in r.j. dope yeah so P star should be complexity empty one but the ends should be just in number I see last solution he says the spider was really happy mewling has to store hashes in our set structure Wow what so are in your Dan so the previous one is okay om n mean om yeah this is me yeah for binary search with Nate naive check wow this is interesting if there is a K something coming to a B and there's an end J as well let's check really answer to question is there a sub array with length comment to a and B this is a function with a range that must take the form true false without the least one three combine a research on this function understand focusing on the binary search are Avery's that check edge I will always be false what started with which I mean clearly cheap icefalls now we perform a check in the midpoint am i low and high where it is possible the note if there is a que substituent come on to a B then there is a nen J mother KF b s as well yeah let's check the answer to the question is there supper with glance coming to anime the question was yes it's false yeah of course focusing on the binary search are you very nice check high will be always force while we start with high mean Carrie chick I suppose now we perform our check in the middle point where it is possible then know what it is ask for the check itself we can a vector a I equal B J okay using set structures what I don't know what I don't understand so if it eats this checkland so seeing equals saber topple any top of a I what is I for I J it means that uh-huh I see if I said it says if uh-huh I see if I said it says if uh-huh I see if I said it says if there's a K there must be a K minus one so we can just try it try to approach this K by just a binary search and for each check we just to check order we just we just check all the tuples means the possible sub erase yeah wow this is cool but the comparison maybe takes a lot of time so time complexity is M plus n times M log this is the research time a man lines of a B the log factor comes from perish the complex 7 I check games name's Lisa there will be M plus n yeah and against will be me it's hmm so for the dynamic programming the space updates and n and x is also MN my research with rolling hash I don't know what is going on so my said there's only one space is enough max I use max enough connoisseur in okay so max then only depends on accident so only you need to keep smacks nen which is one element you know below we use Max's ending to keep max and Traverse to makes tricks diagonal diagonally there's not someone shown your video while this guy's accent is so sad mm-hmm this guy's accent is so sad mm-hmm this guy's accent is so sad mm-hmm well anyway we I think dynamic programming approach is best we have to understand so that's all for this problem see you next time
|
Maximum Length of Repeated Subarray
|
maximum-length-of-repeated-subarray
|
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100`
|
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
|
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
|
Medium
|
209,2051
|
304 |
hello everyone welcome to kodus camp so today we are the 12th day of may lead code challenge and the problem we are going to cover is range sum query 2d immutable so the input given here is a two dimensional matrix and we have to implement two functions first one is num matrix where we have to initialize our data structure here and the second method is some region and which is used to calculate the sum from particular sub matrix and return the value so let's understand this problem with an example so here is our given input matrix and the coordinates of the range we have to calculate the sum in our second method some region so in this example we need to consider the sum of this particular sub matrix and it sums up to 11 which is nothing but 6 plus 3 plus 2 plus 0 so now if we are approaching it in brute force way then we have to iterate the given number of rows and columns and add each value and return the result and that is going to take big o of m into n time complexity where m and n are the number of rows and columns given in the sub matrix so in this case our second method some region is going to be the often called method so every time you want to calculate the sum of a sub matrix it is going to take big o of m cross n time for each operation or each time you call the function and that is going to take too much time and which result in time limit exceeded so how are we going to approach this in an optimal way so we are going to use the same logic we have used in one of our previous videos that is the sub matrix sum equals to target so consider our array is not a 2d and it is 1d in this case we are going to calculate the prefix sum of a given array and it looks something like this for this given example prefix sum is nothing but sum of a range that is starting from zero index and till that point so three plus one is four and at index two the sum will be from starting from zeroth index till the index do and at index three the sum will be from starting from 0th index and index 3 same way till it calculates the sum to the last index so what is the advantage of having this prefix sum for example if you want to calculate the sum from the range 2 to 1 that is from index 2 to index 4 then in that case it is sums up to 2 plus 4 plus 1 equal to 7 so by using prefix sum we don't have to iterate through that range and calculate instead we can easily calculate by the sum but that particular index subtracted by the range previous index that is we want the sum from this index to this index so we are going to take this sum and subtract it from the previous sum that is previous sum till that index so that will get that value easily so we are going to apply the same logic to our 2d array to find our sum so here is a given example input array we are going to calculate the prefix sum at each row of this given matrix and the sum at each row is going to look like this that is we simply added the sum at each row considering it as a 1d array so in this case now we have our sum ready how are we going to calculate the sum of a particular range for example we are going to calculate this particular sub matrices sum so to calculate we are going to iterate through the given range for example row by row so by first row we are going to calculate the sum in that row alone that is the sum of these two cells are going to be value at this index subtracted by the previous sum or some till the previous cell that is going to give us 9 and then we are going to move to our next row and then subtract it in the same way that is 3 minus 1 which is going to now overall the sum of all the rows hydrated gonna give us the sum of that particular sub matrix so we are going to apply this logic to find our result so in our first method to initialize our data structure we are directly going to have a dp array which is going to store the prefix sum at each row instead of storing the actual matrix so this is going to take big o of n time complexity as we are going to iterate the given number of rows and columns and when we call our second method it is gonna iterate through only the rows or the number of rows given in the sum region parameter and written as a result so that is gonna take big o of young time which is nothing but the number of rows given so as many times we gonna call it is gonna take big of m time for each operation so let's go to code now before getting into the most optimal solution so as i said i'm gonna declare a two-dimensional iitp to store our values so inside my num matrix i am checking the basic conditions so i'm gonna iterate my given rows and columns and calculate prefix sum at each row so yes we have iterated our rows and columns and at each row comma column we have added the current value plus the previous value in the previous column so now our matrix is ready with its prefix sums and in our second method let us initialize the variable sum equal to 0 and we are going to iterate the given number of rows that is the row 1 to row 2 and at each row we are going to calculate the sum and finally return some other result so yes coding part is done so let's run and try yes let's submit yes it is accepted so how do we do it in an even more optimal way so in this solution we have seen it is taking big o of m time complexity as it is gonna iterate every row in the given matrix and we did actually a caching technique where we have stored the pre-computed where we have stored the pre-computed where we have stored the pre-computed values for our use so how do we do this caching in a even more better way so that we can take only big o of one that is constant time to access the values so here is a given matrix so this time instead of calculating prefix sum at each row we are going to calculate the sum to the overall range that is we are going to calculate sub matrix wise and the sum looks something like this so this is nothing but for example the sum at this particular cell let's say 14 is nothing but from 0 comma 0 till that particular cell 6 the overall sum for this particular sub matrix will be taken from here same way if you consider 26 which is nothing but from 0 comma 0 the overall matrix sum will be present here so this way we are going to calculate and make a matrix ready in our first method that is num matrix itself so how do we do it for each cell its sum will be at its previous column and its previous row that is for 14 it is 8 plus 3 plus the value at the current cell which is 6 minus its diagonal cell 3 which actually gives us 14. so how do we say that because here 8 is nothing but the sum from 0 comma 0 till this particular column sorry row same with 3 here is nothing but from 0 comma 0 till this particular column so here the overall sum will be the sum till this row until this column plus current value but why are we subtracting minus 3 because while calculating from 0 comma 0 to that particular column we are considering 0 comma 0 that is 3 same way by while calculating column wise we are again considering three twice two times like row wise as well as column wise we are considering this common cell twice so in that case we have to consider that sum only once so we are subtracting it from the overall sum once hope we are understanding this concept and by using this concept we are making this array ready in our num matrix method so what are we going to do in our sum region method so once we pre-computed pre-computed pre-computed the cumulative sum of a given matrix we are going to calculate this particular matrices sum so how do we do it so as i said each cell here represent the overall range of sum from 0 comma 0 till that particular row and column so in this case we have to subtract this particular sub matrix alone from that range to do that we are going to take away the sum of this row and this column from this overall sum so which is nothing but from 21 which is the overall sum we are going to care negotiate or subtract the previous rows how many ever rose from zero comma zero till that range so that is going to be four because we have calculated the overall sum till here till that range also we are going to subtract how many ever columns previous to that particular range so in that case from 0 till that range the sum was in the previous cell which is 9. so why do we add 3 the same technique we have seen in our previous step that is this 3 has been considered in both row wise as well as column wise that is the sum till that range so we are adding that because since it is considered twice we are subtracting it in this range itself we have to add it once and calculate the sum that is going to give us the sum of that particular range so what is the advantage of using this method though it is pretty difficult from the previous method because while calculating this cumulative sum again it is going to take one time of big o of m cross n and while retrieving the value by using this method of calculation it is only going to take big o of one constant time and how many ever times this function is gonna be called it is gonna take only constant time and that reduces a lot of time so hope you are understanding the solution let's go to the coding part so i'm not going to change much of my code so instead i'm going to change only two lines here in my dp instead of dp of r comma c plus 1 i'm going to calculate row plus 1 and column plus 1 is equal to tp of previous row or previous cell in row wise plus previous cell column wise and the current cells value minus the common cell which we have considered twice so that's it this will have the cumulative sum instead of the prefix sum so in this case here in our sum region we don't have to really compute the sum at each row but simply i'm going to return dp off so this is nothing but the oral cumulative sum at that particular cell that is 2 comma 2 or the row 2 comma column 2 minus we have to delete the sums in the previous rows so in this case dp of row 1 that is still before that range and column 2 and we have to subtract the columns in front of that range so to do that tp of and we have to add the common sum which we have in which we have included in both the subtractions so yes that's it we simply gonna compute the value and return it in constant time so let's run and try so yes let's submit yes a solution is accepted and runs in 10 milliseconds so thanks for watching the video hope you enjoyed this walkthrough and if you like the video hit like subscribe and let me know in comments thank you
|
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
|
680 |
okay let's solve today's second question valley pollen john - given an empty valley pollen john - given an empty valley pollen john - given an empty string s you may delete at most on one character see whether you can make it a partner or not palindrome is a sequence of characters which reads the cell backwards and forwards so it's the same when we read for a left or right or we read for right to left the ABA here is example that a string s by self palindrome without adding any kind of modification deletion the second one we have ABC a it's a we can delete one character to make it volunteer enjoy the explaining says that you can delete the character C so if we delete C all we have remain is ABA which is of course a poly a valid palindrome but we can also delete B as well if we delete B we get a CA so I'm gonna put a link to the valley Pauline Jerome one question the strategy to check whether a string is a vollendroff palindrome or not it's just the two have two pointers one from the left to the right and the other one from right to left and we're just checking the correspondent letters one at a time to see whether they are the same or not if we ever find this match then we can return false otherwise when we the two points and meet up meet in the middle and then the whole thing must be a palindrome so for this particular question it's not much different because all we can do is to when we see this match a mismatch all we can do is the delete of one character so we can either delete the left on one or we can delete the right one and as the example here shows it's all possible we can we delete B or we delici the remainder thing is we're gonna have a result that's valid a palindrome so we have to check both cases so that just summarizes it basically describes the procedure we just do the palindrome checking as usual up two pointers moving towards the middle when we see a non match case we try remove the left one and also we try to remove the right one if either one of those succeeded succeed means that the anything in between after the deletion is still palindrome then we can achieve this goal by deleting one of the characters so that's the strategy of Sonya's problem let me move myself over and start coding this question so we have a left pointer starts from the left and moves the location and the right pointer that's the start with the rightmost location while this to have a Maddy in the middle what we should do is check whether this to correspondent character the same along but we are not really immediately returned forced yet because we have to do a deletion and then checking the middle part after that deletion we're gonna have a helper function to do this remainder checking if this if that's a Sam then we just advanced the pointers and when we when the two things meet in the middle we are pretty sure that it must be the case with the same with example one that the string yourself without any deletion is a valid palindrome so just to save a little bit of code we need define another function this polygon but the two pointers waiting specially just copying this and so basically this it's the same logic of checking things just a rapid ad in the function if we in the manage checking logic if we see the force at the first mismatch we could try to escape the left one left a character or we could skip the right part if either way we can have the middle part to be valid the palindrome then the whole thing can be a palindrome so that's the code for this question let me check it seems okay to me so let's try to run it yeah it works yeah it's a again I promise relatively slow and use more memory but I don't see any reason it's not using constant space so yeah anyway that's the solution to this question yeah
|
Valid Palindrome II
|
valid-palindrome-ii
|
Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "abc "
**Output:** false
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Two Pointers,String,Greedy
|
Easy
|
125,1178
|
1,814 |
hi everyone so welcome back to a new video today's lead code daily challenges count nice pairs in an array this is a medium level question in this question we have been given an array nums which will contain non- negative integers and will contain non- negative integers and will contain non- negative integers and we have to Define an Define a function called reverse of X which will be reversing the non- negative integer X reversing the non- negative integer X reversing the non- negative integer X now we have been asked to find if a pair of indices is nice or not a pair of indices is nice only if it satisfies these two conditions one is that I will be less than J and J will be less than J will go till nums of length and I will start from the zero index of the array now the other condition we have is that nums of I plus reverse of nums of J will be equals to nums of J plus reverse of nums of I we have also been told that the total number of nice pairs can be very large so we have to return the modulo of it let's see with an example what we have to do here so here we have been given an uh a nums array called which has numbers 42 11 1 97 so what we have to check here is we have to check that if 42 plus reverse of 11 will be equals to reverse of 42 + 11 if it is true then we will of 42 + 11 if it is true then we will of 42 + 11 if it is true then we will count it as one pair if it is not we will just move on so also we have been given the constant as that the length of the array will be less than or equals to 10^ 5 and will be less than or equals to 10^ 5 and will be less than or equals to 10^ 5 and it will start from one the nums length will not will never be zero and the value contained in nums will be starting from zero and will VAR till 10^ starting from zero and will VAR till 10^ starting from zero and will VAR till 10^ 9 so let's see the approach to this question one approach what we will see is first one is a Brute Force approach in this we will be using the basic for loops and the for Loops if we are using the iterator I then it will start from zero and will continue till nus one less than n minus one and J will start from I + 1 and will continue till less than n + 1 and will continue till less than n + 1 and will continue till less than n here we will check then the condition which we were provided that if nums of I plus reverse of nums of J is equals to nums reverse of nums of I plus nums of J if it is so we will increase the value by one of count so count will in increase by one and out of the loop we will be returning count now we have to see the way we have to Define reverse function right so reverse of a number can be found out in two ways one is two- pointer ways one is two- pointer ways one is two- pointer approach where we will convert the integer to string the other approach will be treating the number as string as integer only but we will use a loop and we will check if nums the value number is greater than zero or not and we will extract each digit and form a reverse number we will form a reverse number so these are the two ways to uh to calculate the reverse of for number now we have the time complexity in Brute Force as o of n² so according to this question this will uh give us time limit exceeded in order to get a proper approach we will see the optimized version now so let's move on to the optimized version so the first step which we have to follow here is we will form or Define a reverse function which will be the same as the previous one now what we have to do is this reverse function we will be calling each time to check the difference between the number and its reverse of number okay so we have to find the difference between them and we will store it in a hashmap store the difference in hashmap or we can say dictionary after this now we have calculated the reverse uh difference between all of them so the third step what we have to do here is we will count the total number of nice pairs so how we have to do is we will count all the occurrences of the difference which count of count the count all the occurrences of the difference which is occurring in the of the difference which is in the value of hashmap now in a hashmap we have a key and the key has a value so we have to check for same values of differences and to calculate the number of OCC es what we will do is we will take count which is the value here count into count -1 by 2 Okay so this will get us the -1 by 2 Okay so this will get us the -1 by 2 Okay so this will get us the number of occurrences we will add it to a sum value so if we have a uh integer value as sum so what we have to do is sum plus is equals to count this is if we are keeping it as C so C and we will take the mod value of it at the end of the function we will return sum so this is how we will get the total number of occurrences of nice pairs using optimized version so let's see the code now and whatever little doubts were in the explanation will be cleared from that let's see the code now so we will Define mod here we saw that first we had to define a reverse uh a function to reverse the value so we will Define a reverse function reverse of X while X is greater than zero to store the reverse value I'm defining an integer so now we will be storing the remainder of x in D and what we have to do here is reverse is equals to reverse ulti by 10+ D now we have to do is X = x / 10 and we D now we have to do is X = x / 10 and we D now we have to do is X = x / 10 and we will return this reverse value so we will return reverse from here now what we have to do is we have to count the occurrence of count the number of reverse difference of reverses right so we will declare a hash map or dictionary so in that we will store the difference of number with its reverse difference is equals to num minus reverse of num and we will store it in the hashmap we will store the difference in the hashmap so count map of difference is equals to count map get difference comma 0 + 1 now we have already stored the difference value now we have to count the nice pairs so count equal Z for I in count map do values nice pairs are count is plus is equals to we will write it clearly count is equals to count plus I * by i - 1 divide by 2 and we will mod I * by i - 1 divide by 2 and we will mod I * by i - 1 divide by 2 and we will mod find the module of it and now we will return the count so let's run it we will try to submit the solution now so it has been accepted that's it for today guys thank you for watching the video I will be adding the uh code in my GitHub and the link will be provided in the description you can access the code from there if you like the video please subscribe to the channel for further lead code daily challenges
|
Count Nice Pairs in an Array
|
jump-game-vi
|
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])`
Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[42,11,1,97\]
**Output:** 2
**Explanation:** The two pairs are:
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
**Example 2:**
**Input:** nums = \[13,10,35,24,76\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
|
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Medium
|
239,2001
|
19 |
hi guys welcome to the channel so today's question is remove an eighth note from the end of the list given a linked list remove the eighth note from the end of the list and we need to return its head so suppose we again with the linked list and our n is two so we need to remove four from the list and we need to return our list like this so let's see how we can do this so we will take two pointers fast and slow both will point to head in the starting we will increase our fast by n steps once our fauces and step ahead of slow we will increase our both fast and slow by one step once our fast will reach to the end of the list we will points our slow next to the slow next or next so let's take an example let me show what I'm saying so this is our linked list and our n is three so in the setting fast and slow both will point to head we will increase our fast by n step and after three step our fossil went to four now we will increase our Fast and Slow by one step till the time fast does not reach to the end of the list software once F fast will be here and Silla will be here so once our fast reaches to the end of the list we will points our slow next to next or next so in this way we will skip three and our list will become like this so let's write the code for this because of some corporate consents I'm not using late code for writing the code but I will provide you the code in the description below and if you paste this code on the lead code it will walk so let's write the code so first of all let's make two pointers fast and slow both will points to add in the starting and we will increase our fast by n step so faster will be fast short next once our fastest and step ahead of slope we will increase our fast and slow one by one but if our fast is none we will simply return head dot max because if our fast is none that means n is equal to the length of the linked list which means we need to delete our first element so we will simply return headed next why for short necks is not none we will increase our fast and slow by oneself you and at the end we will point our slow dude next to slow dude next or next and we will return our head so this was the code you can try the code in the lead code and it will definitely gonna work thank you so much for watching the video if you liked the video please give it a thumbs up and please don't forget to subscribe thank you so much
|
Remove Nth Node From End of List
|
remove-nth-node-from-end-of-list
|
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`
**Follow up:** Could you do this in one pass?
|
Maintain two pointers and update one with a delay of n steps.
|
Linked List,Two Pointers
|
Medium
|
528,1618,2216
|
718 |
in this video we're going to take a look at a legal problem called maximal length of repeated sub array so given two integer arrays nums 1 and nums 2 return the maximum length of a sub array that appears in both arrays so you can see here we have an example one so we have nums one which is this array right here and number two is this array right here so the output is three because you can see the repeated sub array with maximum length is three two one so we have three to one here and we also have three two one right here right so in this case the maximum length of concept consecutive repeated subarray is basically three right and let's say we have another example like this you can see we have all the elements right we can have duplicate elements right all the elements are the same so in this case the longest uh consecutive length of repeated sub array is basically just going to be five right we have five zeros here and five zeros here so in this case the constraints is that we're guaranteed that elements are always going to be positive and the length of the array is between one to one thousand so in this case how can we able to solve this problem let's say we have a example like the first one right here so let's say we have one two three two one and then we have three two one four seven right so let's say we have those two arrays so this is n1 right and this is n2 so we have num's one number two okay and then in this case you can see here um basically what we can do is that we can solve this problem using a blue force approach by simply saying that this is the pointer right our current pointer is pointing at the first element and two we're trying to find three in one right in this case we have one which is right here and what we can do is that we can basically slide our window uh one to the right one by one try to figure out what's the maximum length uh consecutive repeated sub array right so you can see here we have a three here we have a two here right on both side we have a one and then the next pointer is out of bound so in this case the maximum that we can find is three right so you can see the maximum that we can find for this position is three so in this case maybe we can keep track of that using a variable right and then we can move on to the next element in this case is two but you notice that there are two twos in and one so maybe we can start here okay then that's elements of three and then that's elements one so far we've seen the longest is one right for this value position right here and then we try was two okay so those two are the same and then one right so we move one to the right so they're all the same and then we move one to the right so you can see here uh we basically go out about right so you can see here this is it right we found two is still smaller than three so therefore you can see we're getting um you know we're getting three so far right and then you can see we move on to this element which you can see here which is one there are two ones right so we start with one and that's elements two this element is four they don't equal each other so what we're going to do is we're going to choose another one right so far we have one the longest for this position is one so this one right here is also going to be one right so you can see here um if we were to solve this problem using this kind of approach right worst case scenario all the elements are the same in this case we have to go with each and every single position right so this was this zero and so on and for each of those position you we also have the slider pointers across to figure out what's the maximum life of you know repeated sub array so in this case you can see if we were to solve this problem using this kind of approach right in this case let's say we have you know it's going to time complexity it's going to be big o of m and one right the size of n1 times the size of n2 right because for each and every single element in n2 we find that element in one and then what we also have to do is we have to slide our pointer across the uh both array right so for example like this three right here in this case we have to slide our pointer across both array in this case it's going to be the minimum right the min out of n1 or n2 right so you can see here the time complexity is n1 times n2 times the minimum length between n1 or n2 so now you know like what's the worst case right so now we know the worst case is basically going to be like this right and one times n2 times the minimum out of those two right so how can people to you know optimize the time complexity right so in this case you can see here we have a lot of duplicate computation because you can see here when we are visiting three right we want to know what's the maximum length of the repeated sub array at this position right that's what we want to get at this position right so in this case you can see we slide our window or slide our wind pointers across the array right so we have two and then we have the one but you can see here we already know what's the maximum length of repeated sub-array at this position of repeated sub-array at this position of repeated sub-array at this position because in this case you can see it's already right at this position it's already two because we already visited one right one has one longest length of repeated sub array at this point two is has two right so in this case you can see we already have uh computed for two right for the remaining sub array already so in this case why do we need to compute that again right so in this case uh what we have to do instead is basically what we have to do is we just have to calculate it once and then be able to cache this result uh using like some kind of 2d array just similar to what we did in the longest common subsequence right and then basically we're comparing so treat is just like a subsequence right so subsequently we're basically comparing this subsequence with this right oh they're the same let's try let's check with the remaining right if they're not the same like for example in this case like for example this one right if they're not the same right we're maybe trying with this sub sequence right or maybe if we can also try with this subsequence comparing with this subsequence right we're basically trying with all the options right but the thing is for this question is that we're not dealing with subsequence we're dealing with subarray right but let's do a refreshment of what is longest common subsequence real quick so i find this question to be very similar to the longest common subsequence with some slight variation of change but is very similar if you haven't checked out my other video called longest common subsequence i highly recommend to check out that video first before this one so what's the difference between the longest common subsequence approach compared to the current problem solutions approach so in this case i'm going to show you with this example right here so let's say we have two arrays right we have zero one and we have one zero one okay so you can see here we have our db table and let's say we're gonna solve this problem using the let's say we're trying to find the longest commons uh or longest common uh consecutive sub array right using the approach that we did in the longest common subsequence in this case for the top down approach this is what we're doing right first what we're gonna do is as you can see here if i start to run you can see first what we're trying to see is that we know those two elements they don't equal each other right so one they do equal each other so we do is we check the remaining array right basically you can see here we're basically trying to see what's the longest uh common uh you know common subsequence right in this case the longest common subsequence for the remaining array which is from index 0 to index 3 right so you can see that those two elements right here they don't equal each other so what do we do for longest common subsequence in this case what we do is we basically do a dfs uh to compare this longest come or in this case this subsequence with this subsequence right here right you can see here 0 1 with 1 0 right so in this case we're gonna we know that those two doesn't equal each other so in this case we know also not know that those two doesn't equal each other right we can go with different path you can see this is our dfs right and then we know that those two equal each other so zero right zero in this position zero with one zero is one right so we know that those two equal each other so we have one so far and then you can see this is basically how we find this the longest subsequence right basically to find the longest subsequence what we're basically trying to do here is we're trying to figure out what's the longest common subsequence that we have seen so far at this current position right that we have seen so far at this current position not the consecutive so let me just continue to play this so you get an idea right so you can see we're basically doing the dfs once we hit the base case it will return back our answer right and then we continue to update our branch and at the end you can see we're getting three but the result for this example should be two why because you can see zero one is right here right you can see inside this two array the only two common things that they have is zero and one right those zero one and this zero one they're the same and as well as their so there is the same uh common subarray right or you can say this zero one with this zero one right here right so they're the same so in this case the result should be two but the thing is we're getting three because you can see here at this one those two ones right if we were to revert back you can see this one right here is one right those two ones are equal to each other so what we're doing is we're basically trying to see uh you know what's the longest common sub sequence right what's the longest common subsequence for the remaining subsequence right from index zero to index three right so in this case you can see we have zero one and this is zero one right here so that's why at this position the longest common subsequence at this position right is two so in this case um to solve this problem right to figure out the longest or the maximum length of the common subarray right which is have to be consecutive so what we have to do instead is basically we have to figure out what's the for each and every single cell that we compute in our db table right we want to figure out what's the longest common sub array at the current position now what we have seen so far right so let me show you an example with a simpler example right here so you can see that one and two they don't equal each other right so in this case what's the longest common uh sub array common sub array at this position in this case zero right it's not what we have seen so far is what we have now so and then here in this case one they equal to each other so what we do is we check the remaining right so it's going to be one plus the remaining which is to an empty string in this case is zero right so at this position it's just one here what's gonna happen is two and one they don't equal each other so at this position it's gonna be two we don't worry about if it's one with this one right here or comparing if we don't worry about if it's this sub array we're comparing with this sub array or if it's this sub array comparing with this right or empty in this case we're not we don't care about that because we care about if the current position they don't equal each other then there's there uh in this case at this position uh the maximum length of common sub rate is none right so at this position you can see here 2 till 2 is equal to each other so in this case it's going to be 1 plus the remaining which is 0 right remaining is 0. so in this case it's just going to be 1. here is going to be 2 and 1 so in this case they don't equal each other so right away it's gonna be zero here they do equal each other so it's gonna be what it's gonna be two right two and two they do equal each other so it's what we have remaining in this case is just one right we know that at the remaining in this case is one right because you can see here one and one right in this case if we're comparing those two sub array we have one two and one two they're equal to each other right so in this case what we have is two right and we also have a variable called max to keep track of the maximum length that we have seen so far we have seen ones right but then we also have two right two is also larger than one so we replace max with two right so in this case this is what we're returning the maximum length of common sub-array so maximum length uh sub-array uh sub-array uh sub-array right sub-array is always consecutive so right sub-array is always consecutive so right sub-array is always consecutive so in this case the length the max length of uh max length of sub array in this case is basically two right so then we continue so we have two and one two one they don't equal each other so we have continue one they do equal each other so what's gonna happen is we're just going to have one plus what we have remaining right what we have remaining is two and one two they equal each other we already compute that as one so we take that value one plus one is two right and at this position you can see one and two they don't equal each other so right away we just put two because the maximum length sub rate at this current position is zero right because one and two doesn't equal each other there's no way we can find the max or we can find the max length of sub array so it's gonna be zero so what we basically see is that you can see we basically uh compute the table right and then the max length sub array is basically just gonna be two and that's what we're returning at the end we can see here this is our code right so we basically create a 2d cache array and then we have a max variable to keep track of the maximum life right the maximum length of repeated uh subarray right so you can see here we basically iterate each and every single row right for each and every single column we get the current element right for those two elements we check to see if they're the same if they are the same now what we do is we basically check the remaining uh subarray to see if they're the same or what's the longest right if i want to figure out what's the longest or the mac what's the maximum length or in this case yeah the maximum length of the current position right the maximum length will repeat the subarray for the current position i need to know the remaining elements plus the current element because the current element are the same right this will give us the maximum length right of the repeated elements at the current position and what we do is that we basically compare that with the max value whoever has the max value will be the new max value for this variable and at the end we'll basically returning the max value right so you can see this is how we solve the problem so this will reduce the time complexity to uh simply n times m right or nums n1 times n2 right so this is basically how we solve the problem so there you have it thank you for watching
|
Maximum Length of Repeated Subarray
|
maximum-length-of-repeated-subarray
|
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100`
|
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
|
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
|
Medium
|
209,2051
|
51 |
hello folks welcome back to the channel it's been hope you all are doing great today we are going to discuss a new problem called NQ uh this is one of the hardest problem in cleaning code so let's dive into the problem first of all what is Q do you know tune moves in the chessboard basically you have queue it can move eight directions up down top bottom and four diagram directions getting the 71 so just consider n equal to 1 is actually showing one into one ball if n equal to 1 the chess board we can easily Place Q over here so answer equal to true because we can place the one tune without electronic each other then n equal to what you think can possible to place to cure in AHS Port no then if n equal to 3 is possible to place 3 Q in three cross street board so we can place three q and three cross three ball then if n equal to four let's find out so what is an answer of this case yes we can place four queue in t4244 so next n equal to 5 you can place 5 unit 5 cross 5 volt let's find out here in this picture we are placing the first queue in the first row and second queue in the second row 12 the fifth queue in the fifth row but the columns are different and none of the cone can threaten each other so what is the answer of this case yes we can place a 5 cube in the 5 into 5 plus 4 then n equal to 6 is it possible to make 6 Q can place in a 16 to 664 yes we can place so do you guys notice that we can also Place Q in a different combination for in two different combinations 4 n equal to 5 we can place Unit 10 different combination for n equal to 6 we can place unit four different combination and so on now it may sound easy right but as now n getting larger the problem quickly becomes very difficult now you can see this picture say largest board if I want to place this n number of Q here it's very difficult to find so what to do so let's solve the problem here in lead code the question is the nqn muscles in the problems of placing any turns on an N cross and chasper such that no 2q attack each other given an integer n written all distant solution to the n q and puzzles you may return the answer in any Order each solution contains at Instinct for configuration of the M Keynes placement where q and Dot both indicate a tune and an empty space respectively so there is a 2d array that contain q and dots the Q represent the tune and Dot drops the empty spaces in that Matrix so how do we solve this problem the answer lies using a technique called band tracking backtracking is a general algorithmic technique that tries of different solution and retracts when it's fine the current solution is not feasible to know more about the backtracking I am giving a meeting Link in the description box to check out my friends let's know how we can use the backtrack to solve the engine problem first let's start with the core abuse Java for this example but the algorithm can be implemented in any programming language so please start by initializing an empty list to store the solution and increasing an N into n chessboard with a DOT MD scores and Q representator units list of latest integer result equal to no or at least then string off array equal to no string of array length of n for I equal to 0 and less than n i plus 4J equal to 0 J less than n J plus border Phi J equal to dot initially we are considering empty space for all our board now we are write the main function to solve the N given problem before we are initialize the board and we are now passing this board and the result to solve the angle problem to solve the angular problem using backtracking the function takes the parameter empty board and zeroaster row index and the list to store the result now we want to know how we can implement the backtracking here consider n equal to 4 so 4 cross 4 both so first row of the board we can place the Q in here or here so there are n options similarly for each rows we can place each row we can have n options so we can see this picture for trying to solve this using back tracking each row will iterate through backtracking so there is n equal to 4 there is four option to place the queue in each row so considering that the each row can be divided into four sub part like this and again it's divided into Force upward so this continue as will be the row equal to row length so we can see this picture this is the full flash figure of the backtracking working here consider n equal to four point four cross board so the first row of the board we can place the queue here over here so just observe this and we can get some observation the first observation won't tune in each row and the second one is one cune in each column so we can place one Q in each row and column we can either place a cube Raw by row or column by column if any point of time be blocked then to backtrack so here we are iterating the row and doing backtracking for getting successful backtrack we need an additional function for checking the position is same for Q if it is Sage the save function give the feedback as per we are actually placing the Q fifth place queue and do backtrack then to remember that whenever we block we want to go back and so we need to change the tune and make the place as before so we are hydrating in the board with respect to column there is a four option right column so what length is e safe we are initializing the function is safe and we are leaving the values of board row and column is true then there is no returning Tunes so we can easily place the keyword of that particular place if then we are again we are doing backtracking here and here row plus one board comma raw plus one result after back tracking if there is have any block or have any not possible to price and queue then yeah backtracking then we want to change the position as before so we are giving dot here now what about the base case whenever we recursively hydrate all the row on all the columns then we need to add the answer in the list to under eternity so this question the answer should print us the list of things so in this case actually if the row equal to board length then we are opening the if Loop and we are now visualizing the string list for storing the result then we are nitrating the ball if we want to add the answer as a string in each row the in the list we need to a immutable string so we use a string Builder now for each iteration and again we are iterating the board of J we are appending the answer and after closing the password Loop we are adding that the board list then we are under that bond list is that simple next we need a function to check if the N can placed in a given position without being threatened by any other Tunes so we will call the function essay in e-safe we have the answer we have the in e-safe we have the answer we have the in e-safe we have the answer we have the function string board and into row and in column and we are checking in the column each column and upper left diagram and upper right diagonal for one to check the column we are just iterating to zero to row length and if the board of I comma column equal to Q then it returns false so you want to check the upper left diagonal so equal to Raw minus 1 column minus 1 J equal to column minus 1 and I less than equal to zero and J less than or equal to 0 I minus J minus because it's a we are actually one to the upper left diagram positions so we are doing like this then if the board of I is equal to q and we are written false also we are sharing the upper right diagonal so the raw equal to minus rho minus 1 J equal to column plus one I will equal to 0 and J less than Board of length and I minus J plus Board of I is equal to Q root and false and then after this all condition is not failing then we are going to return true the endgame function is where the magic happens we take a board and a column index as parameter if the column inters is equal to n it means we are successfully placed on Queue on the board so we add the word to the solution list which means a result otherwise we iterate over the each row and check which is saved to play secure in that position if it is pro we Mark that position and recursively call in given function with the updated board and you call the index plus one if the recursive call return false be backtracked by making that position on the board as zero and move on the next row here in the main function we are make it is now we are putting the result and that's it now we have complete a Java program to solve the any tune problem using backtracking so we just want to check the problem I am going to submit a problem let's uh test the problem then submit yeah it's working fine and see what the output will look like for n there is a two possible solution for placing for Q naught for chess board yeah it's working and for one q and can place one ball yeah it's actually working then we can submit the code now yeah it's successfully accepted the solution now the time complexity and space complexity of the code the time complexity of this solution is O of n into n factorial is nearly equal to often factorial as it uses a regressive algorithm to try all the possible combinations of placing cunes on the board and the E saves taking again the worst case scenario where there is no solution all the algorithm will have to backtrack through all possible solution to find the next one leading to the time complexity of n factorial the space complexity of the solution is off and square as it used as a 2d array of size n into an present the chess board additionally it uses a rest of size and to store each solution therefore the space complexity of a solution is of n square plus n which means which is simplified as of n Square there you have it we are successfully solved the end Cube problem using the backtrack in Java you can try running the program the large input to see how the numbers of a solution grows exponentially with the size of the G-Spot so here the E safe size of the G-Spot so here the E safe size of the G-Spot so here the E safe function has a Time complexity of off and right can be reduced the time complexity to our phone yes we can to know more about that efficient approach please follow my channel and my meeting and I am coming with the efficient approach in the next video Until then take care thank you foreign
|
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
|
133 |
hi everyone it's cin today we have a problem when we are given a note in a connected undirected graph and we need to return a deep copy of the graph so each note in the graph is has value and also it has a list of the neighboring noes okay let's take this example let's say that we have this undirected graph 1 2 3 4 and then we need to make a deep copy of it so what each note represents each note has its value and also it has its neighbors and uh let's say that we are starting from four right we are given four so we are creating a new node four and also the next step is we need to create its copy also if it's neighbors one and the three what's the biggest problem here the biggest problem is that let's say four has two neighbors one and the three we created one and the three and uh also for the two we have two neighbors one and three so we should not we should have each for each node we should have only one Noe one copy of that node in the memory to do that we are going to keep track of the each note that we are creating in a hash table or in a hash map so we are going to the first search for the each note and we are going to save the whichever node we are creating we are going to save that in our hash hashmap so let's start from the four right so first we are creating four and then we are death first searching so we are going to the next one so none of these exist so we are going to the next one which is three right so now we are creating three so we are adding four and the of node right so we are adding the that node this node that we are created for four to our hash table so we created four now we are going to the next one three does not exist we are adding three also creating a new three new node and adding that to our hash table so but for the three the four is already exist right so we are not creating a new node so one of its neighbors is four we are taking from the hashmap and we are the first searching and we are going to the two again we are creating two and we are adding that to the hashmap and we are adding the node that we created for it so again two has one neighbor that already created three we are taking that from the hashmap and we are recursively calling for the other one 41 one does not exist we are adding one in to our hashmap and now we for the one we have two neighbors four and the two we are taking four and the two from the hashmap and now we are backtracking so now we are backtracking to one where we started to four at this point we already have all the notes we created all the notes and we are in we are returning the we are returning that Noe the root node of that the note where we started for the Deep copy which is four in that case also we are returning that value first thing that we do here we are creating a hashmap where the key is the node value and the value is the node itself that we are creating the reference to the node so in our main method in the Clone graph so what we do first we are checking the edge case if the node is equals to null in that case we are just returning null the next one is that we are checking that if that node if we have we already created that node earlier if we have created that then we are just returning that node if we haven't created yet then we are cloning that node so we are creating a new node and with the value being the value of the node and we are creating the empty array list and we are saving that to our map and the next step is we are recursively adding our neighbors so for example in this case let's say that we are at the last note taking in account our example that we have seen earlier let's say that we are at the node one at which point we have already created neighbors four and the two right they are already in the hashmap so we are recursively calling and for both of them we are just returning them from the maap values which we are adding to our neighbors list and at the end we are just returning the cloned node so what's the time and space complexity of this solution the time complexity is that the vertices plus edges so in our case the nodes how many no nodes we have and the how many edges we have each node and Edge we are visiting once for the time complexity is determined by the size of our hashmap which is going to be this which is equals to number of the nodes so it's off V I hope you like my content uh if you like it please hit the like button and subscribe my channel that's the only way how you can support me see you next time bye
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
268 |
what's up guys it's David Ilan here today we are gonna be going over 268 missing number on leak code this has to do with arrays so the description reads given an array containing n distinct numbers taken from 0 2 and find the one that is missing from the array so we know that there's going to be a number missing from the array we just don't know which one and we have to find it so given here this array 3 0 1 if we put it in order we could my first thought was to put it in order but that takes a long time I think that's n log n time yeah in log n time because you have to sort it that would be easy because then we can just loop through but we could also use a hash set so if we just put them all into a hash set and then check to loop through and check to see that hash set contains that number if it doesn't we return that number that it doesn't contain so that's a one solution and then another I'm going to show you guys the second solution is Gauss's formula so if you guys know a little bit of calculus this is the series basically saying this is the series saying from I to n this is the so n would be the last number so say we have 3 in the first example 3 times 3 plus 1 over 2 it's going to give us like the sum of this series so 3 times 4 over 2 gives us 12 over 2 equals 6 and if we just check that quick 0 plus 1 plus 2 plus 3 equals three plus three equals six so we could just have to code that into our code so I'm going to show you guys both those solutions so let's jump right into it so for the first one we're going to do the hash set so let's create a hash that we set answer I've been gone so long I've been slammed with school mostly calculus in just this endemic thing going on my motivation to been kinda low I don't know why probably cuz I don't leave the house anymore so here we're gonna loop through and just add it to our hash set so new set if that add num and then we're gonna in town so we're gonna have to check plus one so if we're given a three number right there supposed to be four numbers so we're gonna do int count equals mums dot length plus one and now we're going to loop through it I less than count I plus and okay you can still see the code perfect and now we're just going to check if the new set does not contain I then we're just gonna return I and yeah that's correct and if not if we reach here we're supposed to return negative one that's given in our prompt so let's just run that real quick just make sure it works if you said contains I think it's yeah let's submit it and that's that and now I'm going to show you guys the Gauss formula so let's just grab the length real quick nomes that length and so the gospel formula is well the expected size of expected some basically equals length so it's n times these times length plus 1 and all that / - oops and the actual some sort of some that were checking it's going to be set to zero and let's do another enhanced for-loop same thing so for num nums for-loop same thing so for num nums for-loop same thing so for num nums we're going to add these sum so plus equals num and then we just return expected some - actual stone so what expected some - actual stone so what expected some - actual stone so what that does is the actual sum we'll get when we add all the numbers let me show you guys a whiteboard this out for you so if we're adding 3 plus 1 plus 0 gives us 4 which is our actual sum so if our expected is 6 if we do 6 minus 4 equals 2 which is the number that was missing in this array so we just need to return that run that code and boom there you have it if you guys have any questions please let me know and please subscribe to my channel I know I haven't been posting much this past week but I'm going to try and do two or three videos every week from now on calculus is almost over so that's fantastic and I'll see you guys in the next video
|
Missing Number
|
missing-number
|
Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._
**Example 1:**
**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.
**Example 3:**
**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `0 <= nums[i] <= n`
* All the numbers of `nums` are **unique**.
**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?
| null |
Array,Hash Table,Math,Bit Manipulation,Sorting
|
Easy
|
41,136,287,770,2107
|
332 |
Hello hello guys welcome back to tech division in this video you will see here constructed in every problem which from list on day 26th June challenge saw it every basic elements plan route ok so let's know problem statement in this problem departs from Saudi Arabia on Thursday And Constraints Thursday Example2 Represented By The Capital Is And Dhanis Mein Ajib Were Present Tickets From At Least One Valid In Every Day And Points One Must Use Oil The Tickets One And Only Ones Saw A Problem Statement Latest Located Example To Understand Better Knowledge Based job from internet problem you can watch this video in description box of video subscribe now you can see hidden from this point to you all subscribe start and this k and want to printer they regret taking and constraints into consideration 100 glue start from j&k And consideration 100 glue start from j&k And consideration 100 glue start from j&k And cover the route for all the tickets in electrical order of multiple choice from point on the return of the rebel subscribe channel subscribe only one way will be difficult to travel from this is not possible only through this recorder latest to 10,000 if you ok recorder latest to 10,000 if you ok recorder latest to 10,000 if you ok sorry this routine country's late can be possible when you later this point you can travel to travel from your travel tours and travels rule boobs pe rouge possible from this is page subscribe if you liked The Video then subscribe to have and also for me to see in this pic as it is clear that you go from YouTube and you will never reduce that is not its form into ok so this is not to valid root withdrawal tickets will withdraw troops from From this is just wasted 10 days for you can go from 2nd same to you will never go from this point to another which will be given in the test case must be valid reservation notification for is that one must All It's Only One Meaning Wikinews And Forget And Subscribe Button To Be Deducted From This Cream And Use This Constipation ACDT Subscribe Thank You Can Be Used Only One Day You Will Come Back Again You Will Be In The And You Will Not Be Valid Only This But no one can be reduced to like this main question day will cover all the exact one-third shy three exact one-third shy three exact one-third shy three options available for travel and different point and you have two options Unlimited Galaxies are graphically small or option a computer 40 units of option To Record Your Route Fuel Basically Must Subscribe To Channel Subscribe Now To Receive New Updates From This Is Not Connected To Be Nominated For Software Subscribe Must Take New Delhi What We Can Simply 215 Tried To Traverse Solitaire From And Starting Point Is Okay Sorry Travel From This Will keep recording the route from village Will go to see Fennel is baking powder Setting point to 0.2 C The will go to see and E Will go point to 0.2 C The will go to see and E Will go point to 0.2 C The will go to see and E Will go to record 9th again Subscribe No problem again Will go to Ghaghra This is the president for this is the Chief of Defense This is not the answer is the President to go to subscribe to this quarter in government doing this you just need to sort all you least value 100 glister president unit cost day ok so after submitting this will come for instance e saw you make This First Day You Will Be Amazed Click Subscribe Button And Subscribe To My Channel Like It Will Be Id Am Id 2nd Id Veer That Will Have To Use A Map Be Caused This Graph Is Not Starting From 0 To Not In Preventing in values of one sombeer and will have to In Preventing in values of one sombeer and will have to In Preventing in values of one sombeer and will have to you same to you will not valid only possible but just subscribe which will give you no what is the latest subscribe point and used in to-do list maintain point and used in to-do list maintain point and used in to-do list maintain the notes1 is so if you stop this j N You Will Go To K And Will Also Be Recording Value Used And You Will Go To K No From K You Will Go To Z Song In Every Year From Ball Subscribe Remove Video K And Women On Top Of The Valley From 2ND Year Later These Values Will 2ND Year Later These Values Will 2ND Year Later These Values Will Report Subscribe Now To Quip Pump K You Can See But There Is No 1872 Advisors K Having No Ads Victims Were Not Going From K Two Years So They Can Calculate What Will Be The Road Office Follow This Logic Okay So Even On Direct Order Will Not Be Able To Avoid All Logic Subscribe Not Considered A To Go To Take Care Subscribe Situation Will Be Late Question How This Test Will Help Solve Is Starting With Jain Saurabh Jain They Can Go To K 100th Test Jain Vipul Jain And Were Going To Give You A Quick Way To Develop This Element From And Answers Wrong Answers To Your Language Setting Will Remove From The Channel To Subscribe To The Page If You Liked The Video Then I Already Juice And Elements For No Deposit This Point So you will bring a year and technology suji element subscribe you will see the answer is in incomplete jan22 From this is the most unique in its limbs in the mid-day data structures can also be mid-day data structures can also be mid-day data structures can also be used as an example of a is so in this case Latest Se Dasak Hai But Reduce Agency List Will Destroy Their Survival Bhi Posting Arif's Yuva Work No I Will Go To This Post Element Which Will Not Remove These Will Go To 9 Airtel Wipro Limited Airtel Will Be Removed From All Sorts Of Subscribe To That And Toe Written And Answer Nokia Northern Next Values Airtel Wipro To Airtel Next Values Airtel Wipro To Airtel Next Values Airtel Wipro To Airtel Nothing Is Pain And They Will Not Experiment In More Subscribe Again And Again 420 409 Subscribe And Values From Nowhere For Notifications From Smaller States Awards Quaternary Discovered Naugaon Will have to go to anyway and discovered from those who know option will go to 16 December 1872 subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to Message Send Element Devi Travels to 10 Elements and Went to the National Interest Other Element is Not Having Any Other Element Subscribe Thursday Doing a Solution Subscribe 4,320 Loots Finally Bigg Subscribe 4,320 Loots Finally Bigg Subscribe 4,320 Loots Finally Bigg Boss on Thursday
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
69 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problems square root of x we're given a non-negative integer X x we're given a non-negative integer X x we're given a non-negative integer X and we want to return the square root of x rounded down to the nearest integer so for example the number four what's the square root it's 2 squared is equal to 4. what about 8 well it doesn't have like an integer value square root it's something like 2.82 you take that number something like 2.82 you take that number something like 2.82 you take that number and square it you get eight but in this case we would want to still return the value 2 because it's the square root rounded down so how can we solve this problem well given an integer let's say x equals 7 how do we find the square root we know it's going to be two point something and we're going to round that down to two but how would we determine that well the brute force would be to just iterate four in range let's say starting at 1 and going all the way up until the x value which is in this case seven we're going to Brute Force this and find the square root we know the square root is going to be less than 7 and probably greater than or equal to 1 though it probably wouldn't hurt to start at zero because in this case our input value X could be zero and the square root of zero I guess is also zero but that's a minor detail let's say we start at one we square one that's equal to one is that the square root well let's try the next value two squared is equal to four is that the square root of 7 well let's keep trying we get to 3 now 3 squared is equal to nine so we went too high we are now greater than seven so three is not going to be the square root because we know we're going to round down anyway the last value that we saw that did not go over was two squared was equal to 4 so 2 is going to be the square root of 7 rounded down now the downside with this solution is that it is a Brute Force solution it's actually not Big O of n even though it kind of looks like it because we know that the loop is going to terminate before we get to n it's going to terminate by the time we reach the value which is the square root of n which makes sense because let's say you know in terms of n is the input value X we know we're going to stop by the time we get to the value which is the square root of n because we know that value squared is going to be equal to n so in reality this for Loop is going to run in Big O of the square root of n time but we can actually do even better than this as well because we can use a binary search approach which is going to be log n now before I explain it you might be wondering how do we know that this is more efficient than the square root of n because it's not super obvious well I won't give you like a super long mathematical proof but intuitively we can think about this in terms of big n values what is the square root of n if n is equal to a million well the square root of a million is going to be a thousand well what is log base 2 of a million well it's going to be an integer value I don't know the exact value but I know it's in the magnitude of like 20 or something maybe 21 or 19 something like that but clearly that's a big difference square root of a million is a thousand log base 2 of a million is 20. you can clearly see that log grows a lot slower so log is going to be much more efficient if we can achieve a solution like this which we can using binary search we know our search space is going to be between let's say zero all the way up until X it's a range of values we're going to calculate the Midway point so 0 plus x divided by 2 is going to give us some Midway value we're going to check M squared is it greater than x because if it's greater we know that this can't be the square root of x and we need to now decrease our search space so if this is true what we would say then is we're going to cut our search space in half and now start searching between 0 and M minus one whatever that previous M value happened to be and we're going to continue doing this suppose next time we calculate the mid value and mid squared is actually less than x then we would do the opposite we would increase our search space and then search on the values on the right side of that and we would keep doing this but the difference here is that when our M squared value is less than x this is going to be a candidate for our result because we basically want the largest value the largest M value where this is true that's assuming though that the square root is going to be a non-integer value root is going to be a non-integer value root is going to be a non-integer value it's also possible that the M squared value actually is equal to X if this was the case suppose like an example like this where 2 squared is equal to 4. if this is the case we basically return immediately so that's the idea of how we're going to solve this with binary search in login time it's going to make even more sense when I show you the code right now so first things first let's initialize our search base left is going to be set to zero right is going to be set to X we're also going to initialize our result it doesn't really matter what value we give it I'm just going to give it a zero and then we're going to run our binary search while left is less than or equal to right while our pointers haven't crossed each other we're going to continue searching you could say m is equal to left plus right divided by 2 but that could possibly overflow a better way to do it is to say left plus the halfway distance between right minus left so taking right minus left and dividing that by two this also gives us the same value as before it's a different math equation for the same value the only difference is that this will never overflow it's a minor detail but I think it's worth knowing next we're going to run our equalities so we're going to check is M squared you can square it like this in Python is it greater than x what happens if it's greater than x then we're going to decrease our search space we're going to say right is equal to M minus 1. we're going to search on the left side else if the opposite if M squared is less than x then we're going to search on the right side we're going to say left is equal to M plus 1. but also if this is the case we possibly want to set our result to this value because this could be the result this mid value could be the result so we're going to set it like that now the third case and this might not always execute is that M squared is equal to X we can just use an else condition for that and then we would want to immediately return the mid value because we found the exact square root otherwise we know that the loop is eventually going to terminate and by the time it terminates our result will be set to basically the gray latest mid value that was less than x well the greatest value that we could square that is less than x which is basically the square root rounded down so in that case we would want to return the result outside of the loop just like this so now let's run the code to make sure that it works as you can see it does it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neco.io it has a ton of free out neco.io it has a ton of free out neco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Sqrt(x)
|
sqrtx
|
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.
**Example 1:**
**Input:** x = 4
**Output:** 2
**Explanation:** The square root of 4 is 2, so we return 2.
**Example 2:**
**Input:** x = 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
**Constraints:**
* `0 <= x <= 231 - 1`
|
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
|
Math,Binary Search
|
Easy
|
50,367
|
759 |
hey everybody this is Larry this is January 18th and uh or yeah today I should be doing the day 19th of the legal day challenge but it comes up in 40 minutes but I actually have to go out for dinner so I figured uh but I do have a little bit of time for some reason so I think I'm just going to do it in reverse which is that I'm going to do a PR I haven't done yet today for today do a random algo problem that haven't done yet and then when I come back from dinner I'll do the daily problem so yeah uh it's a little bit out of order but you know we'll see where the r takes us and we'll you know have fun together hopefully and hopefully this isn't too hard I should have maybe limited to the not hard because I do actually have to go to dinner uh meeting a buddy but that said let's get started uh today's Farm is 7:59 employee free time we're giv a list 7:59 employee free time we're giv a list 7:59 employee free time we're giv a list schedule of employees which represent the working time for each employee has a list of non overlapping intervals and these intervals are in sorted order return the list of finite intervals representing common positive length free time for okay I man I read the words but I have no idea what this means okay let's take a look at the example uh man I need more Focus I think maybe I'm just I don't know I just don't care that much but okay so then so there are three employees how do you see what is the schedule this is like impossible to read all right maybe I should put the thing okay how do you have three employees oh this is one employee so the first employee they should just write this right like the first employee is 1256 one the second okay and then okay so basically you're just trying to find um yeah basically you're trying to find the time slot that is actually on um that's overlapping for all the employees actually this is funny because I think uh I don't know I mention this but I do when I was an interviewer uh this is a long time ago now um I haven't worked in a while but uh so this is a long time now so maybe I can now say it a little bit but when I was an interviewer uh and I and actually when I was an interviewer I mostly did system architecture because I was just one of the few people actually qualified to do that interview but I also step in once in a while for um for coding interviews and when I did coding interviews this I have like I have two problems that I like to ask and a variation of this problem is actually something that I ask because there are a lot of variation on this one so then there are a lot of follow-ups and uh there are a lot of follow-ups and uh there are a lot of follow-ups and uh and you can kind of figure out how they kind of you know um adjust the answers to more difficult problems but uh and the way that I would solve this obviously depends uh there is I think people always tell me that there's like a greedy way uh and I'm sure there is though end is only 50 so it's not even worth like doing anything that silly um or they're n employees and each of them have end so there's like 2500 um interos but um but yeah but there are a couple ways you can do it the way that I always treat these things if you've been watching me long enough and I think nowadays A lot of people have been doing it my way more um not to say that I invented it but I think I popularized it along a lot of people um because I think people usually do this in a more like greedy structured kind of way and maybe in a lot of those cases it is linear especially when you're only doing with two schedules or two interos but um but this is the way that I've always consistently done it just because it's you know I don't know for me it's just having one thing to kind of uh have an idea about and the way that I would do it is by um uh what's it called defense sorting right or um defense based what I call it's a sweep line defense based sweep line right so basically the idea here is that and you know we can visualize a little bit uh let me bring up my drawing thingy uh and you know I'm not try I take the pen I mean you know basically you just have a an X AIS and of course your intervals are just going to be like you know you for one person you can have this for another person and you know and maybe like a third person is like here and of course your goal here is just to go from left to right and then sweeping all these critical points along the way right uh maybe I should chose a different color right oops uh yeah like here and then and based on those events you want to um you're able to model this in a state uh finite state autom or something like this where you can basically just try to figure out what you want at that time uh and depending on the problem there are you know you have to figure out what states you care about or not uh in this one it seems like it should be pretty straightforward so uh or to define the states not the par straightforward but we'll get it together so yeah so first we'll just have defense right then now we have for S and ye and no for employee schedule or ye schedule maybe I don't know in schedule and then now for s e and e schedule um and these naming is may be a little bit terrible but yeah you can do events. a pen the starting event so you have the X you have starting I just you know maybe I'll call start right so start n is equal to 1 two or something like this just y nums right and of course if you are in production we'll do real un nums SP we could do this and in feor you can also um you don't actually need this in a case because of the way the um the oh am I right on this oh no yeah it's on sorted on uh in the way that this is constructed you don't actually need to keep track of the index um or like the employee right because it's just a lot of segments and you want to make sure that you know let's just say n is equal to link of schedule actually but yeah but you can maybe if you want to and maybe I'm wrong on this so we'll see and defense. a pen we do e+ one we have n right uh the way the do e+ one we have n right uh the way the do e+ one we have n right uh the way the reason why actually I new E plus1 I think this is the part that we have to think about is whether the inclusive or exclusive um the five is a final answer because they have zero length so what does that mean right so that means that they overlap with zero length you do not want the answer I think it's fine I think in Especial with discrete defense uh it just really depends on how you sort it and I think the way that we sort this because we get rid of um because on tie breaks we get rid of start before the and um that will always create more overlaps in a greedy kind of way which should be what we want okay so yeah so then now we can do events. sort right and then now we can do for X as in for the x axis and then type in evence um then now what do we want to do right so we have a current like a current is equal to zero this uh the number of current overlaps right um yeah and that's really it oh and I guess you have to keep track of the answer oh and the okay we I'll write um is it begin uh something like this we won't go with I mean we'll go over it but just as a play order for now um but yeah so basically if the type is equ to start then what do we do that means that we want to add one more interval that's inside our number of intervals right now right or schedules and then else T is equal to uh well n so we could subtract one so then what are the states that we care about so the state that we care about is if current gets to n right that means that if current is equal to n then that means that you have n intervals inside the current uh sweep line so that's the beginning of all the common uh free time right so if this is the case we don't start is equal to um I guess X right okay and then another state that you may care about and technically you can only get up to here of course if T is equal to start because you can only increment to n right um otherwise you know all the other states just yeah well there's only one to get to add uh I say it this way because the other state is let's say you drop from n to n minus one so then now that's the other state that you care about because now you have no longer a common positive thing so if this is the case n um n t is equal to n that means that the I mean you could write this in a number of ways but it just means that it used to be n now it's n minus one so then now we have to do uh that means that the end of the common thing right and the common thing is going to be stored and the current X right and then you could append this wait did I miss read this one I did misread this one sorry but in a way uh cuz for some reason I was soling for common overlapping times but now that I think about it I was like oh that doesn't make sense uh with the negative infinity and stuff but so yeah so but basically now uh so I made a m okay let me step back for a second so I made a mistake I thought it was the common uh the schedule in which the time style in which all the things are common but it turns out it's the um it should be the common free time which means that there's no one right so that actually is a easy fix this is why I like it this way because it's just representing like I said the finite stomer maybe it demonstrates my point even though maybe I'm a little bit cuz now this stuff is as well but the idea is still right which is that if current is zero it only means that previous is one because it can only go from one to zero after a change so then we start the next otherwise if this is equal to one that means someone is um starting the schedule so you have to go make sure that it goes from zero to one um and that's pretty much it that's the only fix kind of you may we might have to um take care of the negative Infinity stuff um but yeah let's take a spin uh what did I do well did I Mis understand this for schedule in not oh it's an interval object not cuz I saw it like this and I thought they would give us a tppo but uh but actually apparently it's an interval object with a start end so okay so easy fix right that's where uh abstraction is nice don't have to worry about you know List have no op oh uh we might have to fix how we no we don't wait what is the element section uh y do append first. start wait where oh we have to return interal objects also we should reset this though it doesn't really matter because you know this there's only one way to get here and there's only one way to get here but and it has to you know but uh H what is this but I think it we have to return an interval I think that's why and we return it t because I didn't realize but uh yeah it's just new interval um is it new am I just like I don't think this new I'm mixing languages in my head maybe uh what am I doing a list of indos right isn't this a list of indos is it new am I just confusing it I don't know languages no that's not right but huh what is going on in and none type oh so start may be none did I mess this up oh because start is none when um this is infinity because well this far it'll be impossible to get but here it goes to Infinity so yeah so we I guess we have to do like if start is not none just so that we don't kind of do it that way yeah all right well the idea is right maybe I H I think this is uh we might have to change this part again because um I might have I like I said I was misunderstanding what they were trying to do so I was greedy on the other way so basically now want to get free time and free time starts exclusive of the end point so I think we can do this um and do we what order do we want it in I guess it doesn't really matter the order because we might have to add a thing that uh like you know start is not equal to X just in case that like it shouldn't but maybe when it starts and it ends and stuff like that and it's it counts like a zero length thing as a thing but yeah way easy effects though uh I don't think I described it as well this is just a lot of experience um but the idea is that um what you how you handle um the edges of like two IND the RS bumping against each other right and for the other one um it was n+ one for the other one um it was n+ one for the other one um it was n+ one because we wanted to overlap that and count that but here now we don't anymore because we want to count free time so we're greedy in that way so that we can have if statements here let's give us some M I think we should be okay but maybe I have some weird Edge case uh looks good though so I'm pretty happy about that um but yeah very powerful idea way powerful technique sweep line events uh and all these things um yeah as you can see I even like I technically solve two problems I mean if you want to say that because I did it with the other one where we actually kept track of all the times everything overlaps right so uh yeah and you can obviously do you know more funky things depending on the question like oh what if only two of or 40% or what you know whatever right of 40% or what you know whatever right of 40% or what you know whatever right of the people are free or something like this and you can definitely you know create intervals that way using your custom rules in very easy straightforward way it's definitely a powerful technique uh just in general for competitive for interviews I don't know I mean like I like to give it but I don't think it's that common to be honest but uh yeah um that's all I have for this one let me know what you think stay good stay healthy to a mental health I'll see y'all later and take care byebye
|
Employee Free Time
|
set-intersection-size-at-least-two
|
We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8`
| null |
Array,Greedy,Sorting
|
Hard
| null |
326 |
what's up everybody ajit mahajan here and welcome back to yet another youtube video in today's video we'll be solving another lead quote question number 326 also called as power of three it has also been asked in day 27 of a pre-lead code challenge so let's get pre-lead code challenge so let's get pre-lead code challenge so let's get started given an integer n return true if it is a power of 3 otherwise written false an integer n is power of 3 if there exist an integer x such that n equals to 3 to the power x okay so basically what they are saying is we are given an integer n and we need to check if it is a power of 3 okay so some of the constraints that are given is n belongs to minus 2 to the power 31 to 2 to the power 31 minus 1 okay now let us look at some of the examples that we are given here okay so and if n equals to 27 which is basically the power of 3 uh 3 to the power 3 so it is true and equal to 0 does not line here so it gives false n equal to 9 is second power of 3 so which is also true and when we have n equal to 45 uh we do not have it here so we are returning false now let us look at how we can approach to the solution so this approach is very simple and you might have definitely got this approach so what we are basically given is uh we have n and n equal to b to the power x form if n is the power of 3 so in this case b equal to 3 what we are taking and it can be termed as b into b where b equal to 3 and we get n when we multiply b x number of times okay so uh in this approach what we basically do is uh we basically take the number and keep on dividing it by three okay and check the reminder uh what we have if the reminder is non-zero have if the reminder is non-zero have if the reminder is non-zero then we check if the reminder is one if it is one then uh it is a power of three if it is anything else except one then we return paul because it is not a power of three so that is what we are doing here we are just uh doing a corner check that is the number which we are given is greater than one because uh if it is less than one then it is uh not a possibility that it is uh power of three then we are doing a while loop and doing modulo and modulo three if it is equal to zero and if it is equal to 0 we go on dividing by 3 unless our modulo is not equal to 0 and finally we check that uh after dividing at the last step if we have n equals to 1 okay so if it is equal to 1 then it is a power of three else we return false okay so i have run this code and i have just uh this is a complete one screenshot so you can see it was uh runtime was 16 millisecond and faster than 43 percent memory usage 5.9 mb than 43 percent memory usage 5.9 mb than 43 percent memory usage 5.9 mb okay so that was the first approach now let us look at the second approach so the second approach is uh almost very similar but in this uh we are doing it everything recursively okay so this is everything is same just what we are doing here is we are making recursive calls so that to make the input smaller okay so what we basically do is we just initially these are the corner checks that is if less than one will return false if n is equal to one then this would return true okay so after that what we are basically doing is we are checking uh n mod three that is what is the reminder on dividing with three and if it is equal to zero then we are proceeding further that is uh doing more recursive calls and then giving the same function is power of 3 the n by 3 okay so the next recursive call would contain current number divided by 3 so it will go on recursing and finally we will get true or false whatever the solution is okay so on running this i was getting uh it faster than 14 and memory usage was 5.9 mb was 5.9 mb was 5.9 mb less than 25 okay so now let us look at this approach three the third approach is completely based on base of a number okay so when i first saw this approach it completely blew my mind now let us look at what up what this has to say so what basically it says is whenever you have to look at the powers of numbers you need to check it in its base okay so if you are talking about powers of 10 then you have to look it in base 10 so the powers of 10 are 10 100 1000 10 square 10 cube okay so in this uh one thing you need to note is that uh the first digit of every power of 10 is 1 and rest are 0 okay if you look at powers of 2 and base 2 then we have we know how they are represented that is first digit is having value 1 then we have 2 value then we have 4 as value then we have 8 as next digit value okay so uh if you convert 2 4 and 8 which are powers of 2 square to q in the base 2 then we have 10 for 2 100 for 4 and one thousand for eight isn't that interesting we have first digit as one and the rest digits are zero uh also in four and also in eight so this property holds for three two so what we are basically doing is we are taking a number converting it to the base three and then checking if uh first digit is one address digits are zero that's it that's the approach okay so now let us look at the code so what we are basically doing here this is the corner check let me increase i don't know if you are able to see it you most probably you would be so this is just the corner check that is uh if n is less than 0 we just return false next for this part of code what we are basically doing is we are converting any number to base three okay so after converting it to base three uh after that our task is very simple we just need to check if first digit is one and rest of the digits are zero for converting into base three we just use a for uh while loop and then converted it to string by dividing it by zero okay it is very simple and after that what we are doing is we are uh checking in the while loop if every digit except the first digit is zero okay that's what we are doing uh size of minus one checks except the first digit and if it is uh not zero that digit is not zero we are just returning false and finally we are checking at this position if the number when after converted to base three has the first digit as one okay so if the first digit is one then we just return two because uh in base three it is of the form the first digit is one and rest are zeros uh if it is not the case then we just return false so that is the third approach uh and i have also run it and i'm getting it faster than 14 and less than six percent uh of memory space now let us look at the fourth approach that we have the fourth approach is basically uh using the limitation of the data type that we are given with okay so if you look at the structure of the function that we are given uh we are given an integer data type okay so the maximum value of integer data type is given this so this is basically a solution from lead code and this is the same article um uh it was to the point so i used it directly so uh and n uh so data type given is end and maximum value this data type can hold is this so they have given some ways to calculate it so this is uh they are basically taking 2 to the power 32 by 2 because half of the range is for negative and positive numbers and 0 is a positive number so that also needs to be included and after that so if you look at that this data type has a maximum number so we are finding the maximum number which is power of 3 in this range okay so the maximum number that is power of 3 in this range is this and they have calculated it with logarithm some manipulations basic manipulations which is 3 to the power 19 okay so for if uh whatever value of n is given then we should return true if it is from anywhere from 3 to the power 0 to 3 to the power 19 okay so uh now as we have 3 is the prime number and the only divisors of 3 to the power 19 would be the powers of 3 right because 3 is a prime that is the first condition that we are having so uh the only thing that we just need to do is just divide the maximum number that is 3 to the power 19 in our range by the number that we are given okay so if we divide the maximum number with the number that we are given uh that is 3 to the power 19 divided by n then uh if the reminder is 0 in that case we can be sure that the number n is divisor because we know the only divisors of 3 to the power 19 are from 3 to the power 0 to 3 to power 19 taking all the powers okay so that is the only thing that we have to do and if the remainder is 0 then we have got our solution okay so what it is a one line solution basically this is the corner case if n is greater than zero if it is n is greater than zero then what we are basically doing is we are taking the maximum number that was 3 to the power 19 and then uh taking modulo with n okay so it will give the reminder on dividing with n the maximum number and if it is zero then n is a divisor of three and which is why we return true if it is not then we return false so uh i have also run this also solution and it gives me run time of four milliseconds because it is a of one solution because we are not doing uh we are just doing single operation and it is faster than 97 and memory usage is 5.9 mb usage is 5.9 mb usage is 5.9 mb so that's all for this video guys uh if you like the video uh hit the thumbs up button if you have some other solutions in some other language comment below uh if you need more such content join the discord server and subscribe to this channel and see you in the next one bye you
|
Power of Three
|
power-of-three
|
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_.
An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.
**Example 1:**
**Input:** n = 27
**Output:** true
**Explanation:** 27 = 33
**Example 2:**
**Input:** n = 0
**Output:** false
**Explanation:** There is no x where 3x = 0.
**Example 3:**
**Input:** n = -1
**Output:** false
**Explanation:** There is no x where 3x = (-1).
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Recursion
|
Easy
|
231,342,1889
|
1,074 |
hey everybody this is larry uh hit the like button the subscriber enjoyment disco let me know what you think about today's farm it is day 18 of the july leco daily challenge and farm is number of sub matrix c's that's some to target i hope everyone had a great weekend i'm back to new york as you can see in the background um yeah it was a very long bus ride so i'm very tired though i passed out because i had i ate a lot of food so i'm okay now so let's go let's see what's today's problem all right give me it's a hard one so hopefully wrap will do well we'll do okay uh given the matrix and target return the number of non-empty submatrix that sum to target non-empty submatrix that sum to target non-empty submatrix that sum to target huh a sub matrix ex okay um is it all one nc was it she said oh no it's just this example which is okay um so if for this for problems like this i mean this is hard uh for sure um i don't have an off my head solution yet so you know we'll do it together it will be fun if it's a little bit slow watch it on 2x or whatever um okay so the first thing i would try to do is think about what i would do in 1d right this is a 2d problem i know and that is some part of the difficulty um the first thing i would do though is still think about one dm solving that first and knowing what to do in that case will um at least give you some basis of an attack maybe not always true depending on how the structure is but this one seems like you know and if nothing else that is going to be one of your inputs anyway where like you have a one by x away then you know one by n away or whatever um you know that's going to happen right um okay so if you're given that let's say you have a number of sub arrays that sum to target well that's a waste um i think uh i wouldn't say i want to say it's standard but i don't think it's actually standard i think it's tricky it's almost like a prefix sum type thing uh but you know it's something that at least for competitive programming and uh i don't think that's the case for interview quite yet but i could be a little bit wrong on that one but it is something that people have gotten and some of that is uh making sure you understood the understanding of that uh problem right let me just write it up so you know people know what i'm talking about um the understanding is uh or is the focus that i would have because i think you know you look at the code and it's like three four sorry not three four three lines of code there's a uh there's a hash table there's a for loop there's a statement there's an if statement there's an ad there's a return and then you're done right um for this problem something like that and it's very tempting to say that okay look the code is six lines of code how hard can it be right this is a easy problem some of it may be because there's six lines of code or whatever people might just like you know have some memories you know memorize it without memorizing it um or maybe another way of saying it is uh not truly understanding it right and so um yeah so definitely make sure you understand that i think that's step one and then step two is that now what right um let's say we do understand the one d one uh the sub arrays one how do we extend it to 2d right well i guess that's the same idea right you um you have the number of all the things that are to the so basically in the 1d version you're given almost like a uh a pointer right i wouldn't call a slide window but like a point of this is the current thing and the current uh cell in that case would be like okay this is the right side of the 1d array um how many left sides are there right so then a corollary to that in 2d would be that this is the bottom right how many um you know how many um how many upper left corners are there right that's i think that's the way that i would do uh start approaching that and then the question is can i do that in a good way because the problem here is that every time you add a new row you would almost have to reset it like if you think about this okay actually let me just draw it out hang on no damn especially now that i'm back in new york i got my drawing thing um i have to think it through a little bit well like i feel like there are a couple ways to do it but i have to maybe take a look at the constraints as well let's see think about this for a second i mean 100 cube would be good enough so that's definitely a thing but basically the idea here is that wait i put on screen i did not could catch this time a little bit um but basically the idea is that okay let's say you have you know you have some cell right and as we said i don't know how that line through into place but this would be it right let's say we have something like this and then now we're here right or let's say we have this cell and we're moving to this set oh so then how do how does that work i don't know how you would work it without like resetting everything because then chris hmm oops how did that happen because if you're moving from say this cell and to into this cell um you know you just add kind of all the numbers here but um because you're trying to find upper left that is in this section right and then you now you're trying to add it to this section for to find target i think i know how now um and some of this is the constraints right um because yeah i mean i think we can just do it that way let's see because you just wait can we do it that way um i think why is this so weird it's not letting me erase this now but okay fine um i said i've i think what another way of doing it and this is a little bit about abusing the constraints is that now we can just do it for every two rows or something like this because here that now this is going to be um let's say we do we pick any two rows what does that mean right and let's say we have some sort of prefix sum that allow us to almost brute force basically we one way that we can do is that now let's say we have you know these two rows and they'll be gonna be all square rows or i'll choose two rows um basically what you do now is compress this with prefix sum into just one d version of what we did before and then you could do the o of n or c algorithm and this out this one right and here is basically this cell for example is the sum of these three cells here is the sum of these three cells right and then now it becomes one d problem and if you do this brute force on the first on the left as in you try every possibility of rs this is going to be r square or choose 2 depending on how you want to say it um i mean you know r choose two is of r square number of rows and for each of these you do o of c uh c work and that would be why is this drawing thing so lagging today uh of r squared times c um which is going to be 100 cube which is fast enough i think that's what i'm going to start doing then um hopefully this ex makes sense as an explanation but yeah i think that makes sense though for me anyway definitely if you yeah i think the key part is still doing the 1d version which is this stuff and once you understand that stuff then it just becomes proof force in a way okay yeah okay let's um do i need a prefix window i guess so well we don't even we don't um yeah we don't need a full prefix what we need is almost like a vertical prefix right yeah um is my painting okay no uh yeah i think we just we need a vertical prefix because we look uh let me bring the drawing back up for a second because if you look at this um okay so we look at the first three columns and maybe that's a bad example but let's say we have let me change the color really quick uh let's say we look at say this row and this row right well every time you move to the right you can just you know add like you're going to add something like this flow which you can calculate from the vertical prefix you don't need the actual matrix prefix right so okay so i think we can do it from that instead of a 2d prefix we're going to do a uh column wise uh prefix yeah and okay so the way that we're going to do it's going to be o of us or square times c and why i'm pointing this out a little bit early is why i'm pointing this out earlier is because now if r is bigger than c we can actually rotate the matrix so let's do that right um what i mean by that is just not rotate that's is that the right word i guess we could uh we could flip the rc um and then that'll be slightly faster in general so let's do that um yeah the way that i'm gonna do it is just this see then yeah new matrix is to go to i think that's like a one-minute for i think that's like a one-minute for i think that's like a one-minute for this but i never remember it so yeah maybe that's fine is this all time c yeah okay we want to flip it so then four nope return self dot num sub matrix some target of new matrix and target right okay so this is just to take advantage of you know r squared times z it's not necessary it's definitely a premature optimization let's take advantage um but i think like i yeah i just feel like doing it today some days you know and obviously this is not a contest so it doesn't matter but um yeah um it's timing wise okay and then now what um okay so then let's create a vertical prefix um yeah so we want a prefix for each column so yeah so you have something like plus one because we want the first row to be zeros so that's fine and then now yeah prefix of i j is equal to um this is actually plus one it's you do plus matrix of i j um again this is only the vertical component so if you are looking at it now um it's not the 2 4 2 d1 because we don't need the 2d one that's the beauty of solving problems maybe is that you know you do what you need right uh okay and then now we do the 1d algorithm given every row right so for i in range of r um let's say i1 maybe just and for j for i2 in range of uh from i1 plus r2 r yeah um okay and then now we do the thing that we did from um the 1d one we just have to make sure that we're sliding okay uh let's just say counts as you go to do um let's start with zero is equal to one being the actually i guess technically we have the extra prefix but no i mean i think this is fine um yeah basically this is the uh the no uh array right also we have to keep track of total as you would put for just overall total um yeah i was just trying to see how what's the maximum i guess given 10 cubic or yeah i think 10 cube is probably the maximum maybe or close to it is that true basically they're all zeros then for each cell you would have the summation of n squared so it's like n k n to the fourth maybe so 100 to the fourth uh i guess that's a billion so that'll be fitting into an int i know that's a really bad upgrade anyway so it should be okay uh okay and now uh for j in range of c right then here oh we do current is zero maybe we have touched this is the prefix on the from the left goings you know going to the right uh and then now we want add the number between uh so this is going to be i2 of j minus prefix of we want it to be i1 inclusive actually um because of the plus one this is actually this minus this i believe and then so that's the current thing of the that's the current um prefix from the beginning to this cell so that now we have to the current thing of the matrix and then to find target right so you have current let's see what are we trying to find i'm trying to write right the formula right so target is going to be so the current we're trying to find a subset of it that we use is going to be equal to target plus some number x right um hopefully this probably makes sense and then yeah i mean maybe i'll draw it out very quickly because i want to i it makes sense in my mind actually but i want to make sure that it also makes sense for people at home but basically what i'm doing is that uh this is the 1d version now so let's just pretend it's a 1d version uh the idea is that now likes i'm using the mouse because i'm lazy to take the thing out but it's kind of bad but let's say this is current and this current means this is the sum of here right and then here we're trying to figure out some subset where this is the target total so that means that this is the x that we're trying to find uh or this is just x that i'm um paramount parameters per perimeter try using oh my i can't do english today but yeah um so that means that the target is the middle chunk you have x is the prefix that we're trying to remove and then the current is the total right so you have this so then now we're trying to find counts of um because we know target we know current so we can minus target on both sides and then so we're searching for this thing right so because of this thing and then total we can increment uh you know this is the indentation is all off but uh yeah and of course the way you should do it is to make sure that it is in count the reason being that otherwise it creates an entry by default um i think this is rightish let's give it a spin uh no i'm really wrong well i got one case right but hmm did i get this one wrong you should i mean not usually but the reason why i take a lot of time on this is because uh i do make this mistake a lot but let's see okay so if the target is zero well this one is just really wrong do i have maybe i have enough by one on somewhere because this one should be even just like by itself right so oh i'm just being dumb am i forgot to uh i forgot to increment current i mean it might not be the only thing that's wrong but oh i'm just also lazy i usually like that counter i don't uh that's why i um a little bit sloppy today to be honest that's why i did the in thing otherwise that doesn't make sense okay oops um okay so i just forgot to increment it even though i was talking about it um and this is if you have any confusion here like i said this is the one d version of the prompts i don't think i did anything new here and apparently i've made a lot of mistakes in the past let's see if i got it okay the first time yes uh you always want to do slightly better than you did previously and today i did it from scratch pretty okay 20 minutes um of course i did a lot of talking and explaining so um i'm pretty happy and proud of this okay that's pretty much all i have for this one let me know what you think i hope you all have a great you know rest of the week uh yeah stay good stay healthy take your mental health i'll see y'all later and take care bye
|
Number of Submatrices That Sum to Target
|
high-five
|
Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target.
A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`.
Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`.
**Example 1:**
**Input:** matrix = \[\[0,1,0\],\[1,1,1\],\[0,1,0\]\], target = 0
**Output:** 4
**Explanation:** The four 1x1 submatrices that only contain 0.
**Example 2:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\], target = 0
**Output:** 5
**Explanation:** The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
**Example 3:**
**Input:** matrix = \[\[904\]\], target = 0
**Output:** 0
**Constraints:**
* `1 <= matrix.length <= 100`
* `1 <= matrix[0].length <= 100`
* `-1000 <= matrix[i] <= 1000`
* `-10^8 <= target <= 10^8`
|
How can we solve the problem if we have just one student? Given an student sort their grades and get the top 5 average. Generalize the idea to do it for many students.
|
Array,Hash Table,Sorting
|
Easy
| null |
350 |
so we will look at intersection of two arrays two and the question is given two integer arrays numbers one and nums two return an array of the intersection each element in the result must appear as many times as it shows in both arrays and you may return the result in any order and we have an example here so if we have nums one which is one two one and nums two which is two and two what we would do is we would return 2 and 2 because those are the elements that appear both in nums 1 and nums 2 and here we have another example so if we have numbers 1 that's 4 9 and 5 and nums two that's nine four nine and eight four what we would do is we would return four and nine because these are the elements that appear in both numbers one and nums two and for this we can return four or nine and four and both would be acceptable as it also says here that you may return the result in any order so the order doesn't really matter so the first thing that we would do is we would create a dictionary and dictionary is also known as hashmap uh in some other programming languages and the concept is pretty similar that people what we would do is we would store key value here and then we would have an array and this is where we would store elements that appear both in numbers one and numbers two so we will do for number in nums one here uh what we will do is we will traverse through nums one and we will look at each element and then store it in the dictionary and what we will do is we will see if the number already exists in the dictionary or not so let's say that we're in the for loop and it will come across 6 and the code that we're about to write but it will do is it will check if the number already exists in the dictionary or not and 6 doesn't exist in the dictionary so what we will do is we will play 6. and then we will give it a tally or a count of one and then it will go to seven and then it will check if salmon already exists in the dictionary or not and simon doesn't exist in the dictionary so we will uh add it to the dictionary and give it a count or a value of one and then three doesn't already exist in the dictionary we will store three in the dictionary and then we will give it a tell your account of one and this will be the second if statement that would be if the number already exists in the dictionary and six does already exist in the dictionary so what we would do is we would add one to that so this would end up becoming two so if we had another six right here then what that would do is we would make it three so hope that's clear so now what we will do is we will write the if those if statements that were number numbers one f number not in dictionary uh what we will do is we will store that number in the dictionary and give it a count or a value of one otherwise if number and dictionary that if the number does exist in the dictionary then what we will do is we will add one to the tally or the count and we will just do plus one and increment and now what we have is we have all the numbers stored for nums one and this dictionary with the count or the deli and the talia would tell us how many times that number appears and now what we will do is we will have we will traverse through the second terms numbs2 so for this we will also do for number in nums too and here what we will do is we will check if the uh any one of the elements from nums to appear in the dictionary and what we will also do is we will check for the tally uh or the count and see if the counter the delhi is greater than equal to one because so let's say so now we have our dictionary here and we have nums too so here what we will do is we will traverse through nums two and the current element is seven so what we will do is we will place seven here and then when we play seven what we will also do is we will subtract one from the counter with the deli so we will do one minus one which would become zero and then they will move to six and six does appear in the dictionary and it has a count or a tally that's greater than or equal to one so what we will do is we will play six here and again what we will do is we will subtract one from two and this will become one and then we will move to the next element which is seven and then seven is in the dictionary but it doesn't have a count or a tally that's greater than or equal to one because it's zero so we will just skip this seven and we won't uh insert it in the array and then we come across six the next element is six and six is in the dictionary and the count of the tally is greater than or equal to one so what we will do is we will store that six in the dictionary uh in the array and we will subtract one from the delhi and this would become zero and it doesn't exist in the dictionary so we will just skip that we won't store it in the array and then we come across six again and 6 is in the dictionary but it doesn't have a count or a tally that's greater than 1 so that's why we won't store this in the ring so now we will take so now we will do for number in terms 2 and if number and dictionary so we will check if the number does exist in the dictionary and the dictionary number so and if the value or tally or count is greater than or equal to one then what we will do is we will add that number to we will append that to our day so we will just do array.append and so we will just do array.append and so we will just do array.append and number and that will append that number to the and the last thing that we have to do is we have to decrement one from the counter the tally so here we will do dictionary number equals dictionary number and we will just subtract one and then we just return the array so we will run this now this looks good and then we will submit this okay and this also looks good so the program so the code that we wrote works fine and it's able to find the elements that intersect and intersect both in numbers one and nums two uh so now we will talk about the time complexity and for time complexity we are looking at o n the reason is because we have nums one and uh we traverse through each and every element that's in numbers one so that's o-n and we also have nums too so that's o-n and we also have nums too so that's o-n and we also have nums too which is this right here and we traverse through numbers to also uh and we traverse through each and every element and we only traverse through it once so that's also oven uh and even though we traversed through numbs one and numbs two uh and it would seem like uh since we traversed through twice that the time complexity would be longer but it's still considered over and for space complexity we're also looking at on because we're only storing elements so let's uh so in this case we have nums one the first list that we're traversing through and storing the elements of so we are only storing as many elements as there are in nums one uh in worst case scenario so let's suppose that we have an array or a list that has elements one two three four and five are all unique values so in worst case scenario we would store all the elements in the dictionary
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
204 |
foreign hello everyone and welcome back to another video So today we're going to be solving the lead code question count primes question number two through four all right so given an integer and return the number of prime numbers that are strictly less than n so for example we have the number 10 so the numbers we can consider are zero one two three four five six seven eight nine and out of those numbers the only prime numbers are 2 3 5 and 7. so just remember we cannot count the number 10 itself cool so we return the number of numbers which are prime less than 10 and that is four so let's see how we can solve this I'll go through a few ways to solve it and instead of just giving you the solution I'll try to go through step by step on how I got the actual solution all right so let's just say we consider the same example so let's say n is equal to 10. so the numbers we would consider are going to be 0 1 2 3 4 5 6 7 8 9. so everything up to 10 okay so essentially let's see what the most basic thing to do is so obviously the most Brute Force solution would be to test out each and every single of these numbers right and we're going to run it through a function let's say the function is called is Prime and this will tell us if the function is prime or not right so very simply that is going to be so n iterations and each time to find out if the number is prime or not is going to take an additional n times so this is going to be basically Big O of N squared so can we actually make this a bit better so this is still a Brute Force solution but this could still be better so essentially in our time function we don't need to iterate through all the N times so it's very important because we can use the same concept later on to make our solution better okay so let's say I have the number 20 okay so its multiples are going to be well obviously 1 times 20 right times one so the same thing just got repeated right so essentially my point here is if we just look at the first three pairs we do not have to look at the other three ten times two so if you look at 2 times 10 we don't need to look at 10 times 2 again so essentially we can break out of our for Loop a lot earlier so how exactly do you know when to stop so essentially you take the square root of n so in this case the square root of 20 that should come up to 4.4 something so that should come up to 4.4 something so that should come up to 4.4 something so let's just you know take the integer value of that which is 4 and we're going to iterate through all the values up to four so essentially we're going to look at one two three and four so now instead of looking at n values we're only going to look at square root of n so now our brute for solution is now going to be n times square root of n in terms of time complexity so let's just look at our Brute Force solution and then I'm just going to show you how we can improve the same thing so this over here is going to be the Brute Force solution of very straightforward we iterate through all the numbers we pass each number to the is prime function if it is prime it's going to return oh sorry it's going to return true it's not prime returns false and based on that we're going to add that to our results so if it's Prime the result is going to get incremented by one and at the ending we return our result now the obvious problem with the solution is that the time complexity let me just go back here it's still gonna we still have to go through all n numbers right uh and each time we're doing an additional square root of n operation well this used to be n we got it down to square root of n so it's still better right but let's actually see how we can improve this okay so I'll be showing you an example with a larger number so n is equal to 20 and the reason for that is because I think it'll just show the algorithm better right okay and one more thing I want to tell you is that this algorithm that I'm showing you is a very popular well-known algorithm I'll give popular well-known algorithm I'll give popular well-known algorithm I'll give you the name later on but my point is you don't need to really know the algorithm to kind of come up with a solution right so far what we've seen is we've had a iterative approach so what we can try doing is we can try using dynamic programming and that's what we're going to do so essentially what are we going to do in the dynamic programming approach we're just going to check if something is a prime number or not now the entire purpose of dynamic programming is how can we use our previous results for the future or vice versa right and the idea is very simple what I'm going to do is say I'm at the number two right so let's say two hat is either prime or not I don't know yet but a very simple thing I can do is that all the multiples of two in the future four six eight so on and so forth are not going to be prime numbers it's just impossible right because for it to be a prime number the only factors could be one and the number itself but if two is already a multiple that means that well this is not a prime number right that's it so that is what we're going to do we're going to go to a number and then we're going to remove all of its multiples cool so let's just look at how this is going to work so let's just make 0 and 1 default values to be false for now and there's a reason we're doing this which I will explain later on so the number two is it prime or not well the easiest thing we can do is we can just pass it through our function okay so if I'm calling the function I'm just going to underline it cool okay so 2 is going to call the function is it Prime well it is so that becomes true but we also now have a lot of extra information which is the fact that all of its multiples are automatically become false that's it okay so that's pretty straightforward now essentially what this means is so let's just do one more so three I don't know three as well so call the function uh well 3 is Prime and all of its multiples so six 9 12 15 16 um sorry not 16 18 are all going to be false that's it so now when I go to the number four I don't need to call the is prime function again I'm done right because this value has been set to false it's done that's all I'm going to be doing so essentially with this kind of method or intermediates that we reached the number of times we call is prime is drastically going to decrease okay so the number five we're going to call this Prime that becomes true this also becomes true uh same over here so at five we would remove the multiples so you remove 5 10 15 cool then you have 13 is also true so is 17 is also Prime and so is 19. so now the number of True Values you have over here that is going to be your answer that is just going to be the number of prime numbers less than the number n so now we've kind of made better right by the fact that we're calling the is prime function a lot lesser now which is still faster right but we can actually make this a lot more better okay so in the beginning the number two is going to be true so let's start off with the number three okay and obviously it's multiples it's going to be false I'm just not showing that for now so I'm at the number three and what are some things I could get out of this right so if I'm at the number three what that means is all the numbers prior to it have already been visited and all of its multiples have been changed to false so that means that before the number three the number zero one and two have been visited and all of its multiples have been turned to false okay now obviously I'm not counting zero and one and why is that well the multiples of zero and one are going to be everything right so one will give you will make everything fall which makes no sense so zero and one by default we're just going to leave it as false okay because if we did the same method everything would just end up being false Okay cool so now at the number three so that means I've experienced or I've went and explored the number two and when I explore a number that means that all of its multiples are gone so essentially what this tells me is that since the number three does not have a value of false and since all the values before it have removed its multiple submitted faults the number three has to be a prime number that's it okay so now since 3 is a prime number we move we remove um so six uh then we would have nine will become false so with 12 so with 15 and so would 18 right so now let's say I go to the number five okay now at the number five I do the same thing how do I know if the number 5 is prime well I don't want to call the function but essentially so far what does it mean I've explored the number 0 1 2 3 and 4. and so far after exploring all the numbers prior to five the number five itself okay the number five itself still does not have a factor it still does not it's still not false that means that none of the numbers prior to it have five as a multiple so all we do right now is that means 5 is a prime number and we change its multiples that's it so now we don't even need the is prime function now we're going to do one more Improvement to this okay so essentially one small thing that we have been doing so far but I just want you to make note of it is the fact that we're only looking at the multiples for those that have a true value and the reason for this is pretty cool so when I'm at the number two well two is a prime number because everything before it was false right that's it so none of its multiples have changed two to be false that's it so two becomes true and by default what we're also going to do by default we're just going to make everything true okay so this is going to be the basic setup and if something is not true that will be change to false that's it so I'm at the number two it is true right because nothing has changed it to false so now I'm going to make all of its multiples to be false okay so I'll just do that again quickly um so that's four six eight ten twelve fourteen uh 16 18 right so that's all of two's multiples now we go to the number three right and same thing three has not been changed to false so that means three is a prime number so now we change three multiples okay so just very quickly six uh 9 12 is already changed uh 15 is going to change and so is 18 done okay now at the number four is already false now the question is do we consider fourth multiples and the answer to that is no and the reason for that is because we're only going to consider the multiples of prime numbers and the only reason for this is because every number so let's just look at Force multiples okay so that's four well that's eight that's 16 uh what else we have 12 and yeah 16 cool right and 20 but 20 doesn't exist in this case so essentially all of these numbers 8 12 16 can be written as multiples of the previous prime numbers of four right so essentially what that means is all these numbers can be their prime factorization can be written solely with the numbers 2 and 3 or only two and only three but in this case since for the multiples of four that's only the number two is enough and the same goes on right so let's say now I'm at the number five so five is true so that would make its multiples false which is only done in this case and now if I go to the number six since six is false let's look at six multiples right so what is that so you have six you have 12 over here and you have 18. so these numbers can again they can be represented with the combination of prime numbers prior to six for the number six itself is just three times two right uh same for the number 12 right it's three times two so these numbers can be written as the prime factorizations of the prime numbers prior to six so there is no point at looking at six's multiples because the previous prime numbers have already considered those numbers so there's absolutely no point for us to do that's it so now the number of times that we actually change the values to both are extremely less it's just going to be the same as the number of prime numbers there are that's it so a lot of the numbers like four or six whichever false we just skip through them we don't need to do anything so this saves us a lot of time right so the time complexity over here previously we had to go through every number we still do but the update is only going to be made on these numbers right so that's about uh half around square root of n so I would I think time complexity is square root of n so again I'm not 100 sure of this time complexity if I am wrong please correct me and let me know but the space complexity in this case is obviously going to be Big O of n in this case because we're using a dynamic programming area of size and so given all this let's see what the code looks like now all right so this is going to be our code so let's just ignore the beginning for now and let's just look at this dynamic programming area right so we initialize our area with all truths and it's going to have a size of N and the zero then first element become false now this condition is very important because we're assuming that the DP array at least has two elements to be able to do this right so if n is less than or equal to 2 we just return 0 right it solves any further problems later as well right with respect to this indexing okay so now we do our for Loop which is we start at the index two and we go through all the way till the ending and over here if the number is a prime number that means that value would be true only if it is true we're going to look at all of its multiples and make it false now one very important thing over here is the fact that for index in range the first number is num times two and the reason is simple so if the first number is 2 right so let's say num is equal to 2 right now I cannot make the two itself false right two is a prime number it has to be true but it's multiples will have a value of false so that means I start at the next number which is just times two so num times two I'm going to go all the way to the ending and the step size is going to be num that's the same as looking at its multiples and those all will have a index value of false and that's it so this is going to be our solution uh let's submit this if I can zoom out there we go uh submit cool and as you can see our submission has been accepted so thanks a lot for watching guys and do let me know if you have any questions thank you
|
Count Primes
|
count-primes
|
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106`
|
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
|
Array,Math,Enumeration,Number Theory
|
Medium
|
263,264,279
|
1,704 |
hello introduction to the video my name is Cameron I'm a graduate Apprentice software engineer currently studying at Glasgow University and I'm using this video as a way to sort of rubber ducky debug a l code problem just attempt to solve it and hopefully it's useful to some on here so the problem going to be attempted today is 174 determine if string halves are alike so just going to read through the spec here you're given a string called s of even length split the string into two halves of equal length uh let a be the first half and B be the second half H the two strings are alike if they have the same amount of vbls uh notice that s contains uppercase and lowercase letters so it could be an uppercase F or lowercase f a return true of A and B are like otherwise return false so s is equal to book so output is true that's because b o is the first half and O is the other half they both have the same F amount of fbl therefore they are I like so H constraints the length is between 2 and a th000 uh the length of s is even and it only contains uppercase and lowercase letters so just going to switch over to my notes Here off the top of my head uh first thing you're going to have to do is split into two halves A and B and then look over H uh and count the amount of those then and both A and B if the amount is the same return true otherwise return false so I'm going to attempt this here just based on what I've written down so we got a we got B so a is going to be equal to we're going to go slice from s the length of s/ by two s/ by two s/ by two to the end and then this is going to be from 0 up until the length of s/ 0 up until the length of s/ 0 up until the length of s/ by two so let's print a and print B uh slice Ines must be and this is must be ERS H these are these are integers need to the floor division I shouldn't need to because is even okay so we have got the two halves correct we've got book and text uh so for element for letter N A if h letter n and then we'll do just copy paste this if it is in this then we're going to do aore vbls canit to buy one and then we're going to do the same thing for B and then down here we're going to do if this is equal to this we're going to return true else we're going to return and that should be us and that's because we didn't Define it up here so re run again both get accepted going to hit submit and accepted so thank you very much for watching the video hope it was useful to you in some way shape or form if it was please let me know um if you had any other sort of solution to this uh please let me know love discussing these problems H and yeah thank you once again for watching and I hope you a great hope you have a great day 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 |
1,816 |
let's say we have the input string my name Jeff and we want to turn it into my name because our k equals 2 we can first split my name Jeff to get each word on its own we split by the space so we break at these two points giving my name Jeff then we can splice the array that we just got up till K getting the first two values which is what we want and then from here we can join it back by adding a space in between each array element through a join so the empty space and then join this array that will look like one line with a join on Space of the split by the space up into the kith element my name j
|
Truncate Sentence
|
lowest-common-ancestor-of-a-binary-tree-iv
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces.
|
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,236,1218,1780,1790,1816
|
1,678 |
that can interpret the string command in the string in the graph the command consists the string consists of an alphabet g open and closed round braces and or within round braces a l and a word in from order okay the gold passer will interpret g okay as the string g around basis as the spring go okay and within around which is a last b string right okay double braces right decorative on the replace it with replace okay similarly this uh wrong basis for plastic no then we have to replace it here okay replace it yesterday i think our interpreter is successful jc return gesture i think we are good so we will go and solve the problem okay define function differentiation and interpret a function definition command and a string input it is coming to the argument declaration of the command on the string to replace yes and straight it's dot replace okay so command dot replace function uh syntax internally a word method represent the number okay we want to see it as here right then they pass this number which are called as parameters okay so e parameter mean we are replaceable so i'll start i will run this code in errors you can see name always yeah that's one error okay i have to give within double quotes okay string copy single quotes and i watch it then the other thing is we have to return this string okay another question finally we decided to microseconds faster than 54 percent of submissions it depends every time your time to submit to someone our time law you mean kept them on somebody just know that about two times but as long as you are successful uh lead could actually just be that's a good enough criteria for us okay simple problem so i hope this was useful okay like share and subscribe channel i will meet you in the next video thank you for your time
|
Goal Parser Interpretation
|
number-of-ways-to-split-a-string
|
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
|
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
|
Math,String
|
Medium
|
548
|
1,235 |
welcome to august leeco challenge this problem is called maximum profit and job scheduling we have end jobs where every job is scheduled to be done from start time to end time i obtaining a profit of profit i you're given a start time and time profit arrays return the maximum profit you can take such that there are no two jobs in the subset with overlapping time ranges so this kind of reminds me of a lot of interval problems we've seen if you choose a job that ends at time x you'll be able to start another job that starts at time x so it's inclusive uh here with this example we can see it the maximum profit we can make is 120. we can take job one skip jobs two and three and just go straight to job 4 and that's going to be our maximum profit here so they do give you a couple hints they tell you to think dp and they tell you to sort the elements by starting time and then they say define this dpi as the maximum profit but really i don't really think it's good to think in terms of this what we're going to do is think more like a path we're going to sort our arrays by the starting time what we're going to do is start at the very first job and we basically have two choices we could either do this job and take the next job that comes directly after it in terms of the start time so we want to find the first start time that comes right after the end time of this job or we can just skip this job and take the one that directly comes after we can take job 2 and just continue down that algorithm so it's almost like a depth first search in a way and if we do that's going to end up becoming like n squared so i think that should work let's start by doing that what we're first going to do we'll do a couple steps here we're first going to combine all our arrays okay i'm going to use that zip function to do that second we're going to sort by starting time and then we're going to write a helper recursive method which basically takes two choices either first job plus the next job that comes after the starting time so next job with starting time something like that or skip this job and take the one right after all right so let's first start um what we're going to do is actually i'm just going to get the length of start time that's going to be and this should be the same for all three of these next let's combine these and call this jobs and what we're going to do is use the zip function we're going to combine start time and profit now the reason we need to zip all three of these is because we want to sort it by starting time right but we start starting time we're going to lose the order of end time and profit so we can just combine these all together so that we can like sort it all together i'm going to have to make this into a list and then sort it and this will sort it by the start time okay now we want to write a recursive method here first get these comments out let's see recursive and we're going to pass in the index number let's see so our base case is if i is equal to n we just return zero because there's no profit to be taken we're done so now we have two choices right we can either take this job and take the job that comes after it in terms of the starting time so we're actually going to do that in a while loop so let me think about this for a second uh let's see so i guess we'll call this one and one would be equal to well the thing is we need to first figure out what is that next job that's going to come so let's see while the next job in theory should be you know i plus 1 but it might not be because there could be an overlap right so we'll have to say okay while j is less than n and let's see jobs i zero so this is the end time of the job that we're currently on we want to make sure that it's less or equal to the jobs of j start time here if it isn't we're going to increase our j all the way up to the point that it's that next job so one is basically going to be let's see jobs of i and the profit that's two right plus dp of j or not db i'm sorry recursive of j or we can just skip this all together and just go recursive i plus 1. finally at this point where you have to return the max between these two and make sure to do a lru cache here which is going to make sure that we memorize and we're not going to have to do any repetitive calls okay so all we have to do then is just return the recursion starting with zero right and let's make sure this works okay so that didn't did not work um let's see what that mess up here so while json n end time oh right this is if it's greater than we want to increase it otherwise we're not going to increase it so my mistake all right so let's go ahead and submit this okay so that does work and that's going to be n squared solution um and we do have x n squared space here because of our recursion we could improve this and they give you that hint right here by saying do a binary search instead of this while loop which is going to be whole n what we might do is instead just do a binary search and check to see what the next one comes right after but if we want to do that means we have to sort our start time here let's sort start time and get rid of this but j will not equal bisect left of start time and we're gonna get let's see jobs of i one i believe that should also work and this would also work this would be n log n because of our binary search here although we sorted again at this point so this is kind of repetitive you could certainly create another array with the start times in order i just have to do this because it was hard for me to figure out like how to do a binary search here on our job so we had all those you know tubals in there so all right hopefully this helps i hope that explained it well thanks for watching my channel remember do not trust me i know nothing
|
Maximum Profit in Job Scheduling
|
maximum-profit-in-job-scheduling
|
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104`
| null | null |
Hard
| null |
450 |
hi everyone it's sorin today we have a problem when we are given a binary search tree and the key and we need to remove from the binary search tree a node with that key so for example in this case we are giving this binary tree and the key is equals to three right and we are removing three and we get this binary tree updated binary tree with the without node three okay let's take a look at our first example in the first example we have this binary tree and our key is equals to 50 so what we are going to do we are going to implement DFS algorithm and we are going to search in our tree but when we are searching it's a binary search tree so since it's a binary search tree all the values of the nodes on the left is less than all the values of the nodes on the right so we are searching for f 50 first we are searching starting from the root if the root is value is more than if our key is more than our root value which is more than 40 in our case then we are searching for our value on the right side of the binary tree for example in this case right so let's say that uh we are searching now not we are searching now on the right side of the sub tree here for our value and um then the next one is we are searching the 50 is equals to 50 so what we are going to do in this case we are going to if the let's set up our rules our first rule is that if we found our value so what we are doing if our left in this case if our left is equals to null right equals to null which is equals to null in the in our case then we are returning right so basically in this case we are our left is equals to null right so we are replacing that with our right so we are returning right here we are returning right and the same way we are doing with our right if our right is equals to so let's say that it's a vice versa if the right is equals to null then in that case we are returning left okay let's take a look at the one more example our key is again equals to 50 and we are starting to search for our node to delete so since the 50 is more than 40 our root value so we are searching for our node on the right side of the sub tree so 50 is equals to 50 now we need to remove 50 and replace it with one of these nodes but with which note we are going to replace with the right child right but the which one exactly let's say that we are replacing with the 60 so we are 50 we are replacing with the 60 so we cannot do that because in that case 55 and the 58 will be on the right side of the 60 so which is in that case if the in that case it's not no longer binary search tree right in the binary search tree all the values on the left should be less than all the values on the right so what we are going to do we are going to in our right subtree we are going to find a smallest value the node with the smallest values right so in this case the node with the smallest value so we are doing in order binary search and we are finding a value with the smallest with the node with the smallest value in this case it's a 55 so we are finding a 55 here and we are replacing the value here with the 55 so we replace that what we need to do now so we need to again uh so now our key is equals to 55 now we need to remove the note with the value of the 55 so our key is becomes 55 now we need to remove starting from the right node right so we are recursively calling our right root of the we are calling our right sub tree with the keys being 55 and we are removing our uh we are removing our node so again we are searching and the 55 is less than 60 so we are searching on the left side of the sub tree 55 is equal to 55 and the left is equals to null so if the left is equals to null so we are returning right so it means that the this value right becomes 58 and this node is no longer valid so that's how we are performing so that's how we are progressing in our algorithm so we can put here our second rule is that if our left is not equals to null and if our right is not equals to null so what we are doing in this case we are finding a we are doing inorder trat reversal and we are finding a node with the smallest value not with smallest value and we are removing value smallest value and we are removing that from our we are replacing that with the value of our node and then we are recursively calling again the right sub tree with the key is being the one that we have just replaced for example in this case we have replaced with the 55 we are calling our right sub tree and with the keys being a 55 because we have to recursively remove the 55 in this case okay the first thing that we do here we are checking one Edge casee if our root is equals to null in that case we are just returning null the next one is that we are checking if our key is less than our root value so since it's a binary tree we are going to search for our value on the left side on the left sub tree if the value is if the key is more than our root value so then we are going to search for our key on the right side of the subt tree for example that the example in the example that we have seen earlier that's on the right side of the sub tree if the if it's not less than or more than it means that it's equal so we found our key so what we are doing in this case if the left is equals to null right so in that case we are if the left is equals to null then in that case we are returning the right so if the right is equals to null then we are returning the left if the if our key has if our note has the right and the left and right sub three so what we do in that case so we are recursively calling and we are finding the minimum value on the right side on the right sub tree so for example in this case we are we have a separate method for it and we are taking the minimum value and we are recursively calling while our left is equals to null and we are finding a minimum uh in order successor and we are returning that value and after returning that value so now we have replaced that value so now we our root value for that the for the key that we have found we are replacing that value with the minimum value that we have found and then we are recursively calling our delete function now with the root right so for the right sub tree and we are looking for the right sub tree for the value that we have just replaced for example in our case it was 50 right so we have replaced that with the 55 now on the right sub tree we need to find the root we need to find that node with the value of 55 and then we need to remove that and after that we will recursively call we will recursive the call again root delete Noe function and at the end we are returning our root so what's the time complex in our case it's um Min search Tre so on average it's a log of n but in the worst case it's going to be uh n and for the space complexity is determined by the size of the our stack by the size of the recursion and it's going to be again log of n on average and in the worst case it's going to be uh off n okay that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
|
Delete Node in a BST
|
delete-node-in-a-bst
|
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_.
Basically, the deletion can be divided into two stages:
1. Search for a node to remove.
2. If the node is found, delete the node.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 3
**Output:** \[5,4,6,2,null,null,7\]
**Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST.
Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 0
**Output:** \[5,3,6,2,4,null,7\]
**Explanation:** The tree does not contain a node with value = 0.
**Example 3:**
**Input:** root = \[\], key = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* Each node has a **unique** value.
* `root` is a valid binary search tree.
* `-105 <= key <= 105`
**Follow up:** Could you solve it with time complexity `O(height of tree)`?
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
791
|
470 |
welcome to august lee code challenge today's problem is implement rand 10 using rand 7. given a function ran 7 which generates a uniform random integer in the range of 1 to 7 write a function rand 10 which generates a random integer in the range of 1 to 10. do not use any random libraries and they give us some examples so they're already going to give us to us a function rand 7 it's predefined and each test case is only going to be given one argument which is the number of times our function ran 10 is called so at first this sounds pretty simple it might be tempting to think well we have our rand 7 function why not just call it twice add those two numbers together and return it if it's uh less than or i should say less than or equal to 10. otherwise we can just run it again and keep continuing that but that's not going to work because it's actually not random it's not uniformly random because let's say you had a six-sided die right let's say you had a six-sided die right let's say you had a six-sided die right and i asked you hey create a function that's going to give us a number between 1 to 12. well with a random die it is random right one through six is gonna be random and you might think well okay i'll just roll it twice and then i'll give you the number that adds up i mean that doesn't work though because first off it's not gonna be one through twelve it's gonna be 2 to 12. and more importantly each one of those summed numbers actually has a different probability like anyone would know that 7 has a greater probability than the number 2. and that's kind of a weird thing that happens with the sort of probability questions it's not that easily you know additive so what can we do instead well let's think about like if simplifying this version if we had a coin and it could be heads or tails let's say i asked you uh use this coin to return a probability between three so if we flipped a coin it would be you know heads or tails so it's two pop two outcomes if we flipped it twice there would be four outcomes right if we flipped it three times there would be eight outcomes because um this would be like heads tails heads that'd be four outcomes and it would continue on like this exponentially 8 16 32 64 and just on and on but here's the issue none of these things are dividable by three so getting the perfect probability no matter how many times we roll or flip our coin or use this random seven function it's never going to be a perfect probability of 10. all right so we need to forget that's not gonna ever work how about this though let's say that we created a matrix and in that matrix we'll have one row that's going to indicate to us the first let's say roll and second row will be just everything like between here uh the second roll and so on and so forth like what we can do is attach a number between one through ten for each one of these columns and matrixes so we'll say one two three four five six seven and the next one we'll say eight nine ten and then we'll start over one two three four and we'll go through that whole matrix but that initially you might think well that's not going to equal this is going to be 49 cells and we need a perfect probability of you know one through 10 right so how is that going to work well it can't it can never work um so what we'll just have to do is if we reach above a certain threshold if we reach above let's say 40 we'll just have to reroll and do it again and just keep doing it until eventually you know realistically we will hit something that's going to be in between here and that will be random that will be in the range of 1 to 40 and that's going to be uniform between 1 through 10. so let's start to code this out it'll start to make sense as i code it so first i'm going to create this matrix i'm going to do it in a an initialize definition and we'll just call it table and this will be a list first we'll say none for blank in range of seven and we'll make that nested like this all right so now we have our table and what we'll do is say four row in range of seven and four column in range of seven we are going to make the self.table we are going to make the self.table we are going to make the self.table row seven equal to a number that we're going to be incrementing and thing is we'll have to use a modular to take kind of take care of what we're doing and so we'll say modular 10 and we'll start with n equaling 0 and so i'll be zero through nine and we can just add one afterwards um that's not a problem and we'll just increment n like this so let's print out our matrix and see what that looks like i'm going to pass here so that doesn't error and let's just make sure this looks like it's supposed to okay so it's looking pretty good let's take a look at this and let me show you this is our matrix right and we see it's seven by seven and all these are going to be between zero to ten well zero through nine which is we'll just make that one through ten the only one that's going to be a concern is from this row column to this row because this is not uniform right so what we'll do is we'll roll twice and if we hit well if row first if row equals 6 then we will just try again we'll continue or if row equals 5 and column equal is greater or equal to what four so four zero one two three four nope uh greater or equal to five yeah so five six then we'll start try it again so we'll use this kind of condition to see if we need to roll it twice all right so now we kind of know what we need to do what we're going to do is say well we'll do an infinite loop while true let's roll for our row we'll say uh rand seven oops and for a column with rand seven and we'll actually need to subtract one here because it's zero indexed that's no problem though and if row equals six or row equals five and column is greater or equal to five then we have to do it again because that's not going to work otherwise we just return from our self.table the self.table the self.table the row and column and this actually does end up becoming uniform now let's make sure that i didn't make any typos of course i did rand is not defined oh rant seven okay let's try that i'm so silly i put in the number there okay so please work this looks like it's working let's submit that and what did i do wrong oh of course you need to add one forget there's gonna be no tens right now okay so okay there we go that's accepted now i've realized this is a very roundabout way of how i explained it because you could uh do some one-liners to simplify this some one-liners to simplify this some one-liners to simplify this um but in order to understand why this works i really think it's important to get this matrix in your head once you do that you could probably simplify this a lot more but the basic logic is going to stay the same like you could have definitely avoid creating this matrix and save some memory but this is probably the only way to actually get it to randomize 10. so i hope that helps thanks for watching my channel and remember do not trust me i know nothing
|
Implement Rand10() Using Rand7()
|
implement-rand10-using-rand7
|
Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API.
Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`.
**Example 1:**
**Input:** n = 1
**Output:** \[2\]
**Example 2:**
**Input:** n = 2
**Output:** \[2,8\]
**Example 3:**
**Input:** n = 3
**Output:** \[3,8,10\]
**Constraints:**
* `1 <= n <= 105`
**Follow up:**
* What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function?
* Could you minimize the number of calls to `rand7()`?
| null | null |
Medium
| null |
1,637 |
hi everyone welcome back to the channel and today we're going to solve lead code daily challenge problem number 1,637 widest vertical area between two 1,637 widest vertical area between two 1,637 widest vertical area between two points containing no points so we're going to first look into the problem statement then we'll follow it up with the approach which we going to use and at the end we'll have the code and the code will it most be of four to five lines of code so let's just go through the problem statement first so they have said that given an in points on a 2d planes where point of I have x coordinate and y coordinate return the widest vertical area between two points such that no points are inside the area Okay a vertical area is a area of fixed width extending so they have basically explained what a vertical area is what is the widest vertical area so you know as the name suggest vertical area is the area on XY plane for example in this uh image this is a vertical area Okay uh this blue and red colored area is a vertical area and we have to find out the Fest vertical area for the given points okay note that on the edges of a vertical area are not considered including the included in the area okay so now what we can do is we can simply follow or simply use the Sorting method to solve this problem for example let's say this uh this is an example right in which we had these coordinates 31 9 0 1 014 5388 okay the these were the coordinates we have now I have plotted the uh plotted kind of a graph for these coordinates as well okay and as you can see uh we don't have to do anything on with the y-axis values right we don't with the y-axis values right we don't with the y-axis values right we don't have to do anything with this with these values so we need not to care about these but the points on the x-axis is our main uh like you know x-axis is our main uh like you know x-axis is our main uh like you know where the main logic lies so what if I sort these this array this given array on xais that is the first value of each sub array okay and try to find the largest G between the two between two consecutive uh X values for example over here what I have done I have sorted uh these values on xais basically zero index element okay so now we get this 1 0 1 4 3 1 5 38 8890 okay now what if I just find out the difference between this value and this value okay now next one will be uh three and one after that three uh five and three okay now 8 and five and so on so forth so by doing that we'll get our value and what we can do is we can keep a variable to store the values for example we can initialize it with zero and as soon as we check anything for example we checked 1 one right so now Max will be equals to Max of current value and uh xais at index I minus xxs X index IUS one okay this is what we can do right so coming to the code as you can see uh what we doing over here is like we have sorted the points like the value the array which we have received on zero index elements that is the xais element basically okay or x coordinates we can say and I have initialized my uh variable in which I'll be keeping the maximum width with zero right next what we are doing we just simply iterating all the indexes and in points so just for Simplicity you know just to not handle the edge case of having zero element I have started the iteration with index one till the last element and what we are doing in this for Loop is we just keep on updating the mix width with e like whatever the maximum of current Val current Max width value and the points we discuss that is uh x coordinate of current Point minus x coordinate of the previous Point okay so this is what we are doing and at the end we just simply return the max width let's check out the test cases and as you can see the test cases got clear let submit it for further valuation again and as you can see the solution got accepted and we have outperformed 100% of the submitted solution so yeah 100% of the submitted solution so yeah 100% of the submitted solution so yeah this was it gr this was the complete solution I hope you like the video thanks time for watching other video and stay tuned for the upcoming ons thank you
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
279 |
hello everyone welcome to day 14 of october lead code challenge and today's question is perfect square in this question we are given an integer n we need to return the least number of perfect square numbers that are need to be clubbed together so as to sum up to n and let's take an example here the value of n that is given to us is 12 uh if we add four three times then it will result in 12 and the answer becomes 3 because we are using 3 perfect squares to combine them to form 12. let's take another example where n is given to us as 13 then the 2 perfect squares that we are gonna choose is four and nine and uh if we sum these up we'll get 13 the output becomes two without much to do let's try and look at the presentation that i have created for this and let's get started with the solution perfect squares lead code 294 it's a medium level question on lead code and i somewhat feel the same also i have observed that in the month of october we are getting slightly easier questions in comparison to the past months august july september june and it feels like they have reduced the level of complexity for these questions let's start the algorithm let's hypothetically assume that we are given the value of n as 13 so what we are going to do we will go and create an array that will store the minimum count of perfect squares that are needed to generate each number in this input array one two three four five six up till thirteen and what we are gonna do we will try and build uh the answer for each of these numbers starting from one so at one we are already aware that there is only one possible way so we'll go and write one here let's move the pointer to the next iterator we have two now when i iterator is pointing to two will create another for loop starting from j equals to 1 till the time my j square is less than equal to i which i in this case is 2 i will continue the operation so let's start the operation for the g hydrator j points to 1 into 1 is less than equal to 2 that's correct so we'll continue the operation what we are going to do we'll calculate the dp of i minus j into j which is dp of 2 minus 1 into 1 which is nothing but 1 so it turns out to be dp of 1. so the answer becomes dp of 1 plus 1 dp of 1 is 1 and we have a 2 there the previous value that was stored at this particular index was infinity because we initially filled all the values with infinity sorry i missed explaining this point and now we can see a better value which is 2 so what we are going to do we will replace infinity by 2. let's move the gi trader to the next pointer and here j becomes 2 j square which is 4 is not less than equal to 2 will abort the process let's move on for the next iteration which is three so i now points to three and let's start the iteration for all the possibilities of j starting from 1 so let me just change the color of pen and now j becomes 1 and the initial value that is stored here is infinity for j equals to 1 square is less than equal to 3 that's correct what we are going to do we will compute this value which is nothing but dp of 3 minus 1 square which is 2 plus 1 so dp of 2 turns out to be equal to 2 and 2 plus 1 is 3 so we got a possible answer which is 3 so what we're going to do we'll replace it by 3. let's go for the other possibility we have j equals to 2 j square is 4 is greater than 3 we need to avoid the process let's continue this for the next possibility of i so since you avoided the process the i pointer increments to 4. let's continue the process and let's start the iteration the initial value that is stored here is infinity and uh the initial value of j is one so what we are going to calculate we will calculate this expression dp of 3 4 minus 1 is 3 so this turns out to be equal to dp of 3 plus 1 so we got one possible answer as 4 so 4 is better than infinity will replace it by 4. let's continue the process j now points to 2. j square is 4 is less than equal to 4 i am talking about this particular condition but it still holds true what we are going to do will calculate this expression for j equals to 2 that turns out to be equal to dp of 4 minus 2 square is 4 so dp of 0 is 0 we know this and we'll add 1 to it corresponding to this value and this turns out to be equal to one so one is greater than one is lower than four so we'll replace this by one so we have filled in one two three one and filled in the first four values let's do it for few more and then you can complete the entire table by yourself let me just use another color pen now i points to 5 so what we are going to do will start the iteration and the initial value held is at 5 is infinity j points to 1 so it turns out to be equal to dp of 5 minus 1 square which is 4 plus 1 which is nothing but dp of 4 is 1 plus 1 is 1 2 so this gives me 2 so let me just replace infinity by 2 let's continue the process next i point j to 2 what is the expression that i'll get dp of 5 minus 2 square which is 4 so i get dp of 1 plus 1 will give me the complete expression will be the complete expression dp of 1 turns out to be equal to 1 plus 1 is 2 so this again leads to 2 is equal to 2 i'll not do any replacement let's continue the process next i move the pointer of j to 3 j square is 9 is greater than 5 we have to avoid the process let's move on to the next iteration of i and here i turns out to be equal to 6 let's start the possibilities starting from j equals to 1 so let's start it here itself the expression will turn out to be equal to 6 minus 1 square which is 5 so dp of 5 plus 1 dp of 5 is 2 or 2 plus 1 is 3 so we have to replace infinity by 3 because 3 is lower let's continue the process next we have j as 2 square is less than 6 that means we have to evaluate the expression would be equal to something like dp of 6 minus 4 plus 1 dp of 6 minus 4 which is dp of 2 db of 2 is 2 so 2 plus 1 is 3 so 3 is equal to 3 we will not do anything the answer stays as it is let's continue the process now j turns out to be equal to 3 square happens to be equal to 9 and 9 is greater than 6 so we'll avoid the process and in this way you can continue it for the rest of the elements you can try this logic yourself and you will observe that at 12 we will get we will use a dp of 8 which will be equal to 2 and dp of 4 which will be which will give us 1 so 2 plus 1 gives us 12 so these will be the two indexes that we are going to use for evaluating a dp of 12. just remember this please go and try this up it will help you more clarity give you more clarity with respect to this now let's look at the coding section uh the coding part is pretty simple and straightforward here i created a new dp array of size n plus one because i the in index rs the index in the rs starts from zero up till n and i initially filled in all the values with dp of integer.max value i explicitly integer.max value i explicitly integer.max value i explicitly initialize dp of 0 to 0 and let's start the iteration for i equals to 1 i is less than equal to n i plus iterating through all the possibilities of i and i signifies all numbers starting from one up till n i check uh with the help of a loop so j equals to one j square is less than equal to y the main statement of the solution is this one where dp of i is equal to max dot min the minimum value out of the current value that is held at dbfi comma dp of i minus j square plus 1 you're subtracting and checking the value at i minus j square and since we are doing this you need to explicitly add 1 to the answer because j square is a perfect number in the end you simply return dpr n let's try this up accepted run time is 73 percent faster which is pretty good this brings me to the end of today's session uh i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
859 |
hey everybody this is larry this is day 12 of the leeco daily challenge hit the like button hit the subscriber and join me in discord i hope today i'll recover from yesterday's uh just tiredness um so i am doing this live so sometimes i don't get it all like immediately all the time as opposed to explanation video i always find that the learning is in how you mess up sometimes it's important to uh learn from how you don't get it right but well we'll talk about that later hopefully you know how this goes anyway today's problem is buddy string uh given two strings a and b of lowercase letters return true if you swap two letters in a so that resource would be otherwise run force okay so it's almost like i think this is straightforward because there only could only be two right so you need two things that are out of place maybe i think i have to think about all this for a little bit because i think so the one thing that maybe uh the only case that i have to kind of consider a little bit better uh because okay so i think if you have only two characters out of place then it's straightforward and that's straightforward implement i think the case that i have to kind of prove to myself is something like this um now i guess it's still two characters out price right so that should be straight uh yeah okay so then i think that should be okay yeah okay let's get let's just implement it right if we have two characters out place then you know it's good so for uh let's see let's just do x y in sip of a b uh if x is not equal to y let's just have a list of um incorrect things in correct as you go to a list of array then we just incorrect dot append uh let's just do it x y and then well one is if we have more than two then that's already wrong right so if length of incorrect is not two then return first because even if you have one up place what does it mean to have only one price right it means that uh or if they're not match it means that there's one that doesn't match right so we need two and they need to be kind of uh you know to get in this um i think there may be another tricky case uh where okay so you have to swap them so yeah so length has to be equal to two so i was worried about this one here but there may be another case where okay actually they give you a lot of cases i was just thinking about these without really looking at the test cases but i think those are the only ones where this one in theory the serial numbers are placed but their ways to kind of swap two numbers where you could swap it to each other so we might have to kind of play around with that idea um but hmm so i think those are all the cases they tell you all the test cases which is very polite of them very kind of them uh huh and i think this is other one is that if incorrect of zero is equal to incorrect of one and uh this basically we're just in a brute force way writing you know that's true otherwise this is just force right because then that means that they have different things so we can actually just return this okay but as we said we have to add some conditionals we either before during this where you know if they all if it's someone like this or even someone like this then you know then we could we should be able to swap two characters that way and the only case that this could be true is if um well first of all the length has to be the length of the incorrect which means that uh there has to be two uh no things out of place and then if any of the characters appear more than once then that's all you need um and i'm kind of lazy okay fine um i guess we could put it in this as well which is that uh c is to go to co elections dot counter and i know that you could do it when you know you could put a in here for example but i just want to put it in the same loop uh which is that c of x uh plus equal to one right and we only have to care about uh the strings in a first yeah uh so if this is zero and any of um so okay so basically if any value of this is greater than uh one then we're good because then you just swap it with each other right okay so then we could express it that way with a c dot values so x for x is greater than one man this these are not this is not syntax sorry for if x is greater than one um then this is true okay let's just want to real quick for the syntax i have a type of my syntax oh oops uh and then now let's go for all the cases there's a lot to type here so bear with me um i could also copy and paste but i'm not sure that copy and paste is any faster at this point um except for maybe for longer ones and the other ones just they really gave you all the edge cases i was actually going to go for it uh without looking at mostly because usually i don't look at the examples if i understand it quickly uh just because i'm already doing it but it seems like it matches these cases at least um let me think for a quick second what other cases there could be uh i guess the one index like do and then just zero index matching uh and maybe just one index where it's wrong or not wrong it's different uh it looks to be okay so let's give it a submit fingers cross uh whoo cool so what is the complexity of this well we look at each character at least at most once so that's going to be all one uh i actually could optimize this a little bit if you pay attention which is that technically i use of n space here but you really only have to keep track uh but depending how you want to count it because this is only gonna uh have at most 26 characters uh you could have done it another way but this is going to be i mean at most 26 characters which are the number of lowercase characters so that's going to be all one space if you want to count that way uh incorrect can actually be o of n uh in linear space but if you just add something like an incorrect uh is less than three or something like that right uh because all you care about is that it is exactly two so if it's three or more uh then you can append it right so that it becomes three which is that and you don't care about it and in this case you can show that incorrect it's also all one space because it's at most it has six oh sorry that's three elements of two elements each so it's just six uh elements so yeah so this is so you can what i'm saying is that you can solve this in all of one space and it's gonna be linear time because uh we look at each character at most once here uh we look at another linear time here and everything else is all one right so linear time constant space and that is the problem i'm glad i actually saw one quicker than yesterday uh let me know what you think about this one uh it's a little bit easier than yesterday's but uh yeah hit the like button hit the subscribe button join me in discord let me know how you feel uh and i will see y'all tomorrow bye
|
Buddy Strings
|
design-circular-deque
|
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._
Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`.
* For example, swapping at indices `0` and `2` in `"abcd "` results in `"cbad "`.
**Example 1:**
**Input:** s = "ab ", goal = "ba "
**Output:** true
**Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'b' to get "ba ", which is equal to goal.
**Example 2:**
**Input:** s = "ab ", goal = "ab "
**Output:** false
**Explanation:** The only letters you can swap are s\[0\] = 'a' and s\[1\] = 'b', which results in "ba " != goal.
**Example 3:**
**Input:** s = "aa ", goal = "aa "
**Output:** true
**Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'a' to get "aa ", which is equal to goal.
**Constraints:**
* `1 <= s.length, goal.length <= 2 * 104`
* `s` and `goal` consist of lowercase letters.
| null |
Array,Linked List,Design,Queue
|
Medium
|
860,1767
|
496 |
hello friends now let's of the next greater element one problem is firstly a statement you are given to a race without duplicates numbers 1 in numbers to where numbers wants elements are subsets of numbers to find all the next greater numbers phone numbers ones elements in a corresponding place of numbers to the next great number of number X in numbers one is the first great number two is right in numbers to if it does not exist output negative one for this number let's see the example the first number is 4 so we find the four in the numbers 2 is here and then we go right to find whether there is some elements that is greater than 4 there is no so we return negative 1 the next element is 1 then we find that the one in the numbers 2 and we go right we find the 3 is greater than 1 so we return 3 and then we find there chewing numbers too but there are no elements on its right so we return negative 1 so as you can see we need the 2 first Pro processing numbers 2 because we needed to find the element in numbers too so maybe we need a data structure to solve the elements the next great element with the risk with the number respectively in a data structure and the bester their structure I think is hash map for every elements in numbers too we record those an element under its nest great elements in the map so when we needed to generate the result we just needed you for every element 2 we capture that next great elements in the map because every elements in this num in these arrays are unique so how to press so the key point of this question is to probe processing pre-processing the numbers - processing pre-processing the numbers - processing pre-processing the numbers - how do you get a next great element the brute force solution should be for every element we go it's right to check whether there is some element a great date if there if we find some element of greater than that number we just record that number to the map but we can have a better solution and you can see if we have find this next great element for every element then it shouldn't be like increasing which means it extending so can we combine all these extending like pairs or sequence we may think about using stack because this question is a classic question for using stack basically we have a two choice one is processing these numbers - from left to processing these numbers - from left to processing these numbers - from left to right another way is from right to left I think a from right to left is easy understanding so as you can see folder number two because there are no elements always right so we return active one and then we will put the index of a number of these two into the stack because it can be the candidate her next great element over its left her elements then we process this four and we compare this for with the stack like we first compare this fall with the peak of the stack if the peak of the stack is less than is the less than this - we just pop that element because if - we just pop that element because if - we just pop that element because if the elements intersect is less than the current element it can never be the Canada result of the other elements always left because if some elemental on the current two elements have some next great element it is should at least a business fall it can never be there elements less than four oh it's right so as they keep heart and then we maintain extending sequence in their stack like it again it'll should there be the stagger should there at first it will be three because we saved the index it will be easier for us to get the element we first ourselves three into the stack and then we process these four we know their numbers 2 3 is less than 4 so we'll pop these three and then we save the 2 into a stack there will be 2 and then for these three it is less than the peak of the stack so we just push that into a stack so stack will be 1 2 and then so on so forth we just push that to zero to the stack so the elements in the stack are increasing we can simply get that next great element in the map from right to left ok let's solve it we first activity and is the numbers mm and we need a stack we usually use the deck because it is an interface and is quicker fasters in the stair class so we use array deck as a when the map and the key is the value over the numbers and the value will be the next great element it's a map in a new hash map and we also need a result array and the size should be numbers $1 then we process this be numbers $1 then we process this be numbers $1 then we process this numbers 3 and we start from the right so n minus 1 I quit or equal to 0 I - - so n minus 1 I quit or equal to 0 I - - so n minus 1 I quit or equal to 0 I - - so why oh because every time we want to get a peak of the stack we should make sure the stack is not empty so when the stack is not empty and there and the numbers - is not empty and there and the numbers - is not empty and there and the numbers - I is greater than numbers to stack pick we just a pop kill pop so now we when we out this while loop we only have two cases one case is the stack is empty so we just er know the next great element of the numbers - I is negative 1 and the of the numbers - I is negative 1 and the of the numbers - I is negative 1 and the or there is some elements that is greater than their current element so we know that we put the key will be numbers - I and the very well P we first check - I and the very well P we first check - I and the very well P we first check if the stack is empty then we return active on if not we written numbers - active on if not we written numbers - active on if not we written numbers - there will be stack you pick okay then we generated a result there will be opportunity to push the current index into the stack or we will never just a will ever always be there empty start from zero I less than numbers $1 I plus from zero I less than numbers $1 I plus from zero I less than numbers $1 I plus and the result I will be either map cats numbers well I finally return result okay thank you for watching see you next time
|
Next Greater Element I
|
next-greater-element-i
|
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
| null |
Array,Hash Table,Stack,Monotonic Stack
|
Easy
|
503,556,739,2227
|
118 |
hello everyone out there welcome to solve it out this is Annie here and today I was solving the pascals triangle in JavaScript so thought to make a video out of it and share it with you guys so here you can see this is the Pascal's triangle a question here the DSA question that is given an integer num rows return the first num row of Pascal triangle so the Pascal triangle is basically that each number is the sum of the two numbers directly above as it here you can see the GF working here and also you can see the example here that is first the input will be of uh like five as the number row and output will be given in a 2d array consisting the summation of the pascals triangle so today I'm going to solve it in JavaScript and also for that I'll start with a little explanations and then I'll continue with my code so I'm going to solve the Pascal triangle using the binomial coefficient method as it is the summation of the two numbers it can be easily solved with the combinations method in mathematics the binomial coefficient also known as the N choose K is the number of ways to choose K elements from a set of n distinct elements without regard to the order of the selection the binomial coefficients are really closely related to the Pascal triangle and we'll see how we can calculate it you can see here the Pascal triangle is on the right side that is one then in the next row there is two ones the third row there is 1 2 1 and in the fourth row there is 1 3 1 on the left side you can see if we compute the combination of these numbers that is 0 c0 it will give us the result 1 c0 1 C1 will both give us one accordingly the combinations formula when we are following it a special formula is the binomial coefficient so using this we are going to solve our pascals triangle in JavaScript now here I'm going to start writing the code so first I'm going to take a array because we are going to return here a 2d array so here I'm going to take a array named result initializing with empty array then I'll take a for Loop here okay where I'll initiate a variable name line equal to 1 and then line will be less than equal to the num row that is the number of rows that we'll be taking in the main function and then line Plus+ as we take the for Loop now I'm Plus+ as we take the for Loop now I'm Plus+ as we take the for Loop now I'm going to create a array for each row you can see this is the 2D array like for each row there will be an array so here I'm going to name it const row is equal to new array our array is created next I'm going to take a variable for the combination so I take here C is equal to 1 now next I'll take another for Loop and we'll take a variable of I and I will run up till to the line and then Plus+ I'll start from the line and then Plus+ I'll start from the line and then Plus+ I'll start from the one and as the line increases it will Loop up to the line that is why less than equal to line now here I'm going to set my zero value as the1 I'll give here C you can check here that the zero value of the Pascal triangle is always one that is the first index you can say the first index of the array the value is always one so I'm taking IUS 1 as I is starting from 1 i- taking IUS 1 as I is starting from 1 i- taking IUS 1 as I is starting from 1 i- 1 will be the zero value or the zero index of the array so that will always be one so I'm giving the value as C next I will be updating the C here but C into lus I IDE by I this is the binomial coefficient part where we are multiplying it with c and line minus I IDE by I okay now I'll drew a dry run which will help you to understand how this part is actually working after that we are going to push it to our result array so that it becomes the 2D array and finally we going to return the result now let's try run our code I can take my num rows as equal to 4 okay next so for line number seven you can see our line value will be starting from 1 and then line is less than equal to 4 and the line will be ++ now a row will be created a new array ++ now a row will be created a new array ++ now a row will be created a new array that is an empty array will be created here and then I have taken Cal to 1 now for the next for Loop it is that I will be starting from one and will be running up to line okay now for this one the line is equal to one it will just run for one time now here next a row I have set the row as I - 1 I is 1 now will be 1 - 0 row as I - 1 I is 1 now will be 1 - 0 row as I - 1 I is 1 now will be 1 - 0 sorry 1 - 1 that will be the zero sorry 1 - 1 that will be the zero sorry 1 - 1 that will be the zero index so or row value 0 it will be setting to C that is one okay value Z is 1 now the C value will get updated here e value here will become e into that is 1 into lineus I by I the line here is 1 - 1 by 1 ultimately the answer becomes Z - 1 by 1 ultimately the answer becomes Z - 1 by 1 ultimately the answer becomes Z so here the loop ends and you push the result that is this result in the array finally in the array you push one okay our first Loop is done next the line is equal to 2 line is less than equal to 4 and line ++ we than equal to 4 and line ++ we than equal to 4 and line ++ we initialize our row with an empty array and then we loop from I is equal to 1 I less than equal to line that is two this time and I ++ first it will print the row zero ++ first it will print the row zero ++ first it will print the row zero value that is the zero index of the row value so it will be i- 1 this one is value so it will be i- 1 this one is value so it will be i- 1 this one is equal to C which is one for the zeroth index then the C value will be updated to Z as it is shown for means following this formula okay next the I will increase to two and uh it will reach its end here and it will perform like if the roow first index value and that will be one and c will be updated again equal to zero and in further we'll push this array to our result array so our first element was one and the next array or the next element is 1A 1 as shown in the output or as required there next it will be line equal to 3 we will be initiating the empty row and then we loop from I is equal to 1 I less than equal to 3 I ++ first the roow RO index value that ++ first the roow RO index value that ++ first the roow RO index value that will be one as C is equal to 1 the first that's is equal to 1 then the C value will get updated that is C into lineus I by I okay so here line is three and therefore the calculation becomes two the C value current is two next the I gets updated to two and of course it checks the condition 2 is less than equal to 3 that is equal to line and the road value will now show the first index value so that will be equal to two because that is the that is our current T value or the combination value so that why it's two and then we'll update our C value and it will again become one on I is equal to 3 the row will show the second index value that is the current C value that is one and the C value will again get updated to zero finally we'll push our third row in the result array I guess the fourth step you can understand it easily now let us run this code and check it whether it is working as we have dry rent or not as I click here run see it's running the result up and the result is accepted for both the cases like this is the output the expected output which matches perfectly for case 1 and case 2 and if I submit now you see that this is accepted and it has a 42 millisecond run time well if you check the uh you know the time complexity and the space complexity it is both n² that is o n Square because we are using two Loops within and also it created a array 2D array so it's taking o n square space and o n Square time hope this help you guys because uh there is quite a few um JavaScript BSA videos that I find out in YouTube so hope this is helpful to you all till then see you in some other projects this is Annie signing off today
|
Pascal's Triangle
|
pascals-triangle
|
Given an integer `numRows`, return the first numRows of **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** numRows = 5
**Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\]
**Example 2:**
**Input:** numRows = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= numRows <= 30`
| null |
Array,Dynamic Programming
|
Easy
|
119
|
225 |
hello everyone today we're going to discuss the input daily challenge the problem segment is implement stack using queues here we have to implement the last in first out step using only queues okay the implemented stack should support all the functions of normal stack like push operation top open empty operations so first we will discuss the basic structure of stack let's suppose the stack is of elements one and two if we push element three in the stack will become one two and three right and if you call the function top then it will return what is the top the last element is three right so the top element is three and if you call the function pop then it will pop the last element which is three and it will return the three element and also now the stack is one two three got popped out right and the last function is empty is the stack empty is not right so it will return false okay this is the basic structure of stack so insulation q okay and then we push it one element this one if the size of the queue is one we are not going to the into the for loop okay now the queue is one and if you push the second element the queue becomes one and two the size is greater than one right and now the for loop is executed and the for loop runs like this and it will q dot pushes uh we are pushing the two dot front into the queue and will become one two and again one and we are popping that element so it will become two and one okay and if we put second element three then the q will become two one and three right and now the follow-up is executed right and now the follow-up is executed right and now the follow-up is executed twice and what it does now we are pushing the front element okay now it will becomes two one three and again two and it is popping the front element and then it will become one three and two and the second time after running for the second time it will store the first front element to the back again right one three two and again one and it's popping the front element three two one okay now the queue is like this if we perform the top operation it will return q dot friend what's the q dot friend three right yeah this satisfying is same as stack and if we perform the pop operation it will it is storing the q dot friend which is three into a small variable yes and it is popping out the first element q dot performs the first element is popular right and the queue will become two on one we got popped out and we are returning the s variable it is a power function and this here is empty return dot empty the queue is now it is three now two one right three got pops up and now the queue is not empty so it will return false that's it thank you
|
Implement Stack using Queues
|
implement-stack-using-queues
|
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
* `void push(int x)` Pushes element x to the top of the stack.
* `int pop()` Removes the element on the top of the stack and returns it.
* `int top()` Returns the element on the top of the stack.
* `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
* Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
**Example 1:**
**Input**
\[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]
**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
* All the calls to `pop` and `top` are valid.
**Follow-up:** Can you implement the stack using only one queue?
| null |
Stack,Design,Queue
|
Easy
|
232
|
392 |
hello and welcome to another video today we're going to be working on is subsequence and in this problem you're given two strings s and t and you want to return true if s is a subsequence of T and A subsequence is a string that's formed by the original string by deleting some characters without Distributing the relative positions so in this example ABC is that in a h b g d c and basically what they mean is can you get rid of some characters here to make your string say ABC and yes you can obviously right so this would be ABC then in the second example is axcn ahbgdc and that one is not because there is no X so the way to do this is actually straightforward because if the order must be preserved it's really easy all you do let's just go through it is you have a pointer to each of these so you actually only need a pointer for the first one and then you Loop through every single character in the other one and if the characters match you simply move up your pointer so let's see what that's going to look like so we have a pointer at the start check are these characters match yes they do so we move this up now we check this character do they match no do they match here yes we move this up match no yes move this up and then once you are Pointers out of bounds that means you've successfully put in your entire substring into your original string pretty much all you need to do is you can just been every time a character matches you just move up your string and when the characters match you just simply uh move it up or you just simply return true and let's show what that's going to look like for the second example so let's say we have a x c and a h BG DC and we're gonna do the same thing so we are going to start here we're going to say do these characters match yes they do so let's move this up and now nothing will match this x so you will once you're done with this substring or once you're done with the string if this pointer isn't at the end then you return false so you just simply check is this pointer whatever this is let's call this like P does it equal the length of s and if it does that means you went through your whole word so you just check for this every time and if this never happens and you went through your whole word and it still didn't happen you just return true so pretty straightforward problem and now we can code it so essentially we make a pointer so we can just call that amp you like left and we'll make it uh we don't actually need to call it left let's just call it like P maybe and it'll make it zero and now we have to iterate through every single character in the big string which is T so we can say four care and T and now we have to check for a match right so we have to check for a match but the thing is p can be zero character so we'll check for that first right so we can just say if or S can be zero characters because we don't want to be out of bounds so we can say if P equals length s let's just return true because that means we went through the whole thing we four checking for characters because s can be an empty string or you could check for that before the function if you want to so now we will check for the match so we can say if s p equals t or not t Char then we want to move up p and so we're going to do this and we are going to uh go through this for Loop but keep in mind let's say the last character match like let's say our word was literally ABC and ABC so in this case you will never return true because at the very end like when this is true you've already recursed out of the for Loop or not recursed but you're out of the four Loops you need to check one more time after the for Loop is over so we can just return uh P equals length of S so if it did actually if this last character was the one we needed this will return true otherwise it will return false so let's try to run that it's actually does it work and you can see it's reasonably efficient or like as efficient as it gets for this problem so yeah let's go through the time and space now for this one pretty straightforward it's an easy problem so essentially we are looping through every character in t and that's going to be it we don't need to like we're checking for characters in s while we're checking a t so it's not going to be like t plus s or anything because essentially if s is greater than T let's say which I don't know if it can I guess it can if s is greater than T then what would happen is we would just have Loop through T and I've checked some characters of s but we're never we're not always looping through the entirety of us so in this case our time is worst case going to be T and best case obviously we found earlier but worst case we're only going to Loop through T we're net we're not if that's is longer than T we're not going to Loop through all of us and for the space we don't use any uh any other variables right we just use this pointers that's up one so yeah easy problem pretty fast hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see in the next one thanks for watching
|
Is Subsequence
|
is-subsequence
|
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
| null |
Two Pointers,String,Dynamic Programming
|
Easy
|
808,1051
|
942 |
hello in this video we are going to discuss the lead code problem number 942 d a string match the word d i means D for decrease the value right B for decrease same way I for increase what they will give you an string right a string input is a string right they will give you and string yes what the string contains only the letters I and D the combination of both I and B are full I or full D whatever it is but the string only contain I and a d right what you need to return we need to return an array which contains only integer right we need to return integer array but what is the condition n plus 1 integers right our output array would contain n plus one why here n is the length of the string if the string has three letters right the length is three we need to return an array which contains integers of length four we need to return four integers right if the string has three characters if the string has 10 characters we need to return 11 digits array right 11 elements array we need to return then they give what is that the integers range is from 0 to n right our R is lower limit is our result resultant arrays lower limit is 0 the higher limit is what n say a length of the string if they will give you three character string right this string you need to return an array which contains 0 to 3. of integers right this is what they will give you the condition we know that ba stands for decrease and increase I just in the start of the probe in the starting of the problem our range is what ah lower value is 0 right higher value is length of the array which is in our example it is 3 right at this chart of the problem we have this data then if we find found any I right if we found any I we need to implement I stands for increment so we need to increase the lower value right if the string has I first we put 0 right after that if another I will come we need to increase the value of I if another I come we need to increase the value of I right the same way if we found the first B in our thing we need to put the high value right three if we find another D value we need to decrement right this is the logic from Logic for our question for example if let me check the question id right they give ID this is what they give in the first example right sorry I just here what is the value of length 4 right string length we need to return an array of what values five values right n plus one value here we need to found five values what is the low value zero high value is 4. right you first I have I so I put 0 here then I found an D so I go for high right 4 then I found another I so I need to add the I value right 0 to 1. then I found another B value so I decrement the highest value 3 right there are four values are printed right ah first to four values we need to found the last value right if you check ah what is the if we apply this logic we get the fifth one as what same right High equal to low that position we attend right we use all the characters so the final value is the value where high and low will be equal right 0 1 2 if we increment the low value you will get 2. are just decremented high value you will get what fifth value so both are same if you use low you just increment it will go to two if you use high you just decrement it will go to two so we don't need to worry about the last ah last value so I just moved to the coding part we need to First find the length of the string length right length of string right ah okay int I just named as a n ah s dot length which is just give me the length of the string then I need to create an array right which contains of integer for our output purpose right end result array I just in M res result array equal to Nu int what is the size of the array we need to return n plus 1 right length plus one k then what is the range right range here 0 to n so int lower range sorry lower range is equal to zero int higher range is equal to what is that um n plus 1 right sorry n then we need to fill our what the filter rate result array so I go for an Loop into sorry I equal to 0 then I greater than n for what we have the string of length n so I just go for first things length right zero to a n ah sorry n minus 1 that is what the less than n right I plus here I if they will give you four letters I just fill the first four elements of the array right here what is I am trying to do is that then if the character right ah Char at if I the position equal to I right increment I just um what result array I just add the lower range right first I add the lower end if the first character is I we just add the lower range zero then we need to sorry that is I rate then we need to increment the lower range right else we can you can use ah s dot chart at I equal to D or you can use this method also if it is I just increment the lower value if it is other than I uh we just decrement the ah what is that higher value is equal to SP equal to higher range right sorry higher range minus right then we fill this first four positions because this string has length of four we have an another position right another element we need to fill so result array ah n right into position ah what is that um yeah in the position right we are filling from 0 to I am right so we need to add the N2 position what is that ah yeah we can use both higher range or lower range because if you increment what this if you increment the lower value it will go to 2 if you decrement the higher value it will go to do so you can use anything right higher range or lower range this is our Prof or problem is entered we need to return what return the result array salt array right I just run the code sorry return array is equal to not here what happens here this Filter Hey what is not a statement sorry equaled equals sorry that is small mistake to Reagan you cannot find the simple yeah spelling mistake sorry for everything yeah it's ran successfully so we need to submit yeah it is running successfully thank you for watching if you have any doubt contact me on Instagram thank you or leave the comment
|
DI String Match
|
super-palindromes
|
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where:
* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* `s[i] == 'D'` if `perm[i] > perm[i + 1]`.
Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`.
| null |
Math,Enumeration
|
Hard
| null |
725 |
welcome to september's leeco challenge this problem is called split linked list in parts given the head of a singly linked list and an integer k split the linked list into k consecutive linked list parts the length of each part should be as equal as possible no two parts should have a size differing by more than one this may lead to some parts being null got it and the parts should be in the order of the occurrence in the link input list and parts occurring earlier should always have a size greater than or equal to the parts occurring later so if we had a linked list with three nodes one two three but a k of five we're going to split this up as equal as possible which would be one two three for the first three and two empty ones for the last two now with this example we can see we have a list of ten numbers but we have a k of three so we wanna divide this up into three parts but that's not going to be equal out right because if we did 10 divided by 3 that's going to be 3 and remainder of 1. so what we're going to do is take that remainder and put it to the beginning however many uh are remaining first those first ones we're going to add one more and how we're going to do this is keep track of the head and just move down the list in a nested for loop we'll store the previous node each time so that way when we know we have to split the list we're going to have that previous node now point to a none and if we find that we've run out of nodes then it's just going to add a null value into this output okay so we have to do this in two parts we're going to do a two pass solution because no matter what we need to find the n here how many nodes are in the linked list and there's no way to know that until we pass through the whole thing so let's just put this up here so i can kind of track what i might have to do let's first store output which is going to be a list and let's go through our list and find r n okay so let's see n would be have our current pointer point to the head and we'll say while cur dot next and make sure to increase our one and i guess we'll store that and start with zero here okay so once we get out of this loop now we should have our value of how however many ends we have okay so what else is left well we know we need to know how many belong in each you know partition and also how many are left so i'm going to call that let's see part and we'll say however many are left now the part is simply n divided by k and however many are left is going to be n modular k right so here with a length of 10 we know that each part is going to have at least three and we are going to add one to that first one when we add to our output all right so let's reset our head or curve to point to the head again and this time we're going to also store the previous all right so 4 doesn't matter in range of we know there's going to be k parts that we need to return and all we do is append to our output whatever our current thing is pointing to right but we also need to make sure that we increase our uh well let me think first i guess we should first add it here and then move along our current pointer so we'll say 4 length and range of what is it part partitions we want to move our current pointer ahead so as long as we have a current pointer we're going to move it ahead so if there's a current pointer we'll say cur square dot next and before we do that actually we'll store that previous to equal curve now why do we do this well we need to break off that previous note right so as long as there's a previous at the end we're going to say hey previous dot next make sure it's equal to none so that way we're like cutting off this linked list but one more thing we might have some left here right so if we have some left we'll actually have to say well if there's a left and make sure there's current value say cur equals faster that previous right previous curve and er equals curve dot next oh gosh i hope i got this right i'm not positive i did let's see let's first check our first example here all right so that does look like it's working but let's also check this one uh okay hmm so i missed something up here oh right i need to decrease our however many are left here left minus equal one because we're going to run out of those let's make sure that worked here okay so it looks like it's working and accepted so great this is time complexity of o of n plus k or hm i think it's just o of n uh plus possibly however many we have left here so call that l of n plus l and space complexity well i think it's constant because as long as you don't count the output it would be nothing extra whatever you're storing so yeah so i think it's constant space all right great thanks for watching my channel and remember do not trust me i know nothing
|
Split Linked List in Parts
|
split-linked-list-in-parts
|
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50`
|
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
|
Linked List
|
Medium
|
61,328
|
1,670 |
Whatever is ready, weather repairing is a little bit, this is the third question for you, goodbye little child artist design front medium, so now what will we do in it, we have to make improvements in it, what should be inside it, you can make friendship with the front, make the officers happy with this also. If I am able to remove friends remove back head and at the same time remove nutrition medals from the middle, then if I say that I am only one, inside this we one want to do something from the side, then it should be like this, you want to do something and So, if you want that I will push you free in the middle, then this should also be possible. If you want to cook from the free middle, then you have this mark one and a half, then it is a very simple question, rest let's see what is its relation. Cheers. So if we see the question here like front circle middle what do we do slice hearts flower front will of rest moments from different pushback flower middle then Arvind Yadav in the middle and the same is pocket functions for the same so this is what we have to do Either this point and model of meeting this was five rotis to remind this many symptoms so let's see we will take we are going to use this class we are going to use English and like if I have some front off then I She velvets on English cases If I get some back then I will give Nobel award on the last of the length belt If I get some medal then these English's size buy to taste to get back to that at this time I am worth index on one But I will cut whatever happens to Mary, like if I am free, then a strong tractor vessel or virus index stone will come on one of my arms and then whatever is this two, it will be discharged, that lump on the front, then in this way, I will do something. So it is a very simple question, what will we do, we have to see that we do not take English, Language of India type, I will list its name, okay, the conductor, we will mix it in it, please request that China or Making the list is a chore because we complain about the [ __ ] and you keep it. because we complain about the [ __ ] and you keep it. Okay, okay, if I have to front the question, what will I do? Hooda is a function. He takes the first argument Alex and takes the second element Commissioner S Band, if some medals. Why dot add Why dot add Why dot add 128 Bye To You Who Value Area Meaning Accurate Size Y2 Going to this next value, cut it off so it will come in the middle If something has to be backed up then what will I do why dot get worried I just pass the value, what does it mean that which is my default index means by default it will go there and add whatever is minute and right means there are few points at the very last, if you want sweets at the front then it adds in the last. If you add in then you should have this technique in this way that if I talk then I can have two pieces either my list will be MP or the notification has come that if why scold is smt means chilli is used. If she has taken it then I will return it - Man otherwise I will return it - Man otherwise I will return it - Man otherwise I will return it otherwise I will return you Dr. Renu means if you are doing it then I have to remove it also. On which index zero sentence means there is air at 2036. Even remove it, I do n't return it because I am on friendship of shift in the pot, whereas if I had to do it from the middle up, then what would I do, see that it will come straight but the value of the index will be found instead of zero, torch light. Middle that if I talk, okay, you will see in place of Jio, what will come in the place of zero, why this scolding, size minus point, then please a byte, why should I say cross size - a byte, why should I say cross size - a byte, why should I say cross size - sit here and see, if I talk and I have to say these women Meaning, if I call for the middle, talk like a top model, then I would want three as my answer, then three, now which index for improvement exam is there before the exam, then one is the president, neither am I, that if you how to Make because the size is here because the size is three not three - 18252 Sukhmay will size is three not three - 18252 Sukhmay will size is three not three - 18252 Sukhmay will now say that if you subscribe then 1.5 now say that if you subscribe then 1.5 now say that if you subscribe then 1.5 inches then here subscribe here and if you want mental but my return of the day how to write Prabhu what do you want? So what I will do and minus one by two which is now this 1.5 inch which will automatically now this 1.5 inch which will automatically now this 1.5 inch which will automatically leave the numbers inside them in this what are we saying zero size minus one by two will update the American that if I talk about what I say Retired Chudawat Remix Hai and Azaan Clean Simple Line Hum Copy Kar Deni Se A Achcha Ok And Here I Will Pass More Index Why Lord Times - One Will Pass More Index Why Lord Times - One Will Pass More Index Why Lord Times - One Night Classes Ok To Prank Tere Upar Phone Number 10 Hai Some More Semi Soluble Is it ok that you are getting Triphala powder I think Singh and yet you have to understand that to connect with lady committee the video was a very easy question and if you liked the video then please press the like button and subscribe but the whole Ko Thiis Very Much
|
Design Front Middle Back Queue
|
patients-with-a-condition
|
Design a queue that supports `push` and `pop` operations in the front, middle, and back.
Implement the `FrontMiddleBack` class:
* `FrontMiddleBack()` Initializes the queue.
* `void pushFront(int val)` Adds `val` to the **front** of the queue.
* `void pushMiddle(int val)` Adds `val` to the **middle** of the queue.
* `void pushBack(int val)` Adds `val` to the **back** of the queue.
* `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`.
* `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`.
* `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`.
**Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example:
* Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`.
* Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`.
**Example 1:**
**Input:**
\[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\]
\[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\]
**Output:**
\[null, null, null, null, null, 1, 3, 4, 2, -1\]
**Explanation:**
FrontMiddleBackQueue q = new FrontMiddleBackQueue();
q.pushFront(1); // \[1\]
q.pushBack(2); // \[1, 2\]
q.pushMiddle(3); // \[1, 3, 2\]
q.pushMiddle(4); // \[1, 4, 3, 2\]
q.popFront(); // return 1 -> \[4, 3, 2\]
q.popMiddle(); // return 3 -> \[4, 2\]
q.popMiddle(); // return 4 -> \[2\]
q.popBack(); // return 2 -> \[\]
q.popFront(); // return -1 -> \[\] (The queue is empty)
**Constraints:**
* `1 <= val <= 109`
* At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
| null |
Database
|
Easy
| null |
6 |
hey everyone welcome back to my YouTube channel today we're solving another lead code challenge lead code 6 zigzag conversion will be given a string which we have to print in a zigzag fashion and then read it line by line and return the resulting string for this one I'll be using two different approaches to solve the problem you can follow me through both the approaches and then decide which one works better for you let's get started in the zigzag conversion problem we'll be given a string let's say think different and then we'll also be given number of rows in which the zigzag will be so if the number of rows is 3 then think different will be written something like this t h i then n k t i f e r e n t so this is the zigzag pattern similarly if the number of rows is 4 then think different will be written like t-h-i-n KD i f e r e n t now the first approach that we'll be using to solve this problem is to Simply store this value in a 2d array and then use that 2D array to print the output let's see how we can do that say I have a 2d array of size equals to number of rows that's the one direction of that 2D array say three and I'll be iterating on rows and columns for this array so let's say initially rho is 0 and column is 0. and I'll keep incrementing the row okay so with row 0 and column 0 I'll push I'll put the first alphabet of this string into the 0 position so I get T here then rho will become 1 C will stay zero and I'll get H here then rho will become 2 C is going to stay 0 I'll put I here now I've reached the last row then we can put a condition in place that if rho is equal equals to number of rows minus 1. then you flip this direction so now we'll start decrementing the row as we are decrementing the row we'll also increment the column to give it a diagonal shape so when you are decrementing the row column will increment and when you are incrementing the row column will stay as it is so now my row is equals to numbers minus 1 which is the last row I'll start decrementing the row so row becomes one I'll put n here then row becomes 0. and here column also becomes one because we are incrementing the column row becomes 0 column becomes 2 I'll put K here now comes in the other condition if rho is equal equals to 0 then we'll start incrementing the row again and will not do anything to the column so now the same cycle will repeat I'll get D here and I here then row will again be equal to number rows minus 1 so I'll start decrementing the rows and incrementing the column I'll get F here and F here then rho becomes 0 you start incrementing the row the column says static and you get the complete string and now to print the output which is this zigzag string red line by line so t k f n hndf e t i r so we can do that if I just complete this so we can do that by reading one row of this array so if I read the first row and the second row and then the third row I'll get the desired output if we can try a very similar approach with number of rows four just to prove our point so say in here also I have a 2d array size 4 okay I'll start with row 0 in column 0. and initially I'll keep incrementing the rows column will stay static so at row 0 in column 0 I'll put the first alphabet which is T then rho becomes one column stays 0. I'll put H at that location so becomes two column stays zero I put I Ruby comes three column stays 0 put n and now the condition is met that R is equal equals to number of rows minus 1 when we reach the last row we start decreasing the value of R and increase the value of C so in that case r will become 2 C will become 1 and I'll put K here 2 comma 1 R will become 1 C will become 2 I'll put D here and R will become 0 c will become 3 and put I here then I've reached the other end point so the conditions will flip if rho is 0 I'll start incrementing R and column will stay static and I'll get ffe r e n t here and again to get to the output we can just read this array row by row and we'll get the output so this is a very simple approach using a 2d array let's try to code it so with the Matrix approach we'll be using a 2d array to store the results of each row and let's start with the basics we'll first check if the number of rows is 1. in that case just return the string because if it's just one row then the this exact pattern will be the same as the original string otherwise we'll create a matrix which will which we can initialize as a blank array then I can iterate till the number of rows so index from 0 till indexes less than number of rows and in here I'll simply set that index of the Matrix to another array so that we get a two dimensional array with our storage area ready we can proceed with reading the string for that I can create another loop and starting from 0 and this time the index will go till the length of our input string along with the index I also need a counter for which row and column the program is currently at so I'll just take a row starting at 0 in the column and when I'm in this Loop I'll simply set for that Matrix set the row and column index so set that position to the current value of our string s which will be index position of s then I can make a condition because I have to check whether I'm going down the rows or I'm moving up the rows and for that if my row counter is equals to number of rows minus 1 that means I've reached the last row and I'll need a Boolean flag also let's say row increment which will initially be true because when we'll start with our algorithm we'll be starting from Top going to the bottom incrementing each row so row increment equals true then if we have reached last row we'll set row increment to false on the flip side when we are decrementing the rows if our row counter comes at zero which will be if reached the first row then we can again set the row to increment instead of decrement okay then comes our row and column shifting as we discussed so if we are incrementing the row we'll simply set rho equals rho plus 1 otherwise which means when we are decrementing the row that means we are going up we'll set rho equals rho minus 1 also as we go up diagonally we will set column equals column plus one so when we go down straight but when we come up diagonally to match that V structure so that's the simple Loop checking for the increment and then based on the based on whether it's increment or decrement changing the value of row and column and then after this Loop let's try logging the value of the Matrix to the console if we run this so for this input PayPal is hiring and number of Rows 3 which is this zigzag pattern we can see in the first array I got p a h n in the second array I got APL as iig which matches with this and then in the third array I have y i r similarly we can check for this input case two so in the first row I've got p i n and then there are some empty items which we'll get rid of in a bit then ALS IG y a h r p i so that approach is working as expected now once we are done creating our Matrix I can simply keep a output variable which will be empty string and then I'll again iterate on the number of rows which is the size of my Matrix and then for each row I'll just append that row to the output so output plus equals Matrix index which means the first 1D array first second third but selecting the complete 1D array at once then I can just use the join function to join it using empty string so that it all gets concatenated and in here I can just return the output before returning let's just log it then we'll submit it expected pH and APL SSI siigy IR and that's the output so I'll just get rid of control logs and return the output from here okay with that let's submit it okay that passed all the test cases and we got two zero two millisecond in runtime and it used 57 MBS of memory now we'll just compare it with the other approach now with the pattern based approach instead of saving some intermediate values in arrays we'll try to think if there's a way I can make the right number of jumps I can skip the right number of characters and get this output from this input itself like what will it take if we take num Rows 4 as an example what will it take to go from D to I and then from I to n so that I can print this character then this character sorry so I can print this character and then this character without saving it anywhere and to be able to do that let's see how many jumps we need to go from one character to the next in any given row so say if I'm at T and I have to go to k I need one two three four jumps and my fourth character is the one that I need similarly to go from k to F I need one two three four jumps and my fourth character is f so for number of rows equals to three we can say we need four jumps to get to the next character similarly with number of rows equals to 4 if I have to print just the first row say I'm at the first character t then I can take skip or jump one two three four five six characters and then my sixth character is I then when I'm at I can jump one two three four five six characters and I'll get in so we can say with num rows equals to 4 the jumps that we need is six similarly we can take it to number of five if I'm at T I want to get to F directly so that I can just print it without saving it anywhere I'll need one two three four five six seven eight jumps and my eighth character is f so we can say with numerals five the jumps is eight and we see a very simple pattern here that the jumps is actually equal to number of rows minus 1 multiplied by two so if number of rows is 4 you get 3 into 2 6 if number of rows is five you get four into two eight and that's the number of jumps you have to make to get to the next character and this is true for any given character in this pattern so if I'm at H I make one two three four five six jumps and I get f similarly if I'm at n I make one two three four five six jumps and I'll get to e so that I can just directly print it now this static jump of numerals minus 1 multiplied by 2 is valid for the first row and for the last row but for all the rows in between we see that the number of characters that are getting printed are double okay because it's a v kind of a structure so at the top we have one element and at the bottom we have one element but then for all the values in between there are two elements each okay let's simplify that so if I'm at the second row say I'm at H and if I use this jump so I'm at H I make one two three four five six jumps and I get to F but what did I miss I missed the D that is needed so for the intermediate rows we'll pick two characters and we'll just tweak the jump a bit so this jump will anyways help me in getting from H to F and then from F to T but the question is how can I get from H to D and then F to E and for that we'll see that the pattern is if I have to get from H to D again let's see how many skips do I have to make so one two three and then fourth character is the one that I need so we can say small jump equals 4. okay and similarly if I'm at I and I have to get to k then I make just 1 and then second character is K so small jump becomes 2 head so the number of jumps that I'm doing is actually decreasing as the number of rows are increasing and that makes total sense because the diagonal value is decreasing as we are going down the rows because it's a v-shaped structure so the number of v-shaped structure so the number of v-shaped structure so the number of jumps that I'll have to make will be less as we go down so to get from H to D I had to make four jumps to go from I to K I had to make two jumps let's try the same thing here I know to get from H to E I need eight jumps but then to get from H to F what is the number of jumps needed that's one two three four five six is the element so from H to f six jumps from I to I if we see one two three fourth is the character so I get four jumps and then from n to D again it's just two jumps and then again it's a row based pattern here that the number of jumps needed for that second character for all the rows other than the first and last rows becomes so we can say small jump will be and if we compare it to the actual jump so that's 6 minus 2 and this is 6 minus 4 and let's look at this value here 2 and 4. how we can get that simply jumps and we'll subtract your row counter multiplied by two like here row zero one two three when we were at first row the jumps were six but we jumped four which is six minus two to get to d one two three fourth we got to D and if I'm at Row 2 then 6 minus two into two which gives me two so I just made two jumps to get 2K so that makes sense to pick the second character I have to make a little smaller jump so that instead of directly going from H to f I'll first go to D and then I know how to go to F with my normal jump now we just use these two jumps to iterate on this complete array and we'll keep printing each value as we jump through the string let's code it up now for the mathematical approach the starting stays the same that if number of rows is one you return the original string and then I can iterate on each row and then print the right characters for that row so if I'm at row 0 I'll just print p i n and so on for that let's create a loop say row counter starting from zero tell the row counter is less than number of rows increment row by one and then for each row I need to know the jump needed and we know we now know the formula for that so let's say the increment needed is number of rows minus 1 into 2 so here the number of rows is 4 that means we have to pick every sixth character four minus one three into two so first I'll pick P Then I then n if I'm at row second I'll pick a and then s and then G to get the right characters then I can have a simple Loop for index which can start from my row counter and it will go till the length of our input string and will not increment the index by 1 but will actually make it jump according to the increment so index equals index plus the increment once we have that I can keep our output variable initialized as an empty strain and then in here I'll simply add to the output the value of string at the index so let's see what we get after this so when we run this if you look at case 2 where the input string is PayPal is hiring and the number of rows is 4 in the standard output we get pin then ASG YH and p i which matches with pin and then a s g then y h NPI so we talked about that this works for the first row and the last row but for all the rows in between we have to pick two elements at each instance so like once I'm printing a I also have to print l if I'm printing S I also have to print I similarly here if I'm printing y I have to print a also and for that we'll simply make a condition that if a row counter is not 0 that means if it's not the first row and row counter is not equals number of rows minus one if it's not the last row either and we'll put one more check here but let's see what we'll do in that case we'll simply set output equals to for from a string we'll take index plus increment we know that will give us this character if I'm at a that's going to give me S but what we need is L if I'm at y index plus increment will give me H but what I need is a so I am coming back a few steps like here from a I'm going to S with six gems but I am going to L with 1 2 3 4 jumps so I'm coming back two steps and for that I'll just subtract 2 into not the number of rows the row counter because the number of jumps that we have to take back um actually decreases as the number of rows increases which we can see here because it's a v kind of a structure so that becomes our output also the condition that we have to add here is for example if I'm at s I know I can pick up I because our string has that position but if I'm at G there's nothing after it so I'll have to first check if there is a element at this position so we'll simply add that condition if this is not and since that is implicitly decided so I can remove this let's put that here let's have a look at the output now okay for case 2 if we look at the standard output matches let's just return the output okay I'll just submit it now so with this one we can see the runtime has come down to only 84 milliseconds which beats 96 percent of the users and we also consumed less memory than before here is a quick side by side comparison of the runtime and memory usage of both the approaches so with the pattern based approach the runtime was only 84 millisecond and with the array based approach it was 202 milliseconds and that is because with the error based approach we spent time in populating that array and then reading it and then joining it all together to get the output string but in case of the pattern approach we just made the right jumps and start and just printed the pattern right away similarly in terms of memory with the error based approach we used 57 MBS of memory because we were saving uh then the intermediate rows in different areas in r2d Array but in case of the pattern based approach we did not use those arrays so we used less memory I hope you were able to follow me along in both the approaches and can now use them to solve the zigzag problem yourself if you liked the video please share it with your friends and subscribe to the channel for more learning content I'll see you in the next one peace out
|
Zigzag Conversion
|
zigzag-conversion
|
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000`
| null |
String
|
Medium
| null |
35 |
hello today we are going to solve swords insert position problem on youth code which is a problem about 3500 code so angles problem we are basic living in a sorted array in which in the description they have specified that they won't be able to be any duplicated values in an area and we are also given a target value that you need to insert in a particular at a particular index location so for solving this problem I came up with a solution where I created an list of individual and I will be inserting all the elements in a given list add the current position and then I would be just checking using the index of location I will get the index value I will be returning it back to the call to the calling function that's how I was able to solve this problem so here if it's like if I tivo'd this problem so taking the input as input array as one three five and six and my target value over here is target value is five so if I consider would be I trading to the entire follow that I would be starting from zero and like let's assume the list to be an empty list for now and the initial and when we initialize it so when I is equal to zero I will be taking like say in the condition in the if condition with where target is less than equal to norm of Phi which is like five less than equal to one which is a fault so it would just add number one over here and it will increment the eye from zero to one second and the second iteration it will check if five is less than equal to three let's keep a track of the number so initially the number was one now the number is three so three five less than equal to three F of false so add the number three into my list so the second case is like now that I would increment from too cause you want to - increment from too cause you want to - increment from too cause you want to - so five less than equal to 5 is true then it would just add the target over here which is five it would increment the high which will be six in my case over here it will be number one last number was five and now the number six so we're less than equal to six - I just added into my list so now using - I just added into my list so now using - I just added into my list so now using the index of locate index of feature and the index of function in the list I get the index of the target five which is 2 and that's what I returned back here another case over you if the target is not present in an area where let's say you the sample 3 where the input array is same but the target value is 7 so in this case the value won't be inserted into the list because any time the target like 7 less than equal to 0 is false it will go into else similarly for the dire keys and the list will be still be 1 3 5 6 so in that case we need to check and we need to put an extra check in place to understand if the target was added or not if the target was not added you need to add the target at the last location which would be 7 here and then when we check the index orbit revert on the right value which is 4 in our case so this is a one way that I solved this problem i while i was thinking of the logic i got another solution for the problem so this solution works if I submitted it would return us the right output okay I just got rid of that parameter so that's the problem of you so yes so the solution is accepted but there is a problem in the solution it's like we are unnecessary duplicating the values of the nones array into a list and then checking the index we can get cluttered out those or we can overcome the situation by returning the index right of it if we find a value of a if we find a number which is less than the target or if we come across the correct index while we are iterating through the list so this can be achieved by getting commenting all the list over here and the even don't we do not want the N spot as well over here we do not want any of this part so what we will be checking is like here instead of checking the target we would be still agitating to the entire array and your instead of checking target is less than equal to something like that we first make try to make sure if the numbers norms of I which we are looking is equal to target if it is or else we also need to check it's similar to target less than equal to number that we had in the previous proposal we need to just check if nums of AI is greater than target and we need to return the index value right away in this case because if I trade you through the solution if I trade you go you're like my target is let's assume T target as five and let's revolver let's walk it through the second propyl solution so the input is 1 3 5 6 and the target we are looking for is 5 so I would start from 0 the first index first number would be 1 and the Return Index let's put this as return index over here which is the value I that we are expecting in our case so number of I which is 1 equal to 5 which is false one greater than file is false so it won't return anything it will I increase the i from 0 to 1 so at the number would become 3 so 3 equal to 5 is false and 3 greater than 5 is also false so it won't go inside the if loop and return anything then it would come to the next number which is 5 by incrementing hi so here the page like five equal to five at the number of is five and target is five so this condition is true since we have an odd it would come inside and it would return the index which is true for us in this case so that's how we will be returning if T value is present in an array and if it is at the current index the second value of second question is like what if the value is not present in the Attic like for that considering the same in case of seven so it would keep iterating so at five but then like five equal to seven falls and 5 greater than seven also false so it would increment the value at six the same condition six equal to seven is false and six greater than 7 is also false so it from not so now what we need to now we need to return the length so your so I is equal to three as we and we know that the value seven should be inserted at position number four which is the index number four here so for that instead of returning the I we need to return nums dot length so if we do that we should get our answer and this using the second proof second approach as well so if I run my core and if I try to something it should get submitted so yeah the advantage of this solution is like we are not creating any extra collection or again not using any inbuilt function we are just leveraging what input we had and we are just trying to check against the target we are looking for and if we find it we return it otherwise we return the length of the index and that's how we make sure that we find the correct position to insert a particular value in a given array thank you that's all
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,725 |
all right let's talk about the number of rectangles that can form the largest square so you are given a reverse window and for a single eye you go to li wi and it is representative and with that so you want to while you want to return the number of rectangles that can make a square with the side of the length of max length so which means you want to return the uh the largest skirt be honest in the rectangle so you can cut be honest so when you can cut you can call the minimum between the dentin with right so in this example it's five this is three this is five right so the max length for the square is five by five and how many three of them right so this is pretty simple idea so i'm gonna just write them so i will have a result equal to zero and i also have to transverse the entire rectangle array right so i'm gonna say is the smallest between the two right and then i will also need to create a current i mean the curve maximum length so maximum value so if max l is less than now so maximum length of the square in a rectangle so max l is equal to now and uh result will be equal to one be honest because that will be the first one and else if my max then is actually equal to the value so i should count my results right and then later on with this return result so this is pretty straightforward i just can't hold many rectangle i mean come from me screw in we can go for the max length and i would say it's pretty good so let's talk about time and space complexity so this is constant space and this will be the kind time complexity so this will be the solution and if you find out this is helpful subscribe like if you want it and i'll see you next time bye
|
Number Of Rectangles That Can Form The Largest Square
|
number-of-sets-of-k-non-overlapping-line-segments
|
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi`
|
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
|
Math,Dynamic Programming
|
Medium
| null |
991 |
Hello Gaye 11th Mein Dubey Will Be Discussing Question Don't forget to subscribe and subscribe Twitter The Video then subscribe to the Big Ronit Tours from subscribe and subscribe The last pressure Yen trying to reach is back to change The operation Let's see how record Subscribe Appointed - Festivals and my tab Trying to move Will probably make the world in President appointed Video subscribe this Video subscribe long and subscribe the Channel subscribe Video subscribe button How to her well Increment result for a prominent operation and mid-november half prominent operation and mid-november half prominent operation and mid-november half fuel subscribe my channel subscribe is subscribed that
|
Broken Calculator
|
array-of-doubled-pairs
|
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109`
| null |
Array,Hash Table,Greedy,Sorting
|
Medium
|
2117
|
622 |
Hello guys welcome to your words made easy my name is the wall and today will be discussing design circular given in this question Thursday subscribe and subscribe the Channel subscribe to subscribe and subscribe the Channel Please subscribe this Video Now why before moving into the implementation Partners pe luta standing in front of entry gate and 151 doors on arrival and will be identified subscribe And subscribe The Amazing Portion Interview Video subscribe for Live Video Pimp Tube to the elements will be removed from the start and elements in the world today is per click By subscribe and subscribe this Video give interview subscribe comment and subscribe the element Thought of the day Quid need to variable to point at which will point to 10 top 10 elements of close with sexual element press subscribe button printhead festival subscribe And subscribe The Amazing subscribe Point To The Next Index Notification Remedy Element Midding Midning Bhavya Veervar Appoint subscribe and subscribe the Channel subscribe List Listen That Implement Dress Constructor Will Define The Amazing Will Be Selections Will Not Be Implementing The Last 4 Minutes Annette Schwarz Element Ronit subscribe to the Page if you liked The Video then subscribe to the Page spiritual not have yadav this Deposit and Withdrawal representative will prepare subscribe to subscribe our Channel element and will simply return for subscribe to the Page that selection apart from the front edit and objective and mid point tours in Different according to subscribe the length of the return of the day person subscribe and loot anil simply return file otherwise to the point in the country will update the point at which can find the value of this point to play components * Increment size available in components * Increment size available in components * Increment size available in This God Decriminalized Wave Element Suggestion Subscribe Now To Front Entry Point To Subscribe That War Front Subscribe Must Subscribe In A Reader India Friend Dodgy Code Kuch Samaj Main Right Result Lets Try To Submit Must Subscribe To MP3
|
Design Circular Queue
|
design-circular-queue
|
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ".
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
Implement the `MyCircularQueue` class:
* `MyCircularQueue(k)` Initializes the object with the size of the queue to be `k`.
* `int Front()` Gets the front item from the queue. If the queue is empty, return `-1`.
* `int Rear()` Gets the last item from the queue. If the queue is empty, return `-1`.
* `boolean enQueue(int value)` Inserts an element into the circular queue. Return `true` if the operation is successful.
* `boolean deQueue()` Deletes an element from the circular queue. Return `true` if the operation is successful.
* `boolean isEmpty()` Checks whether the circular queue is empty or not.
* `boolean isFull()` Checks whether the circular queue is full or not.
You must solve the problem without using the built-in queue data structure in your programming language.
**Example 1:**
**Input**
\[ "MyCircularQueue ", "enQueue ", "enQueue ", "enQueue ", "enQueue ", "Rear ", "isFull ", "deQueue ", "enQueue ", "Rear "\]
\[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\]
**Output**
\[null, true, true, true, false, 3, true, true, true, 4\]
**Explanation**
MyCircularQueue myCircularQueue = new MyCircularQueue(3);
myCircularQueue.enQueue(1); // return True
myCircularQueue.enQueue(2); // return True
myCircularQueue.enQueue(3); // return True
myCircularQueue.enQueue(4); // return False
myCircularQueue.Rear(); // return 3
myCircularQueue.isFull(); // return True
myCircularQueue.deQueue(); // return True
myCircularQueue.enQueue(4); // return True
myCircularQueue.Rear(); // return 4
**Constraints:**
* `1 <= k <= 1000`
* `0 <= value <= 1000`
* At most `3000` calls will be made to `enQueue`, `deQueue`, `Front`, `Rear`, `isEmpty`, and `isFull`.
| null | null |
Medium
| null |
455 |
hey everyone welcome back to the channel today we're going to be solving a problem on lead code the question is assigned cookies so the question says assume you're an awesome parent and want to give your children some cookies but you should give each child at most one cookie each child I has a grade factor of G of I which is the minimum size of a cookie that the child will be content with and a cookie J has a size s of J if s of J is greater than or equal to G of 5 you can assign cookie J to the child eye and the child eye will be contained your goal is to maximize the number of your contention and output the maximum number so we were given an example of one two three G is equal to 1 to 3 and S is equal to one and one so what G is over here is basically the grade factor of the children so let's say we have three children the first child may have a grade Factor one the second child may have a great factor of two and third child may have a great factor of three and as the five is the amount of cookies you can give each child so that their greed can be you know maximized basically if I give one cookie to this guy to the first child and so basically let's say we have child one he has a great factor of one and I give him the very first cookie so the maximum capacity of cookies he can want is one and if I give him one cookie his greed will be satisfied so you know you can increment the count by one over here but in this case if I have another child too his breed factors 2 which means he needs two cookies to get you know fulfilled or satisfied I only have one more cookie left so I can't give him this one cookie because my the great factor of that kid is more than the amount of cookies he can get in this case which is basically s of J is greater than G of I the child I will be content with it so the second child will not be content because he'll only get one cookie in this case so yeah and same for the third case as well the third child will have a great factor of three which is more than a second kid basically so we can't give him just one cookie and satisfy his greed so he will also not get any cookies so in this case we can only have the output as one because only we are just satisfying one child with one cookie right and let's say one more example over here we have G is equal to 1 and 2. so we have let's we have two children who agree factors of one and whose rate factor is two and we have three cookies right and we have three cookies let's say we have three bags in which we have one cookie on one bag we have two cookies and one bag we have three cookies right the very first child will get his greed Satisfied by one cookie if we give him one cookie and the second child will also get his greet satisfied if we give him either of the two cookies either of the two bags of cookies right so we'll have a great fact we'll have an output of two because all both the children is satisfied in this case so um the very first approach that you know that might come in your head uh might be that the Brute Force approach um you know just take all the kids all the G kids over here and loop over them and you know just compare each you know kid with this one cookie bag you know they're getting and basically just increment the count if it's equal or not and just get the answer from it but that's a very bad solution and so an optimal way to solve this would be you know just sorting it first I guess you can sort both the arrays from ascending to descending so if I just sort G and S over here what I'll get is what you're seeing on the screen right now only so you'll get the same format if we sort it in ascending order and when we sort it in ascending order okay and also why we're sorting this is because the question does not stay there whether it's going to be sorted or not so we'll just assume that it won't be sorted and mostly because I have solved this question it isn't sorted so you do need to sort the arrays in order to get the answer in this question so we'll sort both G and S in ascending order over here so when we sort this in ascending order um let's write it over here so we have G over here when sorted will give you one two and three and we have so here when it's sorted it will give you one and one okay as after we sort it what we'll do is we use a two pointer approach what we'll do in the two pointer app which will keep one pointer over here we'll keep one pointer over here at this guy and we'll keep one pointer over here at the bag of cookies we have okay and what we do in this ascending model is we just compare the first kid and see if his greed is getting fulfilled by the first bag of cookies or not if you think about it logically that's the whole scenario right because if the first kid is not getting Satisfied by the first bag of cookies right then all the other cookie bags are not going to satisfy his greed also right because in this case let's say we have one over here right this is one child who has a bag of cookie of one and who has a great factor of one and he have appointed at one uh at the very first kid and we have the second pointer J at the very first bag of cookies which has a capacity of one as well okay in this case the kid's greed is getting fit right when the greed does get fulfilled what we do is we increment both I and J when both of I and G are getting incremented will compare again when we compare again we'll see that the second kid who has a great capacity of 2 does not get his screen fulfilled by the second bag of cookies this jbag of a keys right because the amount of cookies in the jpeg is less than his grade Factor so it's not going to get satisfied and you can also see that if it doesn't get satisfied for two it's not going to get satisfied to three and four and whatever else would be ahead of it so when that is done what we'll do is we'll just you know increment J in this case and see if you know there are more bag of cookies ahead of it but in this case there's no bag of cookies so you know you can't increment shape but let's take a different example let's say we have G is equal to 10 987 and S is equal to five six seven and eight right now when we sort G in this case we'll get seven eight nine and ten and in this case we get five six seven and eight right now if we keep a pointer over here okay I over here and J over here right firstly what we'll do is what we're going to do is we're going to compare if s of I first see what we're going to do is we're going to compare if you know G of I is less than or equal to S of J right so what is gr5 in my case G of I is 0 right are both of our cases I and J initially are 0 right both ing are zero what we'll do is we'll compare now is G of 5 which is 7 and S of J right it's of J greater than G of I then no it's not greater if it's not greater what we'll do is we just increment J okay now J is the over here above 6 and we'll increment J over here right now we compare again geofine s of J in this case again it's not greater we'll increment J over here okay now js2 now when we compare GN G of I and S of J now both of them are equal so what we'll do is we'll increment both of them when both of them get incremented this becomes three and this becomes one and again when we do check it again both of them are say both of them are equal so we will increment both of them and we'll just you know increment this will come forward this will become two now will run the whole Loop until you know either I or J either get are greater than the you know respective arrays and if either one of them you know goes beyond the certain limit of their array we'll just stop the code and we'll just return I because as you see over here I will be what the answer is or you can just maintain a counter just to you know make it more easier for you but in the end you can also just return I because as you just saw I will just keep maintain what the answer would be okay so this is how what the code is guys now let's just score it out okay so this let's just do this here okay make our I equal to 0 by J equal to zero okay now we want to run these Loops firstly we need to sort both the arrays okay let's just sort them in ascending order let's do a detailed sort and an s dot sort okay now we have I and J equal to zero now let's just do a while loop while I is less than lend us G and all sorry all J is less than length of s what we'll do is we'll check if G of I is less than or equal to S of J if that's the case then we'll just increment I and J both and if not we'll just increment J once and then we'll just in the end return foreign okay let's run the code and let's run the code okay so we're getting a runtime error over here so this has to be an and let's run it again yeah we're getting the output um the and function over here we're using and keyword over here just because you know either if both of them are inside their respective length of their arrays that's what that's when you need to run the code if either one gets out if any one of them you know goes beyond the length of their respective Aries we need to stop the code that right there and then right okay let's just submit this yeah and it gets submitted so yeah guys this is how you solve this problem and the last thing just before you guys go to time frame executive the code is O of Max of n log n comma M login so this is the time complexity of the code guys so yeah if you like the video please do like share and subscribe and do check out more DSA you did delete code content on my channel and let me know in the comments what kind of video what kind of problems you'd want me to solve next and also do check out my podcast yeah guys that's all for today and yeah
|
Assign Cookies
|
assign-cookies
|
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number.
**Example 1:**
**Input:** g = \[1,2,3\], s = \[1,1\]
**Output:** 1
**Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
**Example 2:**
**Input:** g = \[1,2\], s = \[1,2,3\]
**Output:** 2
**Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
**Constraints:**
* `1 <= g.length <= 3 * 104`
* `0 <= s.length <= 3 * 104`
* `1 <= g[i], s[j] <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Easy
| null |
337 |
hello and welcome to another Elite code problem today we're going to be doing problem number 337 House robber 3 the Final house travel problem there might be some more but it's probably I'm gonna All I'm gonna do for this uh series and so the variation of this problem is we have a thief again there is an entrance now called the root and each house has one and only one parent so the thief realized that the houses will form a binary tree it will contact the police if two directly linked houses have broken into on the same night just like the old house robbers and given the root of the binary tree you return the max amount of money the thief can rob without alerting the police so for this first example he chooses to rob the root and then the two bottom nodes you can't Rob these in the middle and so the total is seven and for the second example he chooses to Rob these two nodes right here and you can't Rob the top node or the bottom nodes because they're connected and so the total is nine the question is how do we figure out how to actually do this right so let's just show this second example for example and figure out what we're actually trying to figure out and like what how we would approach this problem and we are going to use you know our intuition from the other house Rover problems on how to do this so let's say we have something like this and pretty much let's try to figure out some base cases right so we can either Rob or we cannot Rob okay well that's pretty straightforward but let's figure out some base cases for some lower stuff and then we can figure out like our occurrence relation so obviously let's just start off for one thing if a node does not exist like let's say I go down to the right node of some node and it does not exist what would we want to what would be our output well that's pretty straightforward it would just be zero so if node is none or null or whatever then the output is zero that's pretty straightforward now for a child like for a leaf node what would we actually want to return well you might want to Rob but you might not want her up right and so in this case remember what we did before was we had to check the next like the next two nodes for a House robber so how do we do it for this binary tree well we're actually going to have two options and then we are just going to check all the way up so we're actually going to turn two things we're going to return the like the maximum that you can get while robbing this node and then the maximum you can get while not robbing this node and then from there we can just have a recurrence relation so let me show you what that would look like so let's say we started this Leaf node like we rehearse all the way down and this is going to be our cursive function for most binary functions you can have recursive functions so when you're actually at this last house you can either Rob or not Rob and so what we're actually going to do is we're going to return a tuple doesn't really matter so we are going to say there's going to be a Rob value where you do Rob this node and then there's going to be another value where you don't Rob this node so not at all okay and so let's figure out what those would be right so if we do Rob obviously we're going to return one and if we don't drop we're going to turn zero and let's do that for all of these nodes so here it's going to be three zero one here okay well that's pretty straightforward now let's use another color for the parent node so these values are going to return up to the parent node right these values now what are we actually going to have for these middle nodes well let's think about it right so if we rob node five what options do we have like let's say we rob node five that means we're going to take the value of node 5. okay well that's pretty straightforward but what else can we do well we can't actually Rob node one so we're going to want to take node 5 plus the don't Rob value of node one right of its child because we don't have a choice we can't Rob node one so we have to take the Do Not Rob value from node one okay that's pretty straightforward so that's just going to be a zero so that's if we rob node five now what's the match we can get if we don't Rob node five well we're not going to get a value from node five but now we have a choice we can either take the value from robbing node one the maximum from robbing or we cannot Rob and we're not always going to want to Rob node one just because we rob node 5 because there could be some other cases um that you know wouldn't work for it and yeah uh I like if you draw out some other trees like if you have something like this I think you know and you have some big value here then like you don't really want to Rob node five but you also don't want to Rob node one well actually here you could draw up node one but yeah there are like there are going to be some unique scenarios where and you could try this when you code this up um if you don't necessarily want to Rob node one just because you're Rob node five if you try to code it up that way and I did before it's not going to work and the illustration frees up violate that but basically you want to give yourself the max options possible and you also got to realize that like it's not a lot of time to figure out one of two things like you can either Rob or not Rob right so it's not expensive to pick one or one of the two we don't have to necessarily roll from the other one but anyway so our two options are and I'm actually going to write them down smaller so if we rob current node we have to choose not Rob value from children and then if we don't all right node we can choose either value from children and so this is where we would maximize it so we would maximize the two values so it would actually be more like this so it would be choose Max like this so you would take the two values you realize okay I can actually take either one and what's the biggest one so for this example so if we do Rob we have to change we have to take the not rob from the next node that makes sense but if we don't Rob we choose the maximal value in which case obviously you can see from this example that you would want to Rob this node here and so that's going to be one so we're going to put in a one here now for nodes with two children you got to keep in mind that like the two branches are pretty much separate so if you do Rob from four then you can't Rob this whole level right and if you don't Rob from four then you can rob this whole level so it's going to be the similar scenario but now we have to take into account both branches right and so let's do that so let's say for four we rob 4 for the first case well if we rob four then we can't Rob from either of these two and so we would get a zero right we would take this zero and this zero we can't Rob now if we don't Rob from four remember we don't necessarily always take the can raw because like I said for a bigger tree that's not always going to be the case so we have to maximize these so we have to just take the max value from both of them the max volume just happens to be three and one and so it's going to be three plus one here okay now we return these up so let's use another color to the roof finally and now we're using we do the same thing from the root into Leaf nodes so if we do Rob from the root then what's going to happen then we have to take the not Rob values from the uh to like if we were up here we cannot Rob these two right and so then we'd have to take these two values here so it'd be the three plus one and this one and but we'd have to add them together because there's two children right so it's going to be four plus one plus three so four plus one so that's the do Rob case okay and if we do not Rob then we don't have a value from the root but now we can pick the maximum from each child so what would we do there well we're so from this child it's a four and a four so we're just going to take the four and then this other child is a five and so you have eight or nine and then finally all you have to do is just return the maximal value from the root and then that's going to be your answer and so we have this nine meaning we don't we're all from the root and then obviously if we don't roll from the root then what would be what would we actually want to roll looking at the picture of what we'd want around with these two notes but yeah it's pretty much this is like your recursive relation and then you have to do this for each child so if you have two children you have to add those up so let's actually code it up and I am actually just going to code up real quick just to show you uh and they will show us a solution that will fail for you know if we don't Rob the node we automatically try to rob the node below let's try to actually code that up so we're gonna say deaf robber say node so pretty simple if not node we can just return and like I said we're going to turn its Tuple with Rob or not Rob so if there is not a no matter what you do return zero pretty straightforward now what we need to do is we need to actually get the values from the left and the right recursively and then we need to use those to figure out the values for the actual node so let's just say left equals robber dot left right equals robber dot right now we can return and so remember what I said so if you're going to rob from the uh from the current node it's going to be no doubt vowel and then we have to choose the right we have to choose like the second value from the left on the right so that's going to be what it's going to be left one plus right one I believe so that's the left value now the right value so like I said we're going to try just always robbing the child node and see what happens so that's going to be we're not going to rob but now it's going to be uh left zero plus right zero right so we're gonna always say like let's say we don't roll from three let's just always roll from these two and let's see what happens here in this case now we just simply call return Max robber root so we're just going to take we're just gonna roll from the roof and take them from the max value of the two nodes that are returned the two values that it returns either not Rob or Rob see what you see what happens here yeah and so you could see that they actually give you a tree here where it fails and let's take a look why and that's why I said you don't all you don't necessarily have to roll from it I just couldn't remember the exact test case that would break it but I remember doing it before so if you do it like this let's see what happens if we just always you know if we don't roll from one we always Rock from the other okay so here the maximum should actually be seven where you rob this node and you were off this node okay should be seven but let's try to actually recurse up and let's see what these things return and then let's figure out why it doesn't work okay so this three obviously will return three if you Rob and zero if you don't okay now two if we do Rob from two then we'd have a two plus zero and then if we don't Rob let's just say we always roll from three right which was not necessarily true okay now from one if we were all from one then we're gonna Rob from one and from three so that's gonna be four right because we're going to take this one value and this three value and if we don't roll from one let's say we always Rob two so that's going to be two and now finally this 4 if we do Rob from the 4 we're going to take the 4 and the 2. or if we don't Rob then we're going to rob over here which will give you a four and so you can see this would give you a six and a four and that's not like then the biggest value is six but not seven now let's actually redo this again but now we are actually going to use our algorithm that we have where we take the Max and we don't necessarily Rob okay so here it's going to be three zero right now here if we Rob it's going to always be two but now if we don't Rob we want to take the maximum here so that's going to be a three now here if we do Rob then we're going to always take this 3 right here or sorry no we're not always going to take this three uh actually yeah we are always going to take this three so it's going to be one plus three all right if we do rub we don't have a choice but if we don't we're all we do have a choice so now we can take either and so now we can take the so let's actually take the three okay and now you can see that if we do Rob from this four it's actually maybe four plus this three right here and if we don't Rob then it's going to be the biggest value of these which is going to be four so you can see like this is seven and the other way it was six and that's why we do need to change this code where we can't just always Rob the next node we actually have to maximize it so it's actually going to be the maximum of both of them it's going to be the maximum of left I think I can actually just do this I believe so I can do Max left plus Max right where the right and the left are the two outputs so I'm just going to say give me the maximum value in either of them I think that shouldn't work okay nice so hopefully that example made it clear as to why that is the case okay and so that's going to be it for this problem one more thing though we do need to do the time and space complexity okay so for time we are recursing to every single node that's going to be big of n where n is the number of nodes and we're only checking each node once for space worst case scenario is going to be big of n as well because even though we're not storing any values for something like this our recursive call stack would actually go down the entire tree and so we'd have to save every single stack here so that would be go of N and so you definitely don't want to forget that for um space complexities you want to all you want to always take recursion into you know that you want to always think about like what's the worst case recursion I can have and so even though I'm not actually creating anything else you always want you definitely want to take recursion into uh into your consideration for the space so it's actually going to be it for this problem and by the way so if you guys have any problems um I noticed in some other comments some people said they had some problems with uh like some solutions that they couldn't understand if you have any problems or any solutions that you don't understand for a daily code like editorials or anything just feel free to write in the comments or message me and I can definitely make a video on those for you to help you out and but yeah that's going to be it for this so hopefully you like the video if you liked it and subscribe to the channel and I'll see you next one thanks for watching
|
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
|
136 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem single number we're given a non-empty array of we're given a non-empty array of we're given a non-empty array of integers nums and we're told that every single element in this array appears exactly twice except for one element and that element only appears a single time our goal is to find that number that only appears once and we have to implement our solution in linear time and we're not even allowed to use extra space if we were allowed to use extra space this problem would be really trivial if you know what a hash map is or actually even just a hash set uh because for every single value like suppose we had this input array we'd take that two add it to our hash set so something like this and then we'd see a second two and then we would remove it from our hash set because every element that appears twice is going to be added to the hash set and then removed from it except for that single value like one which is going to be added to the hash set but it's never going to be removed so by the time our algorithm finishes we're only going to have a single value in our hash set and that's the value that we're going to return but the downside of this is in the worst case uh we'd obviously iterate through the entire array which is big of and time complexity but it's also big o of n memory complexity because we're using a hash set is there a way to do this solution without using any extra memory well there definitely is a solution and let's try to figure it out using this example i will say that the solution i'm about to show you is not really easy to figure out but once you've seen it before it's pretty easy to implement and recognize when you can use it so suppose we had this input array and you'll see why i wrote it this way in a moment so i'll just tell you that this solution does require bit manipulation so i'm going to take each of these values show them in their binary representation so 4 for example is going to be 1 0. of course there's going to be some leading zeros but we don't really care about those 1 is going to be represented like this 2 is going to be represented like this okay so this is the binary representation and once again i'll just tell you the solution basically we're going to use a binary operation called xor or exclusive or and if you don't know this operation basically what it does is if two bits are the exact same so 0 xor 0 is going to equal 0. also if they are the same meaning they're both 1 this is also going to equal 0. but if they're different so if we had 1 and 0 that's going to be 1 and if we had 0 xor 1 that's going to be 1 as well so if they're different we get one if they're the same we get zero and the solution to this problem is literally just taking all these input values xor them together and then our result is going to be that single value in this case that single value is 4. and if you just want to know the solution to this problem that's literally it but it never satisfies me so what i'm going to do is actually explain a bit of the intuition behind it and the simple answer is that when you take two values like two and you xor them together of course they have the exact same binary representation so if you xor two values that are the exact same of course you're gonna get zero uh all zeros in the output because you know the bits here are the exact same and they're going to be the exact same so if the bits are the same we get 0 in the output and the reason that's important is because we know that there's two twos right so these are going to cancel out we know that there's two ones these are going to cancel out so we're going to be left with only that single value and the order that you do the xor operation in is not important you can do it in any order and you're going to get the same exact result so that's the simple explanation and i'll just talk for another minute about if you didn't know that xor can be done in any order could you still figure this out what's the intuition behind it let me just talk about that for a minute i'm not smart enough to figure it out just by looking at all of these bits but we know that to simplify it we can just look at a single column right just one of the positions and like i said we know that every value in the input is going to be a duplicate except for that single number so we're trying to prove that we know for sure that the bit in the output is going to be the same bit that comes from that single number which is right over here we know for sure it's gonna be zero how do we know that so we're trying to prove that the output bit is always gonna be the bit that comes from the single value how do we know that well first i'm going to prove to you that this portion of the xor operation is always going to evaluate to be zero how do i know that because first of all zeros in any xor operation i don't change the result that means if we had n and n could be either one or it could be zero n x or zero is going to equal n that's pretty simple if you look at a couple examples we could have one x or zero that's going to be 1 we can have 0 x or 0 that's also going to be 0. so basically what i'm saying is we can ignore all of the zeros here so i'm going to scribble that out and scribble that out so then we're going to be left with a bunch of ones how many ones are we going to be left with well it's guaranteed to be an even number of ones i'm not counting this position by the way i'm only counting this portion and we know it's going to be an even number of ones because we have only duplicates here right it's either going to be zero ones or it's going to be two ones where it's going to be four ones etc and we know that duplicates always cancel out one xor one is always going to be zero that pretty much shows that this entire thing is always gonna be zero so uh so this is gonna be zero right and this is either gonna be a one or a zero and whatever it happens to be is going to go exactly in the output because like i showed a moment ago n xor with 0 is always going to be n so that's going to be this bit and so basically what i showed you is not really a formal proof but i showed you an intuitive proof for just one column but of course we could apply that to every single column so what we know is all of this is going to be gone and this is going to be the output after we do xor so we're going to return the correct result for and we didn't use any extra memory now let's jump into the code now let's code it up and we are going to have a result and we're going to initialize it to zero and this is what we're going to store our x or result in the reason we're initializing it to 0 is because like i mentioned any value n xored with 0 is always going to end up being n so this is a good default value to set it to and then we're just going to go through every single value in nums take that n and x or it with the result and then set the result back equal to that and then once we've done that we like i showed in the proof we know for sure that the result has that single number that we're trying to return so now let's run the code to make sure that it works and yes it does as you can see on the left it works and it's pretty efficient so i really hope that this was helpful if it was please don't forget to 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
|
Single Number
|
single-number
|
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,1\]
**Output:** 1
**Example 2:**
**Input:** nums = \[4,1,2,1,2\]
**Output:** 4
**Example 3:**
**Input:** nums = \[1\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
| null |
Array,Bit Manipulation
|
Easy
|
137,260,268,287,389
|
71 |
hey guys let's take a look at number 71 simplified path we're giving an absolute pack for a file simplify it convert it to the canonical path a period your friends current secretary double period moves to the top upper level and we should return the canonical path always begin with the slash their own must be only one single slash between two names the last symmetry must not ending with a training slash so yeah rip since the absolute path okay this is okay so yeah this is higher most okay yeah like this a be a this current so a be go back a go back slightly roots and see site see hmm well the things come into my mind is this is a typical reduced problem right we splits the inputs to different segments and just loop through the segments if you find some in that empty like this we just ignore it if you find that one dot then ignore it within two we just remove the previous one and finally we will have a ray of all the segments if it's MC we join them by slash and of course there's a roots right so adding a leading / wow it's pretty treat leading / wow it's pretty treat leading / wow it's pretty treat straightforward I think we could just use one ninety why Niner one Niner path split switch with this slash yeah this would be array right and further with item Adam it's not empty okay the current could be also ignored so it's empty or current includes Adam and then we get all these segments now we reduce them result array Adam empty if item is double dots over period we will pop right will pop to the last one yeah sure you leave me out of case I'll push it push them out of finally and we will join them okay yeah we will join them by a slash but the dealing slash will be added here hmm this should work I think this is not about algorithms oh we had a sink scientist aver join is undefined oh we forgot to return to my god somet hope it passes oh yeah but it's super slow okay because you're using because we're using so many like beauty methods let and something maybe we could just do it with a traditional traversal we free met this is like a slight slip state machine if you met her slash Wow hmm I don't want to spend too much time on this problem because the this solution seems pretty simple if we're going to do it we need to check if it is slash yeah it's slash and then we say it current it's a slash when we made something I'm not dot then we say it's a segment in segment okay then we met another slash then it's the end of a segment and now it's segment if anyway another one if it's stick segment I know if we made a connect two slashes in a row then we should ignore one of them uh-huh yeah actually it is so this is the like if we don't have the reduce or sled method let's try to do it okay first I think I need that I need a chart a way to how the house the result so there is a route right the route is a slash so I just say slash and finally we will return check enjoy empty now for lick which have assaults through other characters of the past and we need to keep track of the position of the last slash right yeah okay let last slash index if character if it is slash what is always speaking with a slash maybe not anyway so we set it to 1 0 okay if you made another slash we check if there is any animus in it right okay so the SEC would be we could improve it by checking whether last slash is smarter than some other than I minus 1 yeah and then segment would be slice plus 1 and character right oh yeah and now we say if switch SEC case if it's 1 dot ignore it if it's top of that chunk would pop okay now I don't need to do this check pop break in case now okay and pop if it starts break if that break if start we pop for the our case default we can push six in right okay and then so every few Mets the last one like this we need to that is also the ending signal so I think this should be plus one I equals 5.9 or it's slash and then yeah we join 5.9 or it's slash and then yeah we join 5.9 or it's slash and then yeah we join by / / + let's run a code maybe faster I'm not confident about this one Oh home I put home why ah we forgot update to the last index oh yeah run it again hmmm let's submit uh of course we failed wait we get home fool hmm why we so we match the first slash index refers to fast first slash it's not so oh god I made a mistake we will only do modifications about the chunk when there is another slash but the index for last slash must be updated submit again hmm it's a little faster could we improve that again improve this more so what's the time for this so every character will be Travis only once oh and spaced worse every worse would be half of the letters are all half the latest our words right yeah so it will be in / - it's worth space could it will be in / - it's worth space could it will be in / - it's worth space could we improve this maybe I don't need to slice it oh I need to slice it yeah because I need to check with it they are double or dot hmm maybe 1 dot 2 dot go to the last ending mmm yeah I don't want to spend too much time on this problem and we use two solutions may be good enough for this one huh so see you next time bye-bye
|
Simplify Path
|
simplify-path
|
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path.
| null |
String,Stack
|
Medium
| null |
153 |
hey folks welcome back to another video today we're looking at question 153 find minimum in rotated array the way we'll be approaching this problem is by using a binary search but there are a few conditions that are associated with that just to get the final uh the minimum element so let's jump right in the first thing that we need to do is to actually cover the base cases as always so you would the base case in this case would be if nums dot length is actually equal to one that means that there's only one element in the array and you would have to just return the first element because that would be the minimum nums of zero awesome so the other uh test case you also need to check is that it's not rotated at all right so let's figure let's tackle that taste guess as well so it would be numbs dot length minus one and then you check if nums of right if it is greater than and numbers of zero are left that means it hasn't been rotated and then our minimum element would be at the left so you would just return numbers left so these are the two base cases if you don't return anything by this point you would have to do binary search so it would be while left is less than or equal to right and in the end we don't really get anything then you would just return -1 anything then you would just return -1 anything then you would just return -1 awesome so once you're in the while loop you want to get the mid element so you would say intermittent would be equal to uh left plus uh right minus 11 divided by two and as soon as you have the mid element what you need to check is that is the mid element involved uh in actually the area switch and what would how would you do that so you'd say if mid element if it is greater than nums of mid plus one what does that mean so that means at this point there is a switch let's look at an example right so for in our in this case if you're looking at five and this is a mid element but if it is greater than mid plus one that means this is where the array has rotated and you can just return the element at mid plus one you don't really need to think about it this is where the arrays have been rotated so it would be um just returning with plus one but you also need to look on the left side so if nums of mid minus one if this is greater than nums of mid this means that the left element which should have actually been smaller than the element on the right if it if that's the case that means that's where the switch has happened so you can just return the mid element and if these two cases are not hit then you need to check if nums of um mid if it is greater than nums of zero that means the left side of the array has been sorted and it's fine you don't really need to worry about that means there is no rotation of any sort so you need to look on the right side of the array so you just say um left is equal to mid plus one if not you move to um left side of the area and you can do that by assigning right to be equal to mid minus one awesome um so this is actually the solution it's pretty simple if you understand um what are the conditions you need to check uh let's go ahead and compile this uh right of course let's try that again the first test case is okay everything else is okay as well awesome uh let's talk about the space and the time complexity the space complexity of the entire solution is log n uh because it's a binary search and the that's the time complexity and the space complexities of one since we're not really using any additional space to store any data awesome so there's a solution if you have any questions please let me know in the comments below don't forget to subscribe and um like the video i would really appreciate that it motivates me to make more videos thanks so much and i'll see you all in the next video peace
|
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
|
948 |
hey everybody this is larry this is me going over day 24th of the lead code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom which is the bag of tokens you're given an initial powers of p and a score of zero and a back took and you could pay for it you lose and gain one score your score says one you may pay the gaining token power and largest possible score you can achieve ps less than uh so p is less than 10 to the fourth but i don't know if that helps us that much do we get do are we bounded by p n is less than a thousand so we can do some something there so i think my initial um thing would be to oh you don't have to okay maybe i got a little bit confused oh you can play in any order okay then that is just me being dumb because i for some reason i thought you had to go from left to right or something um and for me i was trying to think about various way of using dynamic programming to uh to um to get it but i don't because they are in order oh sorry um because we could play in any order we should sort it to see if we can figure it out um and it seems like the greedy situation seems to be okay which is that we want to i mean this is like almost like buying high selling low right you have x amount of money and then as much as you can you get you pay for tokens uh to get us more money um and then we just kind of take the max score along the way and i think that'll be good uh let's kind of yeah let's do that um and because i'm a little bit lazy so i'm just going to do everything in uh in a deck so that we can get the smallest and the max after we sorted right uh so let's just say tokens as you go to collections.tech collections.tech collections.tech of tokens i think that should work right um and then now so our initial thing is p and we want to do greedy as much as we can but we'll but i don't know if uh if we need to be at the very end so i'm going to just keep doing running max score so okay so now while length of tokens is greater than zero because we have a token we can always uh either buy or sell unless we literally cannot do either which is this case i suppose so can we buy if oh and let's just say score is equal to zero right so if we can buy that i think we want to buy first so if p is uh if current power is equal as you go to p if current power is um greater than or equal to token sub zero then let's get it let's buy this token because that's the cheapest token we can buy anyway so create the score of one and then we check you know we let's say we end it here this may be our best score and then we continue um and also token start um top left so that it removes the first element right the smallest element and then now and then this will keep on allowing us to keep buying while we have money so then now let's say if score is greater than zero then current power uh plus equal to token sub negative one score minus one sad face token stop pop right but i mean and then we continue right uh and then if we cannot we if we don't have token and we cannot buy then we're just done so then after we just break uh and then we just get the best and that's it so basically greedy is my salute my uh thing because the idea is that you can you only want to buy if it's really cheap or they're if you're gonna buy you might you'll buy it from the cheapest and if you sell and you have to sell them uh then you sell it at the most expensive one right so i think for me that makes sense uh i think that's good enough i don't know if any weird edge cases because we saw it anyway i guess negative numbers but that's not available so cool accept it uh so what is the complexity this is going to be dominated by the sorting so this is n log n minus the sorting because we only pop left and pop right so each element is going to be popped at most one so it's going to be linear time after the sorting but you know and this can be done in this can be done over one time but i was lazy as i did it with a deck with off n so you can actually just keep track of the left and the right and then you could do it one time um you're doing a contest it depends on how i feel it doesn't change the code that much either way because this is just uh you know two pointers from the left and the right um yeah that's all i have for this problem short answer is still greedy and yeah let me know what you think hit the like button to subscribe and join me in discord let me know what you think and hopefully this time i don't delete this video see you tomorrow bye
|
Bag of Tokens
|
sort-an-array
|
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed).
Your goal is to maximize your total **score** by potentially playing each token in one of two ways:
* If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**.
* If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**.
Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens.
Return _the largest possible **score** you can achieve after playing any number of tokens_.
**Example 1:**
**Input:** tokens = \[100\], power = 50
**Output:** 0
**Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score.
**Example 2:**
**Input:** tokens = \[100,200\], power = 150
**Output:** 1
**Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.
**Example 3:**
**Input:** tokens = \[100,200,300,400\], power = 200
**Output:** 2
**Explanation:** Play the tokens in this order to get a score of 2:
1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.
**Constraints:**
* `0 <= tokens.length <= 1000`
* `0 <= tokens[i], power < 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
|
Medium
| null |
1,376 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1376 time needed to inform all employees a company has n employees with unique id for each employee from zero to n minus 1. the head of the company is the one with head id each employee has a direct manager in the manager array where managers of i is the direct manager of the ith employee and manager head id equals minus one because obviously the head of the company doesn't have a manager also it is guaranteed that the subordination relationships have a tree structure the head of the company wants to inform all the company employees of an urgent piece of news he will inform his direct subordinates and they will inform their subordinates and so on until all employees know about the urgent news the ith employee needs informed time of eye to inform all of his direct subordinates uh so after informed time of i minutes all the direct subordinates can then start spreading the news and we want to return the number of minutes needed to inform all the employees about the urgent news so we read the question prompt but how do we actually solve this question let's look at a simple example in this example we have six employees the head of the company has id2 this is the manager structure and this is the inform time so let's build the tree here so we know that there's six employees and we know that um you know the head of the company is two so this guy is going to be the parent so basically the manager of everyone so for employee zero they have the head of the company as their manager so this employee 0 will have a node uh to the head of the company same with employee number one so they will have them so employee 2 um obviously that's the manager the head of the company so they don't have a manager because they're the head of the company so it looks like three four and five all actually report to the head of the company so this is going to be you know like an nra tree with only one level because it looks like all of the people just report to the head of the company so we can see the you know weights that it takes to basically uh inform people right so you know how long does it take for zero to inform all of its subordinates well it's gonna take zero time because obviously they don't have any subordinates same with one same with three four and five and all we're interested in this case is actually just the time for two to inform all of its subordinates which is one so in one i guess email or phone call it can inform all these people so you know in this case our answers are going to be one because we can inform all of our subordinates in one time but what if our graph was more complicated right what if we had like six and seven here and then like eight and nine and then maybe nine has reports for ten and eleven well this is starting to look like basically like a graph right we can start at the top and then traverse down and add all the times up because we know what they are in inform time we can build our graph using this um you know manager array so we can basically know who is the manager of who we can build our graph you know we can say okay well the people who report the subordinates of two are going to be who zero one not two three four and five and we can do the same thing you know in our example here let's say the subordinates of zero are going to be this like six and seven some ordinance of one they could in this example be um you know what is this gonna be eight and then you know on and on we build our graph and then all we need to do is perform either a breath for a search or a depth first search to basically just add up all of the kind of you know paths and that's basically going to be how we solve this problem all we need to do is take our original input transform it into a graph and then perform a simple traversal of that graph adding up our values as we go and that's going to be our final answer so this diagram as you can see is getting a little bit messy so i think at this point what we should do is we should simply move to the code editor where we'll walk through the solution line by line and we're just going to code it up and it should hopefully be a lot clearer so i will see you in the code editor we're now in the code editor let's write this up so let's handle a simple edge case here which is actually one of the examples that lead code gives us in the case that there's actually only one employee in which case there's no one to inform so we can simply return zero it could also be the case that we don't have any employees at this company in which case it's also 0. so we're just going to make a check here we're going to say if n is actually less than or equal to 1 then we just want to return 0 because in that case there's no one to inform cool let's set up a variable to keep track of our final answer and we'll just call it res and we'll set it equal to zero and at this point what we need to do is we need to define our graph which is going to represent the you know structure of our you know org chart here right so we're going to say graph and remember that we're going to be mapping each manager to all of their subordinates so basically it's going to be a list of people who report to them so we're going to say collections dot default dict and oops i spelled default wrong default dict and we're going to pass in a list now let's actually build the graph so we're going to say for index parent in enumerate manager and remember the person at the ith index in manager whatever that value is represents their manager right so for the zeroth index and manager it represents who their manager is so basically what we want to do is we're going to say graph a parent actually uh yeah we'll say graph a parent uh dot append idx so basically we're adding the you know person at index whatever to that parent's list of subordinates so that's going to be how we build the graph now we actually need to do our graph traversal and get our final answer now if you've watched this channel before you know that when presented with the choice of doing it either in a dfs or bfs manner i always opt for breadth first search because i don't like to deal with uh recursive solutions and we have the issue of stack overflow if our you know org chart is really large so i just stick to breadth first search and i find it much easier to code if you like dfs do it that way but this solution is going to be with breadth first search so let's set up the queue that we need to use so we'll say q equals collections deck oops deck and we need to initialize our queue so at each iteration of our queue we want to know which person we're at and how much time we've taken to inform uh the people so far so we're gonna start at the head obviously we need to start at the top of the company and the initial time is going to be that first uh amount of time it takes to actually reach all of the subordinates of the head of the company so we're going to say inform time of whatever head id is so that's the time that we've taken so far now we just simply need to perform our bfs so we're going to say while q and what we're going to do now is we're going to pop our items from the queue and remember the first element is going to be the current employee and the second element is going to be the amount of time that we've taken so we're going to say cur employee and the current time is going to be q dot pop left now what we want to do is actually update our result so we're going to say res equals the maximum whatever the current result is and the current time so that's going to be us updating our solution here and what we want to do is um we want to basically go through all of the children and then you know continue through our bfs so we're going to say for uh we'll call it report because you know we're now going to go through all the people that the current employee has as reports so for report in graph of current employee we're going to say q what happened here with my indentation oops sorry this is really bad right here uh cue the append and we're gonna add the you know the report right and we're gonna add the current time and now we need to update it with the amount that it's gonna take to actually inform that report so we're going to say inform time of report and that's what we need to add to the queue at the end we can simply return our results here so let me just make sure i haven't made any syntax errors and it looks like i haven't so we can go ahead and submit this and once this finishes running we can see that our solution is accepted so what is the time and space complexity of our algorithm here well let's think about it so the first thing that we do is we are going to have to build this graph and that's going to require us going over you know the manager array so to build the graph is basically going to be big o of m where m is the amount of people in this manager list uh so basically all the people that we have in our company right we need to know all their structure so actually we'll just call it n because that's how it's given to us so n represents the number of employees then what we need to do is perform a breath first search over our graph here and you know perform all of this logic to calculate our result here and we know that a bfs over our tree is just going to take big o of n time because we have to touch every single node so our time complexity in the end is going to be big o of 2 n but we know that asymptotically this is the same thing as big o of n so similarly with the space complexity actually storing this graph is just going to be big o of n so it depends on basically the um you know the amount of people that we have and since we can't really have bi-directional um bi-directional um bi-directional um things in our graph we don't have to worry about it being really complicated we're like everyone reports to everyone it's gonna be a tree structure so it's top down uh so it's just gonna be big o of n there for the actual graph itself and then the q uh again for breadth first search your space complexity is gonna be big o of n so like in the you know time complexity we have big o of 2 n but like we previously mentioned it's just going to be big o of n asymptotically so that is how you solve this question not really complicated i think this is another one of those questions where you get some sort of input you need to transform it into a graph and then from the graph perform some sort of traversal in this case it's just a depth first search or breadth first search and you know do some sort of logic and you'll come to your final solution so really not that complicated i mean this part here uh basically half of the question is you know just doing a standard breadth first search and then you've got two lines to actually build the graph so it's really not that complicated pretty standard medium um definitely want to know if you're interviewing at google because they'd like to ask this question according to the uh lead code statistics here and it looks like amazon has also asked it anyway if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this please consider subscribing to the channel i have a lot of videos uploaded and i plan to make a whole lot more so if you don't want to miss those videos please subscribe otherwise thank you so much for taking the time out of your day to watch this video and have a great rest of your day bye
|
Time Needed to Inform All Employees
|
time-needed-to-inform-all-employees
|
A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that the subordination relationships have a tree structure.
The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.
The `i-th` employee needs `informTime[i]` minutes to inform all of his direct subordinates (i.e., After informTime\[i\] minutes, all his direct subordinates can start spreading the news).
Return _the number of minutes_ needed to inform all the employees about the urgent news.
**Example 1:**
**Input:** n = 1, headID = 0, manager = \[-1\], informTime = \[0\]
**Output:** 0
**Explanation:** The head of the company is the only employee in the company.
**Example 2:**
**Input:** n = 6, headID = 2, manager = \[2,2,-1,2,2,2\], informTime = \[0,0,1,0,0,0\]
**Output:** 1
**Explanation:** The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
The tree structure of the employees in the company is shown.
**Constraints:**
* `1 <= n <= 105`
* `0 <= headID < n`
* `manager.length == n`
* `0 <= manager[i] < n`
* `manager[headID] == -1`
* `informTime.length == n`
* `0 <= informTime[i] <= 1000`
* `informTime[i] == 0` if employee `i` has no subordinates.
* It is **guaranteed** that all the employees can be informed.
| null | null |
Medium
| null |
972 |
cool 1972 equal rational numbers come in strings SNT each of which represent non-negative SNT each of which represent non-negative SNT each of which represent non-negative rational number we turn true if and only if they represent the same number the string may use for M is used to denote that became part of a tional number in general rational becoming represented using up to three parts and individual part and on in the repeating point and a repeating point the number will be represented in while I'm doing it following three ways and then your three ways okay cool and you have to see if they are equal is that it okay yeah knowing but not so bad except for maybe this one good to rounding up three okay okay I mean I think we just passed probable dominance into a rational number class maybe that's why the way to go exactly knowledge it is indeed go but that's just play around with destroy we'll put a parser here what do we need let's put them up into there okay no integer part is equal to string that's like - is that good enough that's like - is that good enough that's like - is that good enough I have to go mama - Python good okay so that actually just what I was hoping it would do change the name this is fine tell me we have to repeat we move two fingers in look at us No that's now play over before so just make sure that this gets it my event area also some stuff like actually it's this one that's a good one huh yeah that is annoying okay not undoable I mean is that cheating also I didn't - one without repeating also I didn't - one without repeating also I didn't - one without repeating that sir hmm yeah just to thing I'm gonna stow a string okay that's fine that's like drones okay so that's Dylan on reviewing port what's fine you know you can't do that because it shifts to shift the pace a little bit can't have a mmm that's messy okay that's fine we don't check day today okay let's double-check our input and okay let's double-check our input and okay let's double-check our input and what we expect things to be and then we could play around with it now okay sounds reasonable no even that's every time it doesn't make this easier shouldn't change anything because it will be there because if this is zero damage is a whole number anyway okay now we have let's figure out that this is the other okay so the non-repeating part is other okay so the non-repeating part is other okay so the non-repeating part is you go two digits mm-hmm of the cetera to nominate I'm mm-hmm of the cetera to nominate I'm mm-hmm of the cetera to nominate I'm gonna do numerator is you go to not that was enter nami pier progressive way deliberately but that's okay this is what I okay so is that right yeah okay so I think this is me right 166 out thousand won this is how I ever okay being here and waters a repeating digit mean okay so yeah it means 52 our fifty 1299 that is here it means 25 hours nine ninety you said how that works don't know anymore it's a good look because that's 525 no it's 500 plus 25 of onion no that's not 25 oh I'm using a calculator just to make sure okay so this twenty five out of nine ninety okay so that means denominator is you go to the length of knowledge that's the number of nines like very hacky but I think that books maybe off I want and then the time start by the denominator that we had previously I think maybe this could be soon and I put too much stuff okay should be 990 why it's just 90 okay Oh so let's skip this one which is waterside no I didn't print it out good it's just also like one of those ponds of a lot of that cases maybe I'll meant to say repealing that's why everyone's a little weird okay 2012 9925 of 1991 I was actually surprisingly quick okay I'm happy with that I'll be printing something in a weird way okay not repealing because I didn't know and now we have so this is the number that it represents in some way you know now you have self numerator it's equal to okay actually I guess maybe there's just two cases lieutenant enumerator is equal to so there's no repeating there's no not repeating portion so it's just a integer times the denominator question numerator how about telling you is you go to just the denominator otherwise if you have repeating numbers 10 is this maybe not really all right it's this times 2 repeating down later and it's this plus numerator times pause repeating and now let's print this out hmm and it sure is not an integer as I wanted but okay so okay I could we will just print and then just kind of loud voices okay it's not know how I do I don't remember how to do our string my easy string stuff okay mmm I want to cheese et it maybe not maybe it's fine now but let's make sure that this is right I don't I think this once were yeah didn't have enough time something let's print this so tight and my daddy is here the TDOT I know will to Dottie that's not right it and then be like the first one that's right weights me fine I don't know it's not it's off by a factor but let's bring this back again so 99 is 25 over 9 ID and that should be say five times nine ninety plus 25 you just hop a little bit maybe is it myself night wait I get it no way now okay let's forgot to multiply 1/3 I feel like there's also like a lot of random edge cases that I'm not considering right now it was hard but I do get to get this one like which is a happy about yeah they're just a minute they say think of well okay there's no period that's the one that I actually remember what I was typing I was like god this has a period for no reason but then I didn't add in that test and that's what happens cursed you hmm okay we get another oh well actually got a render second time the first time I guess I should have gotten it quite a bit but it's still happy enough that got it on second try just took 22 minutes ish which was a lot of typing so maybe 59 to code I mean it was a lot of oh no buddy not confident typing I guess if I put it so it's like high-stress typing put it so it's like high-stress typing put it so it's like high-stress typing because I feel like there's an off by one just what do you weigh close to something that I've done cool yeah I mean I think this is a hard form just because there are a lot of edge cases I think the think that I would try to do and that's what I've been to try to do a little bit is just to make sure that maybe if I took out it in put out faster but the first way I try to do is kind of convert this into a way that like they're just fewer opportunity for educators I think I mean they tell you kind of the three type of numbers to look out for I think but we're not using Python I would also worry a little bit about intent doubles and stuff like this and kind of mission I don't know they tell actually is less than four so maybe I need to do worry about it that much I could also have like one thing I did think about was maybe the uh you know symbol find some fraction but you said you what I do is I convert each of these numbers to a fraction containing you know the numerator and the denominator and then just compare it that way and everything here in the code does just kind of checks for that I guess one thing that yeah the one thing to note is kind of figure out and I mean so is just something that remember I don't know if there's a easy way about it maybe it's Google but we quickly gone into I don't know how funny that is or it's not all the time but like you know converting the repeating number to a fraction I really do remember it's like you know over 99 or some equivalent of the fractional parts but then I actually might not have done it but yeah once you convert that then you have like you know a couple of fractions to kind of sum to each other and then that's it that's the way I'm thinking about it because I have three parts that are each fractions I guess and maybe I could write over the fraction class maybe I could have cleaned this up a little bit as well where you know you have two integer part you some diverged the non repeating part which is just an easy you know x over some power of 10 which is what I did here and then the repeating part which is another number over some number of composers of nines and tens yeah and that's kind of how I and you have those three fractions you sum them together to get one mega fraction or pick a fraction which you can reduce or simplify and then you compare it to the second one which you do the same thing with and that's how I did it this is very tricky to get right on a whiteboard or PI on an interview but you can go over a lot of these concepts or a lot of it yes on an interview maybe depending on the kind of individual you might not necessarily need to go you know exactly pixel perfect but the concepts are kind of you know easy to figure out but I don't know about this is a new question it is a good to program one this is high stress for each line versus something that you might have necessary done before must be allergic to something excuse me that gets deployed flowing I guess but yeah oh for you know a fun ish problem and so I'm like half sneezing but yeah but over yeah punished problem I mean I actually thought there will be more edge cases than there would be to be honest but when that's so bad it turned out I mean I did have to have one but I had in the back of my mind I forgot about it but yeah
|
Equal Rational Numbers
|
knight-dialer
|
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4`
| null |
Dynamic Programming
|
Medium
| null |
279 |
oh this question is perfect square so you are giving the integer and so you have to return the base number of perfect square uh let's sum up to the n so the perfect square represents 1 4 9 16 and so on right so imagine there's an index that is not perfect square then definitely the value is not going to be what uh so you probably won't have the update uh value for the non-perfect square index right for the non-perfect square index right for the non-perfect square index right so when i equal to zero right if n goes to zero uh there's only zero way right if i include one is a perfect square of itself so it is one how about two is actually equal to one plus one right one is a perfect square one plus one is the perfect square right so this will be two and then three is going to be one plus one right this is three and then four is actually equal to a perfect square is actually equal to four right over here right so it's gonna be two uh two to the two right so this is x equal to one and then five is actually equal to one plus two to two right so this is actually good too and then you can keep doing this so if you notice like we are actually grabbing the perfect square element uh dp variable right to update our uh the future index if they are on the if they are the uh perfect square index right so we will definitely have to try very well transverse the earn from what from one to uh to n right and then when we want to calculate the perfect square right we basically need to uh traverse another uh this is i and then releases j and then we have to traverse the perfect square for j in i so imagine i minus the j squared right if this is greater or equal to zero right imagine for four minus two to a two right if this is square equal to zero then we can grab the element in the dp and then we plus one right so this is the this is pretty much ideal right so uh let's start coding so uh we have well we have the array dp and new game plus one the reason why i use some plus one is because the base index is starting from zero and then i can traverse so i put one i listen and then i will just initial my i uh my b picture index block so this is a big number right so dp 100 is going to be equal to 100 right but i would keep updating based on my uh based on my um i'm i minus j square right so j equal to one and then j minus uh sorry j with one i minus j squared right this is squared equal to zero and then j plus so this is a square of j and the i is the number i'm traversing so if this is valid right i can graph the element to update the dpi method mean ppl i comma is either dpi or dp um time minus j times j right and then plus one right so it so think about i equal to four right and then j equal to two times two equal to four right so four minus four is actually equal to zero right so imagine this is four and this is two 2 times 2 right so you will get what you will get dp 0 is actually what we didn't touch anything in dp 0 right db 0 is 0 then we plus one which is gonna be one and then this one initially what uh when i equal to four then dp4 equal to four right now i know this is a minimum so i will graph the four comma one so which one is the minimum dp4 right this is going to be one so i update my dp4 equal to one right over here so at the end i will just have to return and this is pretty much it right so let me submit so let's talk about the timing space for the time this is all the fun and this is actually n squared uh square root of n sorry square root of n right so it's all of n times square root of n so this is the time so on square root this is the time and then the space this is all open right so this is a timely space capacity so if you have any question i leave a comment and i'll see you next time bye
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
1,727 |
hi friends uh welcome to followup uh in this video we're going to look at problem 1727 largest submetric with rearrangements so our strategy will be a combination of sorting and a flavor of dynamic programming so we are going to first look at the problem dest and then we look at the analysis or algorithm and finally we code the algorithm so here uh we are given a banner Matrix of sets M by m and we are allowed to rearrange The Columns of the Matrix in any order so we want to return the area of the largest sub Matrix within Matrix where every element of the submatrix is one after reordering the columns optimally so here we have two exam uh three examples if you look at example two it's just a one row is very special but now if you uh put all the columns with ones in the beginning or at the end so you're going to have one so the area is three right so for the first example so notice that for the First Column there are two ones consecutively and for the second column there's one consecutively which is in the middle and well the last column it has three consecutive ones so if we uh switch the uh last two row or two columns so we're going to get configuration like this and then we look at the bottom um left corner we are going to have a area four right so that's the interpretation for this these two examples so similarly you can do uh for example three so here the main constant is uh is that the total number of uh elements in The Matrix is bonded about by 10^ 5 so The Matrix is bonded about by 10^ 5 so The Matrix is bonded about by 10^ 5 so um basically uh this number is a distant large number we need to think of uh temp complexity so with that St we can look at uh the algorithm so I guess for this problem if we do it just manually or do a screening by human so it's very simple to get the area but the thing is to transform or code the intuition so um main con main point as we mentioned is to uh count the area strategically right so the algorithm is the following first so we want to find for each column the number of consecutive ones ending at a certain position so this the first step in the algorithm that is for position in each column we want to get how many consecutive WS ending at that position so this is obviously a simple DP right so given a position r C that is the column C right then if the current element at RC um is one right then the DPR c will be DPR minus one c meaning that uh we add the current to one at this position so if the Matrix element at this position is zero then dprc would be zero because the number of consecutive ones in that position will be zero so once we get the DP table we can do the counting and updating the area so here we can do sorting from high to low for each show so notice that the order is crucial for the counting so this part actually we can first do coding and then come back to explain more vividly so in real coding we could embed the second part in the first part so with that said let's look at the coding and then we are going to explain the this part so we're going to do sting from high to low for each low all right so first let's get the number of rows number of columns and we set the answer to be zero right lens The Matrix and the first row equals the length of the columns then we get to set the answer to be zero at the very beginning then first we finish this part right so this is very straightforward so for let me so for I in range M right so what we are going to do is so for J in range n right so if the current element and IG so you can map the IG to be RC right the same thing so if the current uh element is not zero in other words is one and uh I is greater than zero so we can write like this is more specific right I is greater than zero right so what we're going to do is we're going to do Matrix i g equals 1 plus Matrix i - 1 G so in other words we plus Matrix i - 1 G so in other words we plus Matrix i - 1 G so in other words we do this operations in place so then v a row is um done so we can find the largest um Matrix ending at IG right submatrix size so this actually we can do four key this the index for X in enumerate uh so we can sort U Matrix I so en SED um Matrix at the index I so here we use reverse right so reverse is true but if we start from uh what so here we are using this index key starting from one so you will see what's the meaning so then the answer is object like this the max the prage and then uh we X is the number of consecutive um WS ending at this position in the corresponding column so we're going to get K times this x then we are going to return the result afterwards so this the full solution I guess the point uh left is this the explanation for this uh for Block but before we do that let me first test this code yeah it passes the first example so now let's look at the generic case yeah it passes all the generic cases so now let's come back to this one so first let's you let's use uh the first example to do a walk through right so basically then you can understand uh this four block so then if we do this one so the first row is 0 one right so here we have one also we have one and then this one because this is a one and the pr we have another one so the number of conc to ones any here this column will be two so now let's look at this one so the Cal so because this the one and then we can do two right so this one plus the pr the last uh last row and then we have because this is zero we do not do right so then we have U uh three right because this the one and the then the number of ones to ones and this position is 2 + ones to ones and this position is 2 + ones to ones and this position is 2 + one so we have this one then at each position we want to do this counting so we sort the rows do this one for example this one if we sort the rows we get 1 z so in other words at this row at each because if it end at zero there's not a valid submatrix then we consider the one any end here so this is just one block so then it gives a maximum area one right so if we look at this one so if we sort it we are going to get uh 2 one so if you look at this one because uh this one the number of uh um consecutive on and here is two right then because this index is if we use one indexing is one so we have two so this Matrix correspondent two so here you see it's corresponding to this part right then we look at this position so this position is the second elements in this zow after we do the sorting and this one the number conc ones at this position in this corresponding row is one but because this one is larger than one because we are sorting in a decreasing order so it means that all the PRI rows all the preious uh rows corresponding to columns have more consecutive ones in other words we at least have a matrix has uh height one and length two this gives us um so here this gives us error two for the this element this one gives another element that is two so if you look at third uh this one the one here because we are sorting in the decreasing order it means that all the previous uh elements corresponding to columns have one or more cona ones in the at this row so this way we have this is we have at least three * one the area is three least three * one the area is three least three * one the area is three right so this row actually gives largest the column three so now if we look at a third row right so we're going to have 3 2 0 so first let's understand if any zero for sure the corresponding area should be zero right so if you look at the first element which is three it means that we have um a area this three * what it's corresponding to this one * what it's corresponding to this one * what it's corresponding to this one right this last the column and then if you look at two so this the main point so it means that in this row all PR rows have more or equal more than two or equal to two um consecutive ones therefore so this position it gives us at least because this is the second element if we use V indexing two times the smaller one that's two so 2 * 2 that the smaller one that's two so 2 * 2 that the smaller one that's two so 2 * 2 that is four right so this gives area of four so the last one because it's zero it gives zero so overall the largest one is four all right so the return for this one is also four so this is um example one so now let's look at example two right uh example three so we have one 1 Z 0 1 so now if you look at the DP Matrix right so we get one zero so now we have two right because this any other one above is one so here is zero so we just have zero and here is one we just have one and then we look at the first row it's already insulted order right so this one because it's the first one it has least area one right so this one because all PR one is larger no less than this one so we have this is the second element we have at least area that is 1 * 2 so for this zero that is 1 * 2 so for this zero that is 1 * 2 so for this zero corresponding to eror zero now let's look at the second row right so here we have let's first sort it so it's 2 1 Zer then uh this element corresponding to because this first of the result it gives us an area that is 1 * 2 so 1 * 2 gives us an area that is 1 * 2 so 1 * 2 gives us an area that is 1 * 2 so 1 * 2 so this one so because this is a second element all the previous one has greater than or equal to one It means that we have an um height one and length two um area so this is zero so we get zero so overall since largest one is two this row largest one is also two so the return will be two so now let's look at the code again so first I get all this m in and answer uh initial state right this is very trivial and then for this double for loop we're going to set down the um DP table but I don't need to finish setting the DP table to look at each row so once a row is set I can look at this uh check this each row the contribution to the fin uh or update the answer state so here I for this index X after we sought reversely so as we mentioned the reverse first sarting or starting from high to low is crucial and also we start from what so because at each position as like here so we s in the from high to low at this position all the previous number is larger than this two it representing that so the corresponding columns has a more uh at least equal uh conc to V therefore at this position two the corresponding area is the height that is two the length will be the number element that is two right 2 * 2 that's four so uh that's the right 2 * 2 that's four so uh that's the right 2 * 2 that's four so uh that's the understanding for this part so with that said basically that's about it for this specific problem so here the main point as we emphasized at the very beginning is how to count the area strategically right so and uh so the overall algorithm uh is a combination of the idea of DP and uh the sting but the sting order is very crucial for Community counting the area or updating the area so with that said let's basically about it for this video you're welcome to comment or share more thoughts on this kind of problem in the comment so if you like our or if you like to practice more uh problems you can follow up our Channel or look at the different playlist within the channel thank you
|
Largest Submatrix With Rearrangements
|
cat-and-mouse-ii
|
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`.
|
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
|
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
805,949
|
1,354 |
Ajay Ko Hello Everyone Welcome to Lotus Temple in the World Today Reminded After Minutes From Multiple Subscribe Must Subscribe Prithvi Singh and First Intact Sun Robbie Williams Target Are Isi Channel Ko Subscribe And subscribe The Amazing Subscribe to A 100 Dresses and Attractive Figure Planning To Conv Withdrawal subscribe The Channel subscribe and subscribe the Kal Subah Ke Thru At Every Time The Highest Value Is The Last Updated By Mujeeb Suryavanshi The Receiver And 9359 Subscribe Now To Receive New Updates Reviews And Subscribe To Kal Subah Logic Will Have To Find The Largest Element And our last updated position and will have to put the previous values in the attack took place value values in the attack took place value values in the attack took place value proposition subscribe models subscribe bread servi and interpretation of yesterday morning point to point and use this technique to find your valuable update for its largest and subscribe kare subscribe our Channel subscribe and subscribe 12345 internship notification unconfirmed close loop and hear date of this is gold channel subscribe to that election se ain ax is manly used cars and hiffin 31243 present people subscribe to are yes first they want to declare ver cute Yes you do that and inside also appoint the pilot to short toe values based don't descending short toe values based don't descending short toe values based don't descending order on and tell your off target happened on Sunday and Suresh ji award all award given in tears from foreign tour why and total number of collected Surya 128 Tilak In switch plant which digest value will be written by subscribe and subscribe against jhal dat this note like rs list total no the important phone no 220 not where going to find the model of exam drishti total hello friends welcome to back to And Total Continue Element Will Be Easy For Industrial Estate Which Of The Total Students Will Monitor Next Time And Finally Add New Element And Waste Element To 267 Timely Return Paper Is To Select Ronit Roy Is To Ajay Is To Select Submit Is Lut Gya Sallu Saks Updated On Jo Alarms Sake Thank You For Watching My Video Like Share And Subscribe To
|
Construct Target Array With Multiple Sums
|
find-players-with-zero-or-one-losses
|
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure :
* let `x` be the sum of all elements currently in your array.
* choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`.
* You may repeat this procedure as many times as needed.
Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`.
**Example 1:**
**Input:** target = \[9,3,5\]
**Output:** true
**Explanation:** Start with arr = \[1, 1, 1\]
\[1, 1, 1\], sum = 3 choose index 1
\[1, 3, 1\], sum = 5 choose index 2
\[1, 3, 5\], sum = 9 choose index 0
\[9, 3, 5\] Done
**Example 2:**
**Input:** target = \[1,1,1,2\]
**Output:** false
**Explanation:** Impossible to create target array from \[1,1,1,1\].
**Example 3:**
**Input:** target = \[8,5\]
**Output:** true
**Constraints:**
* `n == target.length`
* `1 <= n <= 5 * 104`
* `1 <= target[i] <= 109`
|
Count the number of times a player loses while iterating through the matches.
|
Array,Hash Table,Sorting,Counting
|
Medium
|
236
|
1,525 |
Everyone welcome to my channel its all the problem is 1525 number of good based on split string so in this problem it is give one spring tools and have to speed string into subscribe And subscribe The Amazing possible fluid ago a sec that apps bba so how many Total Possible Springs Weekend With First Weekend Hair Second We Can Do Hair Third We Can Do Hair Fall We Can Do Hair And Difficult Veerva Possible Cut Sorry for the length and you can do and minus one Karz So Amangal - 150 Check the minus one Karz So Amangal - 150 Check the minus one Karz So Amangal - 150 Check the Labs Hai So Let's Difficult The First Chief Person Number Of District Collector Egg White Heads 300 Behavior Will Be The Left Side Oil Seeds Pe Android Phone Number Of District Collector Dr Zyada Ride For Distance Pimple It Is Not Even A Good Way Of Making Third AC In Hair Will Have A Number to the number of District Collector and always see the light that will be amazed August 2002 District Collectors and the last one is paying bribes is not good at the total number of problems in the temple run away from you Pinto and attend check Drishti Number of Characters In The How Will Check The Distinct Collector Ne String To Be Just Uses Of Destruction And Put All Characters Of The Scene After The End Subscribe Button Vishal This They Will Not Let You See In This Problem The Like Share Subscribe Now To Solve this problem in time will reduce the beneficial processing and subscribe that sc admit b that android previous tire fix are which will hold number of district character dashrath intex battery create a professor at se hair village district number one hair character 1282 gives pain And Share And Subscribe To A Suffix Between This Folder From Right To Left And Create This Se Soaked From Right To Left Is Warning 203 A Freelance Services From Right To Left Of West Indies And Is Dress Preprocessing Soega Will Count Distinctive Again Will Listen And One Sweden Know You For Everyday Items Which Can Cut Hair Top Tips Hair Wicked Hair None They Just Need To Check What Is The Value Of Our Picks After - 150 School Details Let Us See After - 150 School Details Let Us See After - 150 School Details Let Us See And Effects Of I So This Will Give Correct Total Number Of District Collector Zindagi Subscribe To Ki Is Par Fix Of I - 121 Fix Of I - 121 Fix Of I - 121 Who Is Equal To Suffix Of A Suffix Of I Is This Is It Is Our Good Very Good At Will Increase A Plus Correct Other Wise Notes Will Check Exit Poll No One Will Be Considered Them Arghya cities equal states will be 110 able it is equal and rotten eggs subscribe and the are will form using set up are selected for example with example is so in this example behave that a to 100MB se example will have that CBI Chief Editor A Being A Is Lead So Let's First Form A Prefix A Professor Said Saudi Will Want To Three 49 From Left Right To Live With Suggestion Three MP3 496's Gum 100 To Not Equal Want To Do Not Quite A Solid Broken subscribe and subscribe this Video Subscribe subscribe and subscribe the Video then subscribe to subscribe our that we similarly they will update here in do subscribe size of the set off subscribe and subscribe to subscribe our the service will be accepted quote and share the time complexity is open back to times where running only Reduced to find and space complexity and will find so friends this time complexity of 10 celebs complexity of oo hua hai Darshit Saunf Like my solution please hit the like button and subscribe To My Channel and press the Bell Icon to get given and notification incomplete new video You have any questions thanks for watching
|
Number of Good Ways to Split a String
|
queries-on-a-permutation-with-key
|
You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make in `s`_.
**Example 1:**
**Input:** s = "aacaba "
**Output:** 2
**Explanation:** There are 5 ways to split ` "aacaba "` and 2 of them are good.
( "a ", "acaba ") Left string and right string contains 1 and 3 different letters respectively.
( "aa ", "caba ") Left string and right string contains 1 and 3 different letters respectively.
( "aac ", "aba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aaca ", "ba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aacab ", "a ") Left string and right string contains 3 and 1 different letters respectively.
**Example 2:**
**Input:** s = "abcd "
**Output:** 1
**Explanation:** Split the string as follows ( "ab ", "cd ").
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
|
Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning.
|
Array,Binary Indexed Tree,Simulation
|
Medium
| null |
470 |
hi guys welcome to algorithms made easy today we will go through the day 28 problem from obviously coding challenge implement random 10 function using random 7 function please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update given a function which generates a uniform random integer in the range 1 to 7 write a function which generates a uniform random integer in range 1 to 10. it is specifically mentioned do not use systems math dot random function the very first method that we will be seeing is rejection sampling there is a wikipedia page dedicated to this topic if you are interested the link to it is in the description let's understand the basic idea that we will use in our video since we are given a function that generates a random number between 1 to 7 and we need to find out the number between 1 to 10 we need to wind up the scope thus what we do is we take this matrix that has 7 rows and columns in this we write the numbers 1 to 10 repeatedly we see that the first 4 chunks of the number 1 to 10 are complete but this one has only 9 digits so we need to reject any number or index that falls in this sample now how do we know if the 7 appearing is from this one and not from the above sample it is simple let's see it with an example we will try to find a number between 1 to 10 using the random 7 method we will use the random function twice once to calculate the row number and once to calculate the column number and then return the number at that position in matrix now if the function goes beyond 40 we recalculate it as it falls in the red part suppose we get row as 5 and column as 4. the index we need is for number 6 highlighted how do we calculate the index if we see manually we know it is at index 26 that is it is the 26th tile but how do we calculate it programmatically we see that we need the elements sum from all the previous rows plus the number of columns from current row this gives us the required formula shown so now that we have the index we need the number it has since the grid has numbers 1 to 10 we can easily find the number using number mod 10 but we need extra care for indexes in multiples of 10 as in this case the number mod 10 gives 0. so we can use either of the two formulas shown so as to get rid of 0 while performing the modulus operation for our example it gives answer as 7 or 6 both are acceptable at the end we return the calculated number year's algorithm for the same the second method uses similar base understanding but a different approach to create the number rather than calculating the index we create a two digit number less than 40 using this technique the random seven function gives me a single digit we need to make it two digit by performing the decimal digit creation operation so for units place we simply use the random seven function while for tens place we multiply the output from random seven function by ten the number generated with random 7 function is from 1 to 7 so we need to convert it to base 0 by subtracting 1 from it this will generate the numbers from 0 to 66 but as we need the numbers only from 1 to 40 as seen in the previous approach we will discard the numbers if they are greater than 40 and regenerate the random number in this case taking this example as 54 becomes greater than 40 we need to discard this and generate a new number 32 satisfies the condition so we return number mod 10 plus 1 as we did in the previous approach and return 3 in this example here's the actual code snippet for the method you can also check out the link to the code in description below thanks for watching the video please like share and subscribe to the channel also let me know in the comments what you think about it keep learning keep growing
|
Implement Rand10() Using Rand7()
|
implement-rand10-using-rand7
|
Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API.
Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`.
**Example 1:**
**Input:** n = 1
**Output:** \[2\]
**Example 2:**
**Input:** n = 2
**Output:** \[2,8\]
**Example 3:**
**Input:** n = 3
**Output:** \[3,8,10\]
**Constraints:**
* `1 <= n <= 105`
**Follow up:**
* What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function?
* Could you minimize the number of calls to `rand7()`?
| null | null |
Medium
| null |
1,319 |
Hello hello guys welcome back to take devotion in this video you will see the number operations to make network connectivity problem from that list number 1319 and strong Rahul Gautam so let's posted problem statement in this problem during computers number 102 - 1800 made this network computers number 102 - 1800 made this network computers number 102 - 1800 made this network connection problem Data is equal to 1 representatives Connection between computers and computer CARS network Computer network between Delhi and computers Between there computers to make the return Minimum number of times you need not to make the computers where connected through it is not possible to monitor - 121 K Is to connect with Agra to make a single component by using only the redundant as 16 test series from this is quora to components in the first man to remove the number of seats will increase in uric acid remove and not increase on its own thank you still remains the same 2009 use this is not possible to connect to the quote your is one five number of business 100 minimum you should have required only three ranges in order to connect all notes into a single fold so Edge and basically extra so you can remove this thank you can also removed sh and tell this complaint will be connected at the time of hanuman will be connected via this 2012 ajuan in this case no you can suggest you just in order to connect 3515 400g Notes Will Come Under A Single Boys This Possible To Connect With Notes22 Operations At Do Subscribe Configuration Mid-Day-Meal This And Time Configuration Mid-Day-Meal This And Time Configuration Mid-Day-Meal This And Time Configuration Subscribe The Number Of The Third Jai Hind Desh Ke 100 Were Heavy To Number Of Complaints In The First Component You Having one match second component1 inch 9 in the first quantity remove this is the number of units 11009 rent in the way you can remove this is not attended for written test will return minus one is not possible to all of you having it is not having any of You having to the number of but minimum wagers to connect all notes will be minus one of you having sex phone number of a pass for three days will be reborn in so you can remove oil dost reasons in order to cover all the notes in order to Make a dent and single component in this case remove this one and connect like this is not the notes will be converted into a single components number operations in this case will give what you can also remove this thank you can connect like this and you Can Contact Them Who Saw The Number Of Operations In This World But You Need To Find The Number Of Operations In Order To Connect With Only Single Point From This Point Only And Not To Join Him To Give The You Will Need A Minus One Number Of The World Of the problem ho water images in graph with jain notes will need only and minus one dead to make all the notes connected all extra notes of asbestos coming from the concept of minimum spanning tree and issue of having a number of votes in the number of cases In order to connect with node into a single point will be minus one no about this country will give an example to get the latest subscribe to The Channel minimum number of a single point Notes - 1898 point Notes - 1898 point Notes - 1898 dooba hai yeh wer heavy images minus one number Off Extra Idi 4 - 300 Use This one number Off Extra Idi 4 - 300 Use This one number Off Extra Idi 4 - 300 Use This Is The Year Boys Only To 4 Users Liked This Will Make All The Answer Is The Number Only Has Not Been Possible To All Boys Must Subscribe Here Joint Enemy And Mode On This One But You Cannot Have Joint Sense 514 Introduced Into The First Form And You Should Not Have Been Possible Seervi And Number Of Votes Will Be Responsible In Order To Avoid This Possible To Come Into A Single Example To The Point Where I Wanted To Remove Will Increase In The point where not having any total number of cases total number of units two minus one number of cases can remove this channel like this is the singer of solve this problem not the total present as is and how to find the latest jobs and Graph Total Number of Notes for the Minimum Wedges to Connect with Node to Gather * Single Wedges to Connect with Node to Gather * Single Wedges to Connect with Node to Gather * Single Entry will be Minus One Number Subscribed Notes and Having a Number of Cases with Removing All the Number of Businesses Tab Page Subscribe if you The Amazing Bank of Baroda Wedges In this is the number of Note 4 6 Number of cases for which is not given one OK you are just having a single point and craft with the number of units and structural without having any number of a decrease in the value of - 151 - 6 - 151 - Wave Live - 2 - Top Number of 6 - 151 - Wave Live - 2 - Top Number of 6 - 151 - Wave Live - 2 - Top Number of Points 208 Ayo Pure Getting Understanding Inside left side graph you see the graph is very similar to the Video then subscribe to The Amazing Removing This is the first features in notes - One number of This first features in notes - One number of This first features in notes - One number of This is not doing this you can do you just see - 151 Some time for it's possible to join the main admin operation cell also one ok I hope you understand how to solve this problem no one thing to note this number complain Increase the volume to make subscribe mode turn on the number of units for boys in the number of cases will be - - - - 151 - 04 - what is cases will be - - - - 151 - 04 - what is cases will be - - - - 151 - 04 - what is the number of a request to all notes in gift envelope pine tree but in the second Only you have enough two components in the formula will change for a twenty and minus one and number of complaints - 110 one and number of complaints - 110 one and number of complaints - 110 Subjected because it's okay this side 2 and the number of votes 4.33 lone vote side 2 and the number of votes 4.33 lone vote side 2 and the number of votes 4.33 lone vote for change - - - - - Subscribe - - for change - - - - - Subscribe - - for change - - - - - Subscribe - - Only Residents on the Number of Units Can See How to Solve This Problem Subscribe First Step Will Give Me That Edison Say List Song From the Giver Graph Will List Mechanization Second Step Will Be Defined The Number of Components In The Giving Refusal in the Words Using Simple Difficult Find the Number of Units The Number of Units with Nothing of Value and Already Know the Number of Ghosts and Evil Resident Evil Effects Possible to Connect with Regard to Find the Total Number of the Graph Minus One Is the meaning of this point minus one queen thing but if you have been having more components 20 minutes spanning tree will be having large number of pages so if you have any two components in you will be having one and places in this country such native with some Points 220 Subjective Effective Request Components Day You Will Be Subtracting To Number Of A Person Like And Saw In The Country With C Number For Boys Will Be Having - - - - One Number Of Years Will Be Having - - - - One Number Of Years Will Be Having - - - - One Number Of Years In Order To Form Of Boys Number 900 To 1000 Total Pages - The number to 1000 Total Pages - The number to 1000 Total Pages - The number to you this force to use an hour just in order to connect with a components in two because late cooperation amount into complaints and a few words and sentences in this you can not to join date 2nd 10 Grams and Fennel Media This Day Was - One Day You Will Not Be Media This Day Was - One Day You Will Not Be Media This Day Was - One Day You Will Not Be Able To Join This Does Not Have At Least To The Number Of All The Member Of The River At Least Number Of Cases In Order To Connect With This Will Be Possible To Subscribe Quarsi Minus One Vikas Loot Se Trick Point Se Sure Din Also You Have Just Use To Make A Model To Connect With You Just Need To Find The Number Of The World Is Use To Minus One Number And 19 In Certain Cases Will Not Possible To Connect With number of what is the number of villages in this will not possible to connect with a single click of a single point notes youth number of all the best on one side muslims spanning tree with the number of business so this day was so you will never be Able to form a single quality graft Cases where you will not be able to join in condition in which - 110 condition in which - 110 condition in which - 110 Maximum minimum number of a single example 6 Total number of the total number of which says - - - Total number of the total number of which says - - - Total number of the total number of which says - - - - Verb - 123 Subscribe to that - Verb - 123 Subscribe to that - Verb - 123 Subscribe to that no How many do we use in order to connect all this completes * Office will be connect all this completes * Office will be connect all this completes * Office will be using only C minus one number of President US in this case which has just two components which will also just use Singer Labs in order to connect with this answer WILL COME ON TO BE EVEN IF YOU WANT TO KNOW HOW TO FIND THE NUMBER OF UNITS SUBSCRIBE NOW WE YOU WILL RELEASE ALL THE SUBSCRIBE Video from Dr To Cash Withdraw From One Toe To My Channel Subscribe Problem Solved Veer Vikram Points 140 Ofton Visited Nine- 10 Phones and Corporates Ofton Visited Nine- 10 Phones and Corporates Ofton Visited Nine- 10 Phones and Corporates Will Increase in 518 Is Note 09 Dravid Gautam and Differences 323 and Number of Units Increase by One to Three Wheeler Benefits from Evil 4 through Which will Check Video then subscribe to the Page if you liked The Video then subscribe Phone Number Compliant by using deficit and third step will be using simple formula in order to find the number of written tests and also how many states requested to convert to 100 years for the time complexity of not only no problem subscribe to the Page if you liked The Video then subscribe to the good so components into a single complaint and window minimum number of a place which should be just for you dare devils subscribe will not only help you understand very simple and comment subscribe share and subscribe my channel don't forget to subscribe Thank you
|
Number of Operations to Make Network Connected
|
unique-number-of-occurrences
|
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`.
**Example 1:**
**Input:** n = 4, connections = \[\[0,1\],\[0,2\],\[1,2\]\]
**Output:** 1
**Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3.
**Example 2:**
**Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\],\[1,3\]\]
**Output:** 2
**Example 3:**
**Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\]\]
**Output:** -1
**Explanation:** There are not enough cables.
**Constraints:**
* `1 <= n <= 105`
* `1 <= connections.length <= min(n * (n - 1) / 2, 105)`
* `connections[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* There are no repeated connections.
* No two computers are connected by more than one cable.
|
Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.
|
Array,Hash Table
|
Easy
| null |
222 |
hey everybody this is Larry this is day 15 Midway through the November liquor day challenge hit the like button hit the Subscribe and join me on Discord let me know what you think about this problem and you know everything else I guess whatever you like to ask um today's problem is 222 count complete three notes okay so given a root of a complete binary keyword is complete we turn the number of notes in a tree oh of n obviously it's just kind of the number of nodes uh can we do a little bit better right um hmm I guess we can do binary search right is that the idea what is complete again okay so everything's first except for the last right so yeah I mean I think by Navy such as the idea um in that you know you go all the way left you go all the way to the right and then um and then you know one you're trying to find the last note that it occurs and of course that is going running like log square of H time or something like this where H is just oh that's not true um so H is the height so each one so it is weird like H log H or something on H but the last uh level it's gonna have an N over two notes right and the worst case so that means if you do a binary search on that it's gonna be log n so it's gonna be H log n um and since H to height is going to be log n it's going to be log Square n right so and that is less than Over N so that would work uh whether that's easy to implement is another story but uh yeah but that's the idea okay so maybe let's do that um yeah okay let's kind of do that let's um I think the first thing I want to do is just go left and then go right and then see if they're in the same depth right because if they're in the same depth then that means if they're on the same depth that means that it's a complete tree right so I just want to roll out that case um yeah there are other things you can do is well maybe let me also do 10-day is well maybe let me also do 10-day is well maybe let me also do 10-day search but let's just ignore that for now um okay yeah okay so let's just say um so I guess the height of the tree is actually let me think about this for a second the height of the tree is going to be always if you go left all the way down right and you could prove this with either induction or just like enumeration uh exhaustion or whatever because you know in every case the if you go all the way left if you keep going to the left you're always going to get the height so let's do that um for a complete three so that's so something like this right um and then here we have H is equal to height of the root right okay and then now I mean so we could do a binary search but we can also just do um you know repeat doubling or something right I mean I guess in both cases it's about the same which is that you take a middle thing and then if um now you take a middle finger and then if it's the same height then that means that by whatever you want to go the other side and if it is a different height that means that it's on the left side right um you could kind of draw it out but maybe I'll join now hang on so this is just a binary search on the two cases um I think this one is slightly uh easier to understand or visualize anyway than the other one that I was saying so yeah so basically you only really have two cases right so you have something like this and this is just like searching about talking about binary search and then dot here right in the same height right so let's say we look at this and we go okay this is the same height as this so that means that the last node of this tree on the last level it's gonna be on this side right and then of course if you kind of uh do a second the only other case is right so uh this is a node and then you have this height and then now let's say you know um okay I messed up here but let's say you kind of go here and then you see this node right or maybe equivalently you see that this note doesn't exist doesn't same idea um then that means that you know that it's the answer is going to be within to the left right so that's basically the idea and you're trying to find the last note on the last level um yeah hmm try to get rid of this so the idea I think I'm set the implementation may be a little bit tricky um right how what is it I mean I was thinking about um just numerically um doing it what is the number of and number of nodes is five to ten okay to the fourth so then we can definitely use a number to represent it right so here um let's see so on this is just kind of annoying to a way but I think that's okay right so the way is just like numbering each node I think and then you know figure it out that way and the way that you have to do this zero is left one is right and then you kind of um put that in right so that means that for H I have to get this way um it may be off by one so we'll have to figure out so for H the number of nodes on that level or um so I got distracted by a second so one two so come on yeah so one is one two is two three is four so that me but it goes from to eight right or to seven I guess more precisely but so it's just two to the H minus one is going to be the right left is to go to 2 H minus one and then this is just a regular binary search right um if sound of mid so if this is found then we want the left to 0 to Mid I always write is equal to Mid minus one so we have to add one here I think that's mostly the idea and that and of course that note will be maybe that note plus one is going to be the answer right and then now um this point is a little bit tricky maybe not maybe I'm just a little bit lazy um so then now I don't know if this is off by one so H is three this would have a two Chef okay fine dude um if this is greater than zero then that means that we want to go to the right so then we return found oh this is node I don't know I could move that way um minus this thing I guess so I guess it doesn't matter really because I'm just using the N operator so nose okay and then also if current is equal to zero I want to say then if node is not none we return true otherwise we well okay maybe I'll write in a different way if node is none we return Force regardless and then if this maybe someone like this just kind of give it a spin I don't know if this is quite right there are a lot of off by one potentials to be honest and yeah there's only one 1.5 is clearly not there's only one 1.5 is clearly not there's only one 1.5 is clearly not right I don't know that I handled this case to be honest but so because I assume that H is greater than one to be honest so okay fine maybe I'll just special case it because I'm I don't know that was in the spirit of my solution so um so it should still I mean I know that is still one for the other ones but yeah all right so the last one is one so okay let's print out left right I think one thing that I do like about the new UI is that I get the print statements in uh independently so that's good so one and one so it's gonna return one that makes sense but I think that is let's see this one four and seven that also is good so I think maybe I just have some off by one on the found stuff um so that's okay so four and seven okay so this is actually correct in what we want because it's between four notes and seven nodes but h uh this is H minus one I think I thought I oh no I um what is two H minus one because I had this minus one here for that reason I don't think this but I think this as a result might have changed some of this stuff as a result um because this statement may not be true but okay but now do we do a plus one so it's 4 and 7x inclusive it is hmm that's what and seven okay five four seven foreign just take a look and see what it's doing so guys 4 7 is force because it tries to look at the um well let's just do what is it trying to find because that seems wrong so if it does find this the six does exist oh no does it because I think I number from zero one two three four so we don't want to find from four to seven because we because the way that I set it up oh I see the way that I set it up is um is from zero to whatever and it only has seven nodes okay so now this is wrong but thank you I had to this is so annoying to get right but okay three to six so it tries to find a five and five is the six so it finds true and then five six if I try to find a six and his Force so oh yeah but then now we have the plus one which is what I had originally because I miss some point of that okay so now that looks good because I knew that I was going from zero index that's why I had a plus one here but then I think I confused myself somewhere along the way let's give it some mid I'm about like I don't know sixty percent confidence 70 confident if I could have tested this actually but uh all right let's try it this other case so forth five notes three and six we choose we picked the five with fours the four is not hitting even though it's right here I'm putting out very weird stuff but why not so the four is foreign oh I might I think I did it wrong huh no that's right no well I mean maybe not but so the four is this five but I think I did my math wrong on this because for um the number we treat as one zero and binary that means I go right first for some reason white love and that will give me thank you man I'm I don't I messed this up didn't I huh man my numbering system is wrong that's why wow this is way weird okay let me think about this a little bit more Okay so okay I was going to bring up the drawing thing but I think I just messed up and so I've been doing too much stuff in my head recently so I should have just drew it out but basically on top you have zero and then you have one two so that's already a little bit weird maybe no that's right so far and then three is going to be one uh or zero one maybe four five do I have to stop by one did I mess that up I've uh 2x plus 1 2x right this doesn't work so Dad just don't have one in this case maybe I just messed up I forgot so then one zero um and then I guess so huh well okay I guess so we have to start at one so all right let's redo this so that means that we're searching for this foreign I think I was thinking about another algorithm I think that's one thing that happened sometimes with me anyway um is that I've done so many poems that sometimes I take these shortcuts but these shortcuts sometimes I will so um so don't try this at home okay so we don't care about the first thing but we do care okay let's see let's say we have this number and then we go right so we go to do we go okay we want to go to the left or to the right so it's this minus one because it's the next bit the first bit is always a one all right and then now we don't have because we're going from one index again we don't need to plus one there okay let's give it a submit that was kind of an easy fix it was true but maybe I just kind of okay fine hmm a little bit sloppy to be honest because I like I said I think you know we've experience you take shortcuts but sometimes your shortcuts are wrong so you have to validate and that's why you're doing the testing or in my case uh just we're good at testing but uh what did I do last time uh-huh uh-huh uh-huh well I did some crazy stuff last time but same idea actually so good on past Larry this time uh I don't know what I did here some kind of memorization but yeah um like I said this is going to be all of log square and or like yeah log n tops Times log n time in terms of space this is going to be all of H there's no way around it but just log n because it's a complete tree so all of log square and time and log n space um that's pretty much all I have with this one hopefully it's you know it's sloppy but it's good so yeah let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Count Complete Tree Nodes
|
count-complete-tree-nodes
|
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.
According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
Design an algorithm that runs in less than `O(n)` time complexity.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 6
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5 * 104]`.
* `0 <= Node.val <= 5 * 104`
* The tree is guaranteed to be **complete**.
| null |
Binary Search,Tree,Depth-First Search,Binary Tree
|
Medium
|
270
|
891 |
hello and welcome back to the cracking Fang YouTube channel it has been a while I have not touched lead code for a long time and let's see if I can dust off my skills and put out a video so today we're going to be solving lead code problem 891 time based key Value Store design a time-based key value data design a time-based key value data design a time-based key value data structure that can store multiple values for the same key at a different time stamp and retrieve the keys value at a certain time stamp we want to be implementing this time map class and time map will just initialize the object with the data structure and we want to have a set method which takes a string key a string value and an integer timestamp and this is going to store the key with the value at the given time timestamp we're also going to have a method string get and this is going to take a string key and an integer timestamp and what it's going to do is return a value such that the set was called previously with timestamp prev is less than or equal to the timestamp provided if there are multiple such values it Returns the value associated with the largest timestamp prev if there's no values just return an empty string so this question is pretty easy uh and one thing that we want to make note of before we go is uh this one line here is that all timestamps um of set are strictly increasing so that means as time goes on we're never going to get a time back right so if we get time stamp 3 in the future as we're getting uh the set method called we're never going to get something like timestamp 2. and this is actually going to greatly simplify the problem so let's not even look at a basic example let's kind of just look at the intuition because it's relatively straightforward and we don't really need to waste time with an example we can kind of just walk through how we would do it with the actual intuition and then we'll code it up so I will see you once I've wiped away all this text with a blank page here okay so we looked at the question prompt now let's actually see how we're going to solve this problem remember that there's two methods that we need to implement here and that is going to be our set method and we have our get method let's look at set first because it's relatively straightforward remember that we're given a key here we're given oops P we're given a value and we're given a time stamp so we need to store these values right we're going to use two dictionaries here the first dictionary is going to map key to all of the values for that key right because we can store multiple values for a key also we need to store for each key all of the time stamps we have because remember we need to do a lookup based on the timestamp so these are going to be our two dictionaries key to value and key to timestamp now one thing that's very important to realize is that remember earlier when I said that time stamp in the set method is monotonically increasing which means that we will never go back in time with a timestamp that way we can be sure that each value the index in here if we think about it if we were to flatten our values and just have like V1 V2 V3 this would correspond with timestamp 1 timestamp 2 timestamp three right for each key that we have here because you we never have to like insert something prior it's only going to be increasing so we can just think of like appending these so this is going to be very important now we have the get method which is the tricky part right we're given a key and we're given a time stamp and remember that what we want to do is we want to find the time stamp so if this is our timestamp that we're given we want to find the value at whatever the previous time stamp is such that the previous time stamp is less than or equal to the current timestamp and it's guaranteed that this one will exist and whatever this biggest previous timestamp that we have for the key that's what we want to return so that's why we have the dictionary to map key to timestamp luckily like I said because the timestamps are always increasing this list is sorted now we're looking for what we're looking for the biggest value that's less than a certain value and we're guaranteed to have that value at this point it should be screaming to you that we're going to use a binary search here because we have a sorted list and we're looking for an element so we're not looking for the element exactly we're looking for one to the left of it which is that classic kind of just moving the indexes until you get to a certain point binary search so that's how we're actually going to find the index uh inside of our mapping right so say the key is I don't know 12. and we have the values one two three say we find the index to be two for whatever time stamp we're given then we just need to go into our value dictionary for that key and the index because time is increasing uh will be the same there so we just perform our binary search on the value list here for the timestamps find whatever index corresponds to the timestamp we want then we just return the value at that index from the list of values in the key to Value dictionaries so that's what we want to do it is a binary search to find the index and then we just return the value inside of this dictionary so relatively straightforward two dictionaries each storing the key as the key and a list of either the value or the timestamp as the value in the dictionary and then we just do a simple binary search so enough talking let's go to the code editor type this up really straightforward really simple let's do it all right let's now code up the solution before we do I just want to say I got a new keyboard it's one of those mechanical ones if the sound is too loud or it's too annoying just let me know in the comments I'll switch back to my other keyboard which was much more subtle so let's get into it first thing we want to do is just code up the init method so what we want to do here remember is just set up our two dictionaries one which Maps the key to the values and one which is going to take the key and map it to all of the timestamps for that key so we're going to say self dot valuedict is going to be collections dot default dict passing in a list here and we're going to say self dot time dict is going to equal collections dot default dict and we're going to pass in a list so that is the init easy part done let's now do the set method which is also really easy just get rid of some space here and what do we want to do we just want to say self.valuect self.valuect self.valuect for a given key we just want to append the value so we'll have that list of values for a given key and we want to do the same thing for the timestamp so we're going to say self dot time dict for a given key we're just going to append the time stamp so that is the set method let's now do the get method or we actually have to do the binary search so remember for binary search we need to first set up our left and right boundaries so the left always begins at zero the right will begin at the end of the array so now we actually need to get the length of the array so we're going to say length of self dot time dict and we're going to pass in the key to get the items here uh but it's not guaranteed actually let's double check this uh is key guaranteed to be in there uh let's see if there are no okay so it's guarant it's not it's possible that we don't get a value for the key here uh because it doesn't exist so we actually need to do here is do timedict.get and we're do here is do timedict.get and we're do here is do timedict.get and we're going to pass in the key and if we don't get anything we're going to get an empty list because obviously the length of an empty list is zero uh and that way our binary search will actually just never start we can just return our um you know our empty string which is what it asks for so uh and remember we need the end of our list index so we have to subtract one from the length of it so that is going to be the left and the right boundary now let's actually set up the binary search so we're going to say while left less than or equal to right we're going to get the midpoint so the midpoint is left plus right uh divide by 2 and now what we need to do is check the three cases if our current midpoint actually equals to the timestamp uh then we're good to go because remember that the previous times what we're looking for is previous timestamp less than or equal to whatever time stamp is given so if they're equal then we can just end the search there we found what we're looking for so we need to say that the um the current value here or the current timestamp is going to be what it's going to be self of time dict of whatever the key is at the midpoint right so that's the current timestamp and we're going to say if the current timestamp equals to timestamp then we're done we can simply return uh what the index right we want to return the value of an invalue dict at that index so we're going to say return self dot value dict of our key at whatever the midpoint is and we are done now we have the other cases where we have the you know the current timestamp is actually too big so that means that we need to move our search to the left side so we're going to say else if the current timestamp is actually greater than the timestamp that we're searching for we want to say that right is going to be mid minus 1. and then the last case is where our timestamp is too small we want to move it to the left so we're going to say left equals mid plus one so either we're going to find the current timestamp exactly as part of our binary search or we will have moved the right pointer to where we want to be or it doesn't exist because it's possible that we actually don't go through this because remember if the key doesn't exist in the time dictionary we're going to turn an empty list length of an empty list is 0 minus 1 is negative one this will never fire which means that we actually need to return our empty string here so we're going to say return at the end self dot value dict of the key at whatever the right index is which is going to be the index which holds our value here if the right index is actually greater than or equal to zero uh because remember we could have not even done the search and that way right would be -1 at the end of this right would be -1 at the end of this right would be -1 at the end of this um otherwise we just want to return an empty string so I'm just going to run this real quick make sure you're making these two but syntax mistakes looks good and let me submit this and there we go I think that's means it's accepted yeah we're good to go so uh let me clear this let us talk about the time and space complexity so in it I mean this part we're just initializing a um you know our data structures here this is going to be Big O of one there is no nothing there here we're appending to the end um of addiction of a list inside of a dictionary it's just going to be Big O of one uh for that one and the time and space uh let's see so get uh obviously this is a binary search so binary search time complexity is going to be log n and the space complexity here is going to be Big O of one because we don't use any extra space we just use these ones so in total I mean the time complexity is going to be log n for the get um to store all the values it just depends on how many you end up storing so I guess that's bigger event in space but I mean for each individual one it's just o of one um so yeah that is your time and space complexity like I said I haven't made one of these videos for a long time so sorry if my explanations aren't great I am a little bit Rusty I need to dust off my Elite code skills but hopefully uh this question was relatively straightforward and um you know get me back in the uh back in the saddle so yeah hopefully you guys enjoyed that uh if you guys want to see any other videos let me know I mean no one's really hiring right now so it's difficult a lot of the questions on leak code are very out of date and there's not really any point of me doing like the top ranked ones because companies aren't really doing interviews so it's difficult to actually know which ones are but anyway uh yeah if there's a video you want to see that you're stuck on let me know if it's not too particularly annoying um I should be able to make a video otherwise thanks so much for watching if you made it to the end you're awesome appreciate for watching all this way and have a good one I'll catch you in the next one bye
|
Sum of Subsequence Widths
|
score-after-flipping-matrix
|
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`.
A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 6
Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.
**Example 2:**
**Input:** nums = \[2\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
| null |
Array,Greedy,Bit Manipulation,Matrix
|
Medium
|
2268
|
1,283 |
hey everybody this is larry this is day six of the leeco november challenge hit the like button hit the subscribe button join me in discord let me know what you think about this farm looks like a mafi problem find the smallest divisor given a threshold okay criminal number and threshold positive and divide it all the way and sum up to resolve the division find the smallest divisor such that the result is less than or equal to threshold so if the divisor is okay um is it always possible okay so this makes it always possible um because so basically what i how i'm thinking about it and this took a little bit because i don't know this is a new problem to me but which is that there are a couple of ways right one thing i would think about is well one is just reading it correctly and i think it took me a couple of seconds to kind of understand what this problem is about and then you could go kind of one way or the other about this right where if your divisor is one then what does that mean right if the rise is one is just the sum of the array which just shows here uh if your divisor is um let's just say your divisor is infinity right or just some really big number then these are all zeros and by nature uh wait is it round to the nearest integer greater than or equal to okay is it really rounded if it's greater than or you go to that element because then it's just the ceiling right anyway that's not so okay so in that case even if you chose an infant like infinity or some really big number as the divisor then you get one for each array element right and then that's why that's when i looked at the bottom i looked at the threshold and i go okay so that makes sense because then now um if you choose an infinity number you always get an answer if you choose an infinity number and then you're always going to not or actually you don't know but when you choose one you may or may not get an answer but you know right so in between you're trying to find the smallest horizon which that's uh this thing is true uh and from that i think that's where i would solve the problem is that um for this problem there is you know you have some function that you know you're given a divisor and you get the sum of the divisors right or the sum of the dividend or whatever it's called um and it makes into a sense that as you increase the divisor the number gets smaller right so then you have like this curve that goes like from high to smaller um and from that you know it's a very obvious binary search from that because then now you can just go okay we're trying to find the smallest number that holds these conditions right and that's how i'm going to write it out uh and i always recommend practicing binary switch because for me i always get it i don't know it always seems a little bit tricky um but yeah so for me i write something like left is zero the right is the code two um i guess the maximum element which is 10 to the six but it doesn't really it shouldn't matter that much so i'm gonna write ten to the eight it's just a big enough number so that you know you don't have to worry about off by one or something like that um and then we this is standard template so i write it this way so that when left is equal to right the answer is equal to left the answer is left and also this means that we want an inclusive range right because that means that left and the right arm you know because left and right are the same answer then if you draw it in terms of range they have to be inclusive uh okay so then let's do mid as you go to left press right dotted by two that's just the middle um if good is mid then that means that what is good right good is equal to in this case if mid as a divisor gives us a num um gives us what's it called sum of um let's just call it give us a sum with the divisor that is under the threshold right so this is good what does that mean for us uh or if mid is good what does that mean right let's see so basically we should have something that's uh for source four subscriptions for us and then true at some point and then now let's say our mid is true what does this mean that means that we can go lower so we should look but it includes this number because this could be here right so you could forward the right and then just include this number and then look at the left so that means that right as you go to mid because we want to make sure that mid is still in that inclusive range and also look at the left right and then otherwise left is equal to mid plus one because similarly if this is false then you know that this number is not going to be good and also everything to the left oops everything to the left of this number is not good and also this number is not good so then we could skip mid and also go to mid plus one so that's how i kind of have these you know that's how my explanation for these and at very end when it comes together we just return left and i now have to write the good function of course um so let's just say it's x or divisor maybe so then now we just have to have a total for num and nums total plus you go to num over toe over divisor oops and we want to round up the way that i write rounding up is just added by a divisor minus one and then we just return to uh total is less than you go to threshold is it is equal to right yep and that should be pretty much good enough let me run it for the test cases this is 11 and 19 yeah so that looks good i'm relatively confident because binary search is something that i've done a lot but maybe i missed some uh test cases oh yeah okay so that is uh let's talk too soon is that because we start left at zero that means that at some point it could be zero right so we actually want our smallest answer to be one uh so that's a miss on my end as i was saying how confident i was so it happened sometimes uh so you have to be careful about your ranges und i was focused on the right side because i was like oh if it's big enough it doesn't really matter um because they will always go to the left so you don't have to worry about it but on the left side you have to go to the right and you have to make sure that zero is not in the range so yeah let's submit it again and hopefully this time is slightly better and that's embarrassing uh yeah that's good so what is the um what is the uh complexity of this problem right so in terms of space is very easy to see that it's constant space we just have you know a couple variables and a couple of and you know that so it's all one space constant space right so here we see that we go from one to ten to a and we do this lot um and every time it we divide the i2 so that means that we this would be o of log 10 to the a number of operations right or iterations i like to phrase this as u where u is 10 to the a this is the size of the universe so this is o of n log u is the notation that i generally use um so that's the number of iterations where good function uh and each of each iteration calls good and good is just o of n right because we look at every element away at once when we call this function so now this is of n so now putting that together is just n log you time uh that's all i have for this problem uh it's binary search it is something that i recommend practicing a lot i've seen it all over the place both in competitive and interviews people expect you to know it people are very you know um yeah pretty uh standard now for benefit rush so uh definitely play with that let me know what you think hit the like button hit the subscribe button join me on discord and i will see y'all tomorrow bye
|
Find the Smallest Divisor Given a Threshold
|
reformat-date
|
Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: `7/3 = 3` and `10/2 = 5`).
The test cases are generated so that there will be an answer.
**Example 1:**
**Input:** nums = \[1,2,5,9\], threshold = 6
**Output:** 5
**Explanation:** We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
**Example 2:**
**Input:** nums = \[44,22,33,11,1\], threshold = 5
**Output:** 44
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 106`
* `nums.length <= threshold <= 106`
|
Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number.
|
String
|
Easy
| null |
806 |
hello quick introduction to the video my name is Cameron I'm a graduate Apprentice software engineer currently studying at Glasgow University and I'm using this video as a way to sort of rubber ducky debug a elak code problem just attempt to solve it talk through my thought process and hopefully it's just so to someone watching this so problem I'm going to be attempting today is number 806 number of lines to write a string so just going to read the spec here you're given a string s of lowercase English letters and an array width denoting how many pixels wide each lowercase letter is H specifically width zero is the width of a and width one is the width of B and so on okay you're trying to write s across several lines where each line is no longer than 100 pixels starting at the beginning of s write as many letters on the first line such that the total width does not ex 100 pixels then from where you stop an S continue writing as many letters on the second line proceed continue this process until you've written all of s return an array result of length to where the whatever's index zero is the total number of lines and result one is the width of the last line in the pixel the width of the last line in pixels so example one we've got 10 20 30 40 50 60 70 80 90 100 so I'm just going to C this up it's 100 200 260 so there you can get 100 lines on the 100 letters on the first line 100 letters on the second line and you're left of 60 so you can write there's three lines and on the last line there's going to be 60 okay um so I'm going to switch over or I'm going to look at constraints um s will only contain lowercase letters length is between 1 and 100 or a th000 sorry and each width is between 2 and 10 and the length of widths is equal to 26 okay so just going to go over to my notes here so the first thing I need to think we need to be able to do is convert each letter in the string to its number or its width so I think the easiest way to do that is just to get its asky or its asky number and then or it's asky value sorry and use that to map its position in the array so what we can do is we can do some sort of mapping so I'm just going to write that down so we need toble to do that somehow then we need to figure out how much we can fit on one line so I guess we can just start by maybe iterating overate over string um add length or pixels length of string two a total if so it's 100 F total exceeds 100 add one two lenses and then we can return lens and index zero current total and index one okay let's try this so I think we're going to try and do this TOP Step the map each characters part try and do that as we're I Traen through um old for or character and S uh total plus equals um what's first thing I want to do is see find out what this asking gives me I think it just prints the asky value of whatever character you put in there but may be wrong we just comment this up for now I'm going to let's just look this up so o d we need to do Rd so that gives us 97 so we can do Rd minus 97 that will give us a that give us zero sorry perfect so we want to go to the index or character- 97 then we need to also check if total is greater than or equal to 100 all lines plus one then to return the line's plus one and then we also need to reset the total so totalus = 100 return um lens total oh H Total Lines do not exist there we go I think we maybe need to put this check first may this needs to be it needs to start at one okay um so that's test case passed no actually yeah this check should go afterwards that was right the first time H so I'm just going to try and do a bit of troubleshooting here just going to print off the wets that we get every Loop so for these last three we should get four yep now it's saying here that the total should be 24 meaning that there are 400 or four left over um let's just comment this out um in print total at the end so we get 260 oh that's wrong one for here we get 102 which does line up um with what we had here with two left over there are only 3 years um so it should be ending on a two not four ah I've forgotten that you canot with this there's a possibility you can go over 100 line over 100 characters on one line so what we can do is we can say um chore width is equal to this then we can say F chore width is greater than or h plus total is greater than 100 then no then yeah then create a new line yeah and then we just a total by 100 I guess we can just put this into one big or um okay could this just be simplified into this one lane let's try this so if you try and add the width of your character to the total and it's greater than 100 then go to a new line and go into new line and set your total to minus 100 otherwise oh we should still be adding this total either way so should still be adding it here okay case one passes now this doesn't so each time we're going to print the total here instead of yeah instead of going outside do it print the total every single time I think I should probably try and do this manually so we've got three Bs but are all 10 so that's 30 3 C's takes you up to 60 3DS take you up to 90 a takes you up to 94 four uh a again takes you up to 98 and then when you try and go into a new line you have to go into a new line and then you have to yeah so it should be four left over oh yeah no but this it takes away 100 I know it shouldn't take away 100 it should total should be equal to zero let's try this there we go hit submit and hopefully accepted so thank you very much for watching the video hope it was useful to you in some way sure perform if it was please leave a comment or if you had some other solution that was a bit simpler or more efficient uh please leave a comment love discussing these problems and their Solutions So yeah thank you once again for watching the video and I hope you have a great day bye
|
Number of Lines To Write String
|
domino-and-tromino-tiling
|
You are given a string `s` of lowercase English letters and an array `widths` denoting **how many pixels wide** each lowercase English letter is. Specifically, `widths[0]` is the width of `'a'`, `widths[1]` is the width of `'b'`, and so on.
You are trying to write `s` across several lines, where **each line is no longer than** `100` **pixels**. Starting at the beginning of `s`, write as many letters on the first line such that the total width does not exceed `100` pixels. Then, from where you stopped in `s`, continue writing as many letters as you can on the second line. Continue this process until you have written all of `s`.
Return _an array_ `result` _of length 2 where:_
* `result[0]` _is the total number of lines._
* `result[1]` _is the width of the last line in pixels._
**Example 1:**
**Input:** widths = \[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "abcdefghijklmnopqrstuvwxyz "
**Output:** \[3,60\]
**Explanation:** You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.
**Example 2:**
**Input:** widths = \[4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "bbbcccdddaaa "
**Output:** \[2,4\]
**Explanation:** You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.
**Constraints:**
* `widths.length == 26`
* `2 <= widths[i] <= 10`
* `1 <= s.length <= 1000`
* `s` contains only lowercase English letters.
| null |
Dynamic Programming
|
Medium
| null |
997 |
maybe hello there so today is day 10 of the Meili coding challenge questions so far the question has largely remained to be easy but tomorrow we are getting into the 11th day so into the middle of them once hopefully tomorrow we can have something that's a little bit more challenging today is still a relatively easy question it's called find the town judge so we have n different people labeled from 1 to N and there is a rumor one of these people is a town judge the judge has this properties as follows the judge faster nobody everybody except for the town judge trusting him Imahara and there is exactly one person that satisfy the these two properties if there is one so if there is one we should return the integer number that can identify him or her otherwise it's a negative one will be given to us this the array of tuples which means prison a trust a person B so that's the input so if we think about this as a graph everybody here is a node so we have n different nodes here this property basically translates to for the there is no out coming edges out going I just from the tongue judge and this second sentence translates into the town judge node has n minus 1 incoming edges so if we just process this array to populate the statistics about the number of incoming and outcoming edges for every node we can just do a simple query for just to see from 1 to n which person have satisfied these two properties and then we can just return that if we can find one otherwise we will turn negative 1 so in terms of time it will be the amount of time to process all the edges and also just to try go through all the nodes to check this 2 property so it's a number of edge+ number of nodes and in terms of edge+ number of nodes and in terms of edge+ number of nodes and in terms of space we are storing the incoming and outcome outgoing edges number of those things so it's a 2 multiplied by number of nodes number person so it's 2 n so yeah so that's the time and space analysis I don't think it's for this question this simple we don't it's not necessary to go through some of the examples just for the sake of verifying what's going on let's actually just take a look at one so here what are we gonna calculate is the incoming of edges or prison one it's zero actually and the outgoing edges for persons one is we have 1 3 1 4 so that's 2 for the persons one from prison to the incoming edges 0 as well and the outgoing edge from person 2 is 2 4 2 3 so it's 2 for Princess 3 the incoming edges 1 3 has 1 2 3 2 4 3 s 3 and the outgoing edge from prison 3 is 0 for prison for the incoming edge we have 1 4 + 2 4 so it's 2 outgoing edge it's 1 4 + 2 4 so it's 2 outgoing edge it's 1 4 + 2 4 so it's 2 outgoing edge it's it trusts the prisoner Sri so it's one there so then we're just looking at the prison by prison we find the judge should be the one that trusted nobody so I equal to 0 and in edge just call it judge should be n minus one so we find this is the person here this is a person one person two for this reap risen for so this is just the detail works are about the example we're populating the image and our edge and just check person by prison to find the person that contains zero outage and n minus one incoming edge and that's the judge so that's pretty much the solution we're just going to translate the above example process into the code so we for the incoming edge we increment the person that's been pointed to and the outcoming edge or the person that the edges originating we increment that as well and after this follow-up we that as well and after this follow-up we that as well and after this follow-up we processed all the other edges and inside this trust array and we check for from person to person so the criteria is that if this person has no out coming edge and it has a minus one incoming edge so the president acceptor for himself trusted him and he trusted no one otherwise we're just going to require a negative one so this should be the coasts or solving this question and I guess a little bit optimizing can be done here is that so this can be translates to simplify a little bit to be the difference between incoming edge and outcoming edge to be the difference has to be n minus 1 so this should work as well because you're testing the two equality with the end that's equivalent to take the difference and from both sides the Union edge person substract how coming our edge prison should be equal to n minus 1 substructure 0 you know just basically you know rearranging terms in this mathematical equations here so it should be equivalent and then the then we realized that another optimization we can do is to just consolidate this to hashmap into 1 or if you can if you use an array of size n that just think you can consolidate it to array into one as well I'm gonna just call it trusts and it's gonna be let me just B is M multiplied by n plus 1 use array as well you use our array instead of the hashmaps what we have here is going to be the images on the is subtracting the average so instead of having two things to keep track of those for the in two we just increment that and the Frog we just decrement and so instead of in the end we calculate the difference we it's kind of a effect I already big calculate the during this for loops there so that we can actually reduce the space requirement from 2 n into just the end if trusts person that has to be equal to n minus 1 as usual us here we can return the person so that's the space optimized solution I should work as well I hope it's indeed so there's really nothing special about this you know space reduction you can preserve that by analysis about this final testing condition you know you have to equality equation inequality there if you're just rearranging terms you can get this and you can realize instead of do this final substructure in the end we can just consolidate those two into one either hash map or array and just do the smaller increment as small updates doing the graph processing part yeah when we do the prison lookup within just by directly testing this final quantity there so that's a little bit optimization on space but the time is still the same the space you dropped a constant multiplier the multiplier but it's a still linear so that's the question all right
|
Find the Town Judge
|
find-the-town-judge
|
In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **1** and **2**.
You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist.
Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** n = 2, trust = \[\[1,2\]\]
**Output:** 2
**Example 2:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\]\]
**Output:** 3
**Example 3:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\]
**Output:** -1
**Constraints:**
* `1 <= n <= 1000`
* `0 <= trust.length <= 104`
* `trust[i].length == 2`
* All the pairs of `trust` are **unique**.
* `ai != bi`
* `1 <= ai, bi <= n`
| null | null |
Easy
| null |
1,331 |
hello friends today we can discuss this question from the latest read good bye we click on text 18 problem number 1 3 1 rank transform of an arrow so question statement states that you are given an array as an input and you have to output an edit in which each index define the rank of that element the how can we define the rank is actually an integer which states the order the smallest number has the smallest rank and as in number increases the rank also increases and the rank should be small as possible so the thing is we have to just give the number 1 2 3 4 according to how small or how big the number is as you can see 10 is the smallest 1 then 2 then 3 then 4 but if any number the same their end should be same as you can see in this case this is the rank because 5 is the smallest and the 9 is the second smallest that's it ok so the basic logic here is we have to sort this array to God to get the like the ranks but the thing is if we sort this array we have actually lost the original position where each element is so what we do is we make appear in which we store each element with its original index and then we sort it according to this number and after sorting it we have the index in which the number originally was and then we place the Quran according to that is see with an example this is an edit and this is the original indexes ok then they sorted so after sorting the so what we do is maybe make a pair of the number and its index original index this is the original next before sorting after sorting the because this 10 will come first so this will become its indices 1 then this 10 will come each and every spot then the 20 count it indexes to 3806 3 and what 0 as you can see now the index is all stored so what we can do is we make a new errand ok so now as you know at the first index there at the first index 10 was and it should have the Wrangell this number at the SEC at the 4th index they should be ramped do but because those are sale we have to put the same rank here also now because this is different it should be at Rank 2 which is at index 2 9 3 & 4 this which is at index 2 9 3 & 4 this which is at index 2 9 3 & 4 this is the final error I hope you understand this logic so this is the code because they can be the length of this can also be 0 so I have returned in this case and then I make a vector of letters is actually a pair of childhood then I'll store the first value of this is the value in the second is their text the first value and second is index and then we sort it's actually sorted by the value because we are not giving it at any parameter so it always sorted by the first well then we make the counter equal to 1 because we start by one and make the first index the first value its African so it equal to 1 then we start the loop from 1 equal to n not starting on the first because they are marked actually the first initially and then we match that in the second of like starting on the second number if it is equal to the first because if any consecutive numbers same the rank should be same and after sorting all the conservative number will come side-by-side so if they are same we come side-by-side so if they are same we come side-by-side so if they are same we do not against the counter we just put the same value in the solution vector or else we agreement the counter first and then store the value I hope you understand the logic and if the counter will increase if the two positive numbers are not same they are different because different numbers should have different ranks but extreme numbers should have same rank so we are not increment the counter here and after it is it returned the solution this code runs perfectly well and yeah I hope you understand the logic thank you for watching and I'll see you next time
|
Rank Transform of an Array
|
path-with-maximum-gold
|
Given an array of integers `arr`, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
* Rank is an integer starting from 1.
* The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
* Rank should be as small as possible.
**Example 1:**
**Input:** arr = \[40,10,20,30\]
**Output:** \[4,1,2,3\]
**Explanation**: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
**Example 2:**
**Input:** arr = \[100,100,100\]
**Output:** \[1,1,1\]
**Explanation**: Same elements share the same rank.
**Example 3:**
**Input:** arr = \[37,12,28,9,100,56,80,5,12\]
**Output:** \[5,3,4,2,8,6,7,1,3\]
**Constraints:**
* `0 <= arr.length <= 105`
* `-109 <= arr[i] <= 109`
\- Every time you are in a cell you will collect all the gold in that cell. - From your position, you can walk one step to the left, right, up, or down. - You can't visit the same cell more than once. - Never visit a cell with 0 gold. - You can start and stop collecting gold from any position in the grid that has some gold.
|
Use recursion to try all such paths and find the one with the maximum value.
|
Array,Backtracking,Matrix
|
Medium
| null |
120 |
hi guys welcome to tech geek so today i am here to share the solution of another medium problem that's triangle so this is elite code medium version basically asked in interviews of radius service based on product based company for product base it's basically asked in the first round um so let's see what the solution is and what the question is so basically the question says uh you need to find a triangle you are given a triangle array you have to find the minimum path sum from top to bottom okay now how we will do that for each step you have to move to an adjacent number of row below you can only look with the adjacent number of rows below more formally when we say if we are on index i of the current row okay we can either move to index i or to i plus one okay we have been given an example 2 3 4 6 5 7 4 1 so for this example that's 2 3 we can only move towards the particular let's say this is i index okay so for this we can either move to i or i plus one okay let's see it more clearly okay so this is the array which we have been given that's two three four now what is this in the top bottom or top to bottom okay what all we could do is we have this two three four five six seven four so obviously for the first row we need this because in every part this is required now from moving from two we have two options either to move here or to move here right let's say this was zero comma zero so from zero comma zero we can either move to one comma zero or one comma right so whether it is the zero is i then we can move from i or i plus one we have two options right again if you now will check two plus three what is it's five again two plus four it's six so we'll take the medium or the minimum one as we need to find the minimum sum so we will find the minimum okay i hope this is clear now as this is uh more so we'll cut this will move towards this is something which we are planning for but let's not take this cutting part first we explore all the parts okay this is just for tech now from three we have two options either to move to six or to move to five right again from four if we take this path then we have two options again we'll check the minimum one this will turn up to be sorry five plus six this will turn out to be eleven again this will turn up to be 5 plus 5 10 this will turn up to be 11 again this will be 7 30 and again you have the same this can move to this and this now let's take the minimum one if you take the minimum one five after five we are coming to 11 10 11 13 obviously we'll take the less one that's 10 now from 10 again we have various options so from five we can either move to five that's uh the same or this so 10 plus one either we have 11 or we have 18 so obviously we'll go with 11. so this is the basic part that we have is it is this so this is the part we want okay so what we will do is now we will check from top to bottom we check i and i plus 1 and we'll add with it and we'll check whether the minimum one and we'll store it and then parry so what i will do is i will take an array name dp okay this is the dp approach actually so i'll name this array dp and we'll have the size with one curator to that of the size of the array okay so uh size of the array or list you can say it was one two three four okay so we have this five elements initially we will store zero in each one of them okay this is what we will begin with now let's see this is what here we'll come here now what we'll do we are having zeros initially let's uh assume we have zeros here we will begin from one okay we will begin from bottom we'll take the i as zero let's i hope you can see this that's i is size minus one that is we are going from bottom to one in this way and j will be from zero to i y zero to y because for every element let's say this is one we are having one element for two we are having two three and four so we will have it equal to 0 and for this we'll fill let's just take this as 0 1 2 3 now for every dp of j we'll fill this dp of j is triangle dot get i for j that's for the first element if we are talking about for now this plus minimum of dp of j and minimum or dp of j plus one so initially both are zero so minimum is also zero adding with four we get four okay so that is what we are getting for now that's four okay then talking about the next one now we'll move to the first that's one okay again checking for one what are we having in dp of g that's tp of j that cp of one is again zero and two is also zero so this will be one same goes for eight and three that is for the last array that's the last row you can see we will be having the elements as it is why because we don't have any values here in dp of g or j plus one why we took this extra element was because for dp of 3 we will take check dp of 3 and dp of 3 plus 1 2 now i becomes 3 sorry 2 again we'll traverse from 0 to 2 so now what it is triangle or dot get dot i dot j six okay plus minimum of dp of j and dp of j plus one okay so minimum of dp of j that's 4 and j plus 1 is 1 so minimum is 1 and 1 plus 6 it's 7 so in dp of g that's 0 we'll have 7. coming to 5 again now dp of 5 plus dp of j and j plus 1 so 1 and 8 obviously one is smaller so we have 6 here again coming to seven plus okay minimum is three so we'll have ten okay again coming to i equals to one now we'll take three and again comparing with seven and six which is one or six so we will store six plus three that's nine here again coming to four smaller of ten and six is six four plus 6 that's 10. now comes to the last one that's 2 we'll check 0 and 1 9 is smaller again so in db of 0 we have the answer of that's the result in level i hope this is clear you can see the code here it's working fine on the test cases as well as all the cases this was a dp solution in case you have any other solution you can type it in the comment box or if you have any queries related to this anything is not k i'll be happy to share the solution thank you
|
Triangle
|
triangle
|
Given a `triangle` array, return _the minimum path sum from top to bottom_.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.
**Example 1:**
**Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\]
**Output:** 11
**Explanation:** The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
**Example 2:**
**Input:** triangle = \[\[-10\]\]
**Output:** -10
**Constraints:**
* `1 <= triangle.length <= 200`
* `triangle[0].length == 1`
* `triangle[i].length == triangle[i - 1].length + 1`
* `-104 <= triangle[i][j] <= 104`
**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
| null |
Array,Dynamic Programming
|
Medium
| null |
142 |
hi all welcome to learn code repeat so today's problem is list cycle which is a cycle detection problem and we'll be solving this using floyd's cycle detection algorithm it's also called as tortoise and the hair algorithm so let's first look into the problem so the problem says given a linked list return the node where the cycle begins if there is no cycle return null there is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer internally pois is used to denote the index of the node that tails next pointer is connected to note that pos is not passed as a parameter notice that you should not modify the linked list and the follow-up is can you solve it and the follow-up is can you solve it and the follow-up is can you solve it using of one space which is constant memory so here the example is 3 2 0 minus 4 and then minus 4 connects to 2. so for this example purpose they are given that the position is 1 so that is the first index so minus 4 connects to 1 here so let's take an example and see how floyd's algorithm will help us so let us consider this as the linked list so we have one two three four five six seven eight and eight again points back to three so what floyd's algorithm says is it uses two pointers and it says that one pointer moves slowly and the other pointer moves two times as fast as the slow pointer and when we go over this linked list there will be a point where both the pointers will meet inside the loop since it's in the loop right so if i normally go over this list right i will go to one two three four five six seven eight then again i will come back to three and this will go in a loop right infinite loop so what floyd's algorithm says is if you use two pointer one that moves slowly and one that moves twice of the speed of the slow pointer then inside this loop there will be some point where both the pointers will meet if both the pointers meet then we can say there is a cycle so here it is not saying that is the first point where it meets the question is about giving back the first point where it meets right so in the question they have asked given a linked list return the node where the cycle begins so we have to return that particular node where the cycle begins right so if both the pointer meets inside the loop that may not be the node where the cycle begins that may just indicate that there is a cycle inside the linked list so how to check where the cycle begins for that the algorithm says that keep the past pointer as is where both the pointers met at the same position and have the slow pointer reset back to head and then move both slow and fast pointer at the same speed one node at a time and after that when both the pointers meet at that time that node will be the node where the cycle begins okay so let's see this with an example right so let's say our slow pointer is marked as s and fast pointer is marked as f okay so initially both will be at the same position which is at head right now when the slow pointer moves one position to this point past pointer will move two positions to this point right again slow pointer will move one position but at the same time fast pointer would have moved two position right so fast pointer will first move to position this here and slow pointer will be here okay then again pass pointer will move to position so it will be one two it will come to this point and slow will come to this point again first point will move two positions one two so it will be here slow will move one position it will be here okay again fast pointer will move two position it will be here but at the same time slow pointer will move this position one position so it will come here right so it won't move at the end of the loop it will still be a different position than fast point right now again first pointer will move to position and first pointer will now come here and slow pointer will also move one position and slow pointer will also come here right now both fast and slow pointer is at seven so this means that cycle is there okay so now we have identified the cycle now let's keep the fast pointer at this position and reset this low pointer back to our head position and now move both the pointers one unit at a time that is one node at a time so first slow pointer moves to this position at the same time fast pointer will move to this position then again slow pointer will move to this position and fast pointer will also move to this position now both the pointers have met so this is the starting point and that's what we are expecting 3 is the starting point of the loop of the cycle right now why does this algorithm works right so consider that if this is a distance m and where it met right where both the pointers met initially this is let us say x right and this whole loop distance that is there is the y distance right so m plus x is actually a multiplier of y okay so m plus x equal to sum z into y and by using this proof we can say that once the cycle is detected we can move one step at a time and there will be a point where both the pointers low and fast will meet and that will be the starting point i won't go in much detail into the proof but you can look into the wikipedia article and there are multiple other articles on floyd's algorithm that explain in detail why this algorithm works but on a general note since slow is moving one step and fast is moving two step if you go in a cycle there will be some point where both of them will meet so that is understood right uh since it's going in the cycle at some point both of them will meet so cycle detection is easier and once that is met we just need to reset the slope pointer and move both slow and fast at the same time one node at a time and when they meet again that is a point where the actual loop started and this algorithm is also important because that way we will also come to know if we have to remove the loop right remove the infinite loop or remove the cycle at what point we need to remove the reference right so here in case if we have to remove the cycle right once we know that both the fast and slow points meet here this is the beginning of the loop right we can again make the fast loop go back into the loop until the fast dot next equal to slow and when it is equal to slow we can remove this particular reference so that way we can remove the loop so if the question was also to remove the loop we could have done that in the next step okay so let's look into the algorithm for this so first we'll check if the head is null if it is null then we can directly return null as the value so here i am checking if head is null or head dot next is not in that case i can directly return now i'll have a slow and fast pointer so both slow and fast pointer is first pointing to the head now in a loop i will try to traverse the list node for slow it will be one node at a time for fast it will be two node at a time so i've used a do while loop here so do slow equal to slow dot next and past equal to fast dot next and after that again if my fast is not equal to null because i need to take care that it can be a non-cyclic linked list right it can be a non-cyclic linked list right it can be a non-cyclic linked list right in that case my fast can be null right so if my fast is not equal to null then fast equal to faster next so i'm doing two operations here for the fast right first is going over two nodes here now here if fast equal to null right in that case we can directly return null right because we know that it is null because uh there is no cycle so we can directly written null here also here we can check if fast equal to null in that case also we can return null so in these both cases we are returning null if there is no cycle and this loop will exit if slow is equal to fast so this is a cycle detection right so after exiting this loop we know that the cycle has been detected now to check which node started the cycle for that we need to reset the slow back to the head so here what i did is i reset the slow back to head and i am doing a simple while loop till slow is not equal to fast both slow and fast is moving at the same speed that is one node at a time and this while loop will exit when slow equal to fast at that time i can directly return the slow node so let's run this code and the test case runs fine let's submit this and the code is accepted so the run time for this will be o of n where n is the total number of plus node that we can have so in worst case it will be o of n and since we are not using any additional space so the space complexity is o of one so i hope you like this video please do hit the like button and do subscribe to the channel for future such videos thank you
|
Linked List Cycle II
|
linked-list-cycle-ii
|
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Medium
|
141,287
|
1,446 |
Loot Hello Everyone Welcome Back To My Channel Today We Are Going To Solve Neither Problem Is Which Give Correct Is This Problem The To Find The Power Of String Events Near To Power Of The Power Of Power Maximum 90 Mean That You Have Only One Unique And The Thing Which Will Be The Will Do Subscribe To Comments Feed To Yehi Eid Suffering Fest-2012 Is Tweet Mean That You Need Fest-2012 Is Tweet Mean That You Need Fest-2012 Is Tweet Mean That You Need Character Was Unique Character Should Balance To 9 Model No Greater Ahirwal Off And Take A Step Up In This Very Simple We Need To Find Something New Something And Which - All Singer Who New Something And Which - All Singer Who New Something And Which - All Singer Who Liquid Not Positive Setting List Subscribe Button To Maximum Subscribe Which Leg Believe One Length Something For Pure Sequence Effigy Straight Little Distance At Least One Rank One Thing Which Will Take The maximum liquid will soften will start from your computer from three 500 600 800 me protein 1516 and 72nd what will start from is difficult-1 and when compared with a difficult-1 and when compared with a difficult-1 and when compared with a begum pure it is the best item now half wake up when compared with this great so 2090 sq.cm 125 - E I fail that I shrunk like this - that I shrunk like this - that I shrunk like this - 176 recording white - One means the 176 recording white - One means the 176 recording white - One means the practice of similar to two express just so friends welcome to dinner I will go for destroy condition which means of water till now na Amla RSI is series optical to be software this avoid civilian shiv will update maximum something which can be quiet is length to inactive will update were next9 doobie naav V2 specific artist 2009 actor vikram at this time that suzanne what we will do it is will go Back Toe Will Soon Sleep Vikram And Read Forward In Loop C Is Equal To Fati Means Will Prevent This Condition Sunil Increment Equal To Max 100 Answer To Prohibition Teaspoon Citric Acid Condition Is Not Good To Hear This Song In Three Grade To Do Subscribe To Updates Reviews And Danny To Increment Every x21 200 Similarly I Will To Forward Seed And Digital 3D Painting Images And You Can I Do Na That I Co Share Is No Duty World E C Every Year Will Do This Tips For All Answer Will Updated Soegi Values For Which For All Answer Will Updated Soegi Values For Which For All Answer Will Updated Soegi Values For Which Made And Answer Value So Answer Will Get Updated With Them For Android X BP Come Again In The Course Of Clans Devi Warning Spelling Of Incorrect Song Again I Ko Seervi Acidity Increment Twitter Bittu Divorce Hair Increment Festival Similar Request Increment Hydride Key Increment Name Micro Seervi And Receive Notifications And Chief Compare Answer Boys 28 Will Get Updated 256 Vikram Soft Na Gauriyon Seervi thing notice ruby to age Vikram Soft Na Gauriyon Seervi thing notice ruby to age Vikram Soft Na Gauriyon Seervi thing notice ruby to age also no name witch app that when effective this grade one and answer no 142 12345 no need to update and actions will again welcome one with positive one will get updated show devi like and share is not good to see such Friendship's Answer Will Not Get Updated With A Positive Attitude And Actions Will Welcome One 100 Index Vyavas Ho Singh Sushil Disposal Basic Logic This Temple's That Tweet Voice With Two Variables I One Word Answer In English Two One Because It Is Drawn In Suffering And 116 Actresses What is the cone is something length which is unique in its right now avoid her from one to go to the element to liquid liner remind me to get maximum value and they will update you know it here open today Logic Teri Sample Flat C The Code of Conduct Document Ko Dant Se Zee TV Were Taken Two Variables Started Loop Same Condition End At Last When Som Vs Case Security Them Own This Thank You Will See That After This Follow Your Answer Will Have You Want Oo This Pardes Test Case Yes Brother So Because It's Not Fair Tourism And Courier Father For Safety Say One After This For Loop Just Put An Answer Let's Match Answer Comment Diamond Is Attested Serial Better Understand Why They Have Written This Five Line So Ifine Solution Is Pigmented If I am then I hope you understand the problem is logic body problem but he is confident outline the video is for you for details please share with your friends subscribe my channel and x video
|
Consecutive Characters
|
angle-between-hands-of-a-clock
|
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string `s`, return _the **power** of_ `s`.
**Example 1:**
**Input:** s = "leetcode "
**Output:** 2
**Explanation:** The substring "ee " is of length 2 with the character 'e' only.
**Example 2:**
**Input:** s = "abbcccddddeeeeedcba "
**Output:** 5
**Explanation:** The substring "eeeee " is of length 5 with the character 'e' only.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters.
|
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
|
Math
|
Medium
| null |
261 |
all right so let's talk about the value tree so you're giving a graph of node and then you want to return to if the edges of the given graph make up the value tree so uh if a tree is like this it's definitely okay so you return true if you connect like if there's a cycle right um you want to return false so for example two right so there's is and uh there's additional line uh right over here so this turns out what one two three are in this uh are in the cycle right because this is an under graph so in this question you can use the union fine so unified is pretty helpful so unifying i can just what so i said everything independently uh how many one two three four five right so zero one two three all right so basically i connect uh everything by i mean two uh two itself right so i will just say this initially and then if i just get the edges from the to the array right so zero to one so i would just say zero to one or something like this right and then zero to two right um sorry i have no idea what i raised but and then this is zero to three right and then one to four so one two four right so i can just check right if i'm in the cycle now right so uh this color so if i go from zero to two right then two complex two compressor two right so this is not this is like a one note cypher this is not like a two note cycle right so this is okay and i mean it doesn't matter it's zero to two to zero right two to zero to three and then what three right so it doesn't work right so uh this is okay so i'm gonna stop coding and you'll be able to follow along but you need a unifying class so i'm gonna say across uh uf ufc uh uf as union point so i will have a uh i will have a parent so which is going to be just point at the paranoia basically so probably uf i'm going to give a size so i'm going to initiate the size for parent and i'm going to just initialize my current array to keep itself right so this is initialized and i'm gonna call union so i want to find out what's my route of my terminal so what's my ancestor right so your a able to find no one so i would need to have a i would definitely need the fine function so probably so fine i mean like you want to find out who is your uh virtual current ancestor so far so the accessor should be the top of the current subtree based on the node right so i'm going to say uh in fine and then you know right so uh while the node uh well the node does not go to parents i know right so if they are not equal right so no will be basically like no will be three so if i have a three right so there's a parent i mean there's a pointed point all right so if the three does not point at itself then i would just keep doing this because there should be someone like this guy point a right so well no it's not equal to payron then i want to update my payron to grandparent right and i'll update the note to parents so you'll just keep going on the next level so i will return which is the parent the ancestor so now back to the union so when i find out who is my ancestor for root a i mean no one and no two which are root a and root b so if they are not the same if they are not ascend right so i will have to assign one of the route to the other one right so i'm going to say parent and if you can say rupee so i'll point my group b to eight and i mean you probably have to check out the size so if the size is actually what root a size is smaller than root b so you want to connect a small tree to the bigger stream right and then vice versa for root b size is what uh necessarily all right so um what do you have to do so you want to basically like this and also another function this should be public right so another helpful helper function i'm going to check a boolean so i want to say this a list to know i'll connect right so i'm going to find one here and this is pretty much it right so again you are missing one element so the one element should be what should be the account and then the count should be wrong it should be useful to your size and then whenever your union like uh whenever your union you want to subtract one right and then basically this is supposed to be right so um yeah so let's move on to the largest tree so i'm gonna create a uf union edges 0 to edges 1 but if they if there are connect right if uf star is connect the edges 0 comma and then later on you want to check uh that's my union count is actually put one right and this is because like if they are uh if they are the same i mean if they remember one which means there's only one root right it doesn't comment on anybody or i mean yes so you just hold them mistake dice right and then parents 9 19 should be fine right yes all right let me submit so let's talk about the timing space uh full of space right it's going to be 11 real number of the in array uh i mean number of lengths based on the updates on them so it's all fun enough for the time this is what low key all of you right and then you want to compare union so every single time it's a one total of two which is like two edges right and then you want to check where it's coming right this corner is a little bit painful you want to be fine right and then urine you also have a fine right so let's talk about this is going to be about all old age h represents the height of the high dosage current tree so follow for the worst case right it's going to be all the height of the tree so i'm going to say the worst case for the time is going to be all of e times h right so this is my solution so time is over e h and then space is over n right so this is a solution and i'll talk to you later bye
|
Graph Valid Tree
|
graph-valid-tree
|
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph.
Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\]
**Output:** true
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\]
**Output:** false
**Constraints:**
* `1 <= n <= 2000`
* `0 <= edges.length <= 5000`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* There are no self-loops or repeated edges.
|
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
|
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Medium
|
207,323,871
|
783 |
Hello friends today I am going to solve liquid problem number 783 minimum distance between BST notes so in this problem we are given the root of a binary search tree and we need to find the minimum distance between the values of any two nodes in the tree and the two nodes should be different and it's also not specified that the two nodes should be adjacent nodes which means that the two nodes could be any different nodes it could be node for a note 3. so now let's look at this example here and find out the minimum distance between the two nodes so just by looking at this example um at this tree we can know that the minimum distance would be equals to one why because um we have node one and two we note that binary search three all right since this is a binary search tree we know that the roots are basically um sorted when we move from left to right so if we do it in order traversal uh we would find a sorted array so let's choose performer in order traversal here so we start from our root node and we move to its left until and unless we found find the leaf node now once we have found our Leaf node um this becomes um our node uh which we uh this becomes the first element in our array so we push our the value of the note to our array and then next um this root becomes the next element so we push the value of this root and then we move to the right of the sub tree so now this is also Leaf node so we push this node to our tree now we backtrack and we found uh we reach this node right so we have already travels all the left nodes to its left so now we push this node to our tree now it travels towards its right and for this node there is no right left node or right node right so we just push this node here to our tree now to find the difference we take the difference between the two adjacent nodes so the difference between these two notes would be equals to one the same is with this case the difference is one um same is with this case so difference is one however the difference here is equals to 2 but the minimum of all of these is equals to one right so that would be our answer so basically we are going to perform in order travels sold so the traversal that we perform is in order here but since we are using an array so the space complexity becomes o of n and the time complexity becomes um oov and as well so how can we actually reduce the space complexity because the time complexity will still be the same since we need two Traverse all of the nodes to find the values and then um find the minimum distance but we could actually solve this problem in constant space complexity so let's see how we could solve it in constant space complexity so for this also we are definitely going to use in order traversal but now um instead of using an array we are going to store uh use a variable previous where the previous variable will store the value of the node that would actually be the previous value in the array so we actually found our array one two three right and so on so basically the previous of no this Note 2 would be the value one and the previous of three would be two so now how do we find the previous uh node so basically what are we going to do is we are going to perform in Auto traversal and um we travels towards the left of each node so now for the subtree travels towards its left and for this sub tree since a single node is also subtree we try to Traverse towards it left but there is no left subtree right so we go towards the left of the tree left of the node and then once we have returned so if once there is no left note we return from the uh from our recursive call and then uh what we do is we calculate now the difference initially the previous value is set to now because there is no previous to node one there is no previous write to this node with value one so initially the previous value is set to one uh to null so for that case we won't calculate um the minimum distance now in the next case what we do is we actually set the value for previous so now our value for previous becomes equals to one now in The Next Step um we backtrack to the node 2 and then we try to move to the note to its right but before moving to its right now we have the previous value right so we already have the previous value set while we were here so we are going to use this previous value and find the minimum distance so what would be the minimum distance so far so the previous value is equals to 1 and the value of the current node is equals to 2 right so that would be 2 minus 1 which is equals to 1 and the minimum distance we do not have any values so that we would set it to Infinity so now the minimum distance is equals to one now once we have found our minimum distance we then update our previous value to the current node so this will always be the value of the root so now the value of the current node is equals to 2 right so the previous value becomes equals to 2 and then we go towards its right sub tree so now we go towards its right so the right note is three and then for each recursive call for each sub tree we are going to do the same three so um once we make the call this itself is a sub tree right so now for this sub tree we make our traversal tools it's left but since there is no left sub uh subtree so we backtrack and then we have a previous value equals to 2 right so now what we do is we calculate the minimum distance again so uh basically we take the minimum between two minus three um so we are going to take the absolute value so that would be 3 minus 2 so that the value would be equals to 1 and since the minimum values distance is already one so there is no change at all in the next case we try to go towards its right oh before that we update our previous value now the previous value is equals to the value of the current node which is equals to 3. now we try to move towards its right but since there is no right node we backed track towards its parent node and then finally we reach this node right so now we have completed traversing it's left so we Traverse its left next now we are going to perform our calculation so the previous node is equals to three current node value is equals to 4 so distance would be 4 minus 3 which is equals to 1 the same as the minimum distance so no change at all now we go towards its right and we perform the same computation so since there is no left node um so and okay we actually have to update this previous value before we go towards its right so we update it to 4 and then we go towards right which is node 6 here and then for this we go to its left since there is no left now we perform our computation so previous value is equals to 4 current value is equals to six so six minus 4 is equals to 2 and minimum is equals to one so it there is no change in the minimum is still one and then we try to go towards its right but before that we update the previous value to 6 but since there is no right so we backtrack and then finally we have uh traversed the whole tree and we finally return our minimum distance which is equals to one so now let's try to code our solution so what do we need is the minimum distance will set it to Infinity all right and the previous value we'll set it to null now we are going to perform our DFS so let's construct our DFS function so we are going to pass the root value here and if the root is null then we are going to return else we are going to perform in order travels also DFS towards it's left and DFS towards its um right but before we travel towards its right we perform our computation so what we do is if we have the previous value set then we are going to um find our minimum distance which will be the minimum of the distance itself and the difference so basically root dot value will always be greater than the value of the previous node because it's a binary search tree and previous note is it's sorted in ascending order so that's the case so we take the minimum of both of these and then we update our previous to the value of the current node and finally we call our DFS function and return the minimum distance let's run our code oh something went wrong here okay so we are not passing the value we are just passing the root node because when we are taking to that okay let's submit it cool now um the time complexity is off and for this solution and space complexity is um not constant because we are performing a recursive call so we are actually storing um the stack uh for the recursive call so that would be a bigger of the height of the tree and the world in the worst case the height of the tree could be um of um could be n minus one where n is the total number of nodes in the tree so yeah
|
Minimum Distance Between BST Nodes
|
search-in-a-binary-search-tree
|
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
| null |
Tree,Binary Search Tree,Binary Tree
|
Easy
|
270,784
|
56 |
hello and welcome today we are doing a question from weak code called merge intervals it's a medium let's get started given a collection of intervals merge all overlapping intervals example one given the input 1 3 2 6 8 10 15 18 we output 1 6 8 10 15 18. so 8 10 15 18 stayed as is they don't overlap with anything so they didn't really get merged but one three and two six they do overlap so we merge them into the entire range they cover which is one and six example two we have the input with start time one and time four start time four and time five so that gets merged into one five since it overlaps on the four so this is actually pretty straightforward we just need to make sure we understand what it means to be an overlapping interval so over here we can see that b overlaps with interval a and we know this because b start time is greater than equal to a start time and less than equal to a's and time so it lies within a's range if that wasn't the case if a was further out if its start time was greater than both a start time and its end time we know that they don't overlap so what i'm actually going to do for this is take my input and i'm going to sort it by start time so over here it's kind of already done for us we have 1 2 8 and 15 in increase in order what this allows us to do is say that for any interval we're on any interval that comes after has a start time greater than equal to our start time so we always meet this condition the only thing left to check would be if its start time is less than equal to our end time and then we know we overlap and then converge so if i had another interval say with its start time at ease end time and it's end time later on then i also had d that was over here start time sometime after c's and time over here say this was longer and i had e which had a start time over here and end time later on so how would this look like we see that it's already sorted by start time a is earliest then b c d and e now as we iterate through we see that b has a start time greater than a because we've sorted it so that's already established and its start time is less than b's end time so we can merge this into one interval and we'll have a new interval as so now this is our new merge interval now we move on to c and see that it also merges into our new interval so we can merge this again into an entirely new interval with all of it together we see that d also merges into c its start time is greater than c's and less than c's end time so this also gets merged into this interval but since c's and time is already ahead of d's we don't really need to change anything this can fit as is and e's start time is after c's end time so it doesn't overlap and would be an interval by itself so that's the intuition behind the solution let's just go ahead and code this up so if intervals is empty we return the empty list and i'm going to have a list called result to return my final answer now the first thing i want to do is sort by start time so intervals dot sort this is just the default function which takes the first index to sort of all the intervals in that list so this is gonna store it by start time and now that is done i can go through and iterate so for interval in intervals um when do i add the entire interval to my output list well if it's the first interval or if there's no overlap so if result is empty or there is no overlap so the last thing i added to result its end time is less than my start time so that means that interval has already ended and mine's going to start some time after so or result -1 the last thing i ended to or result -1 the last thing i ended to or result -1 the last thing i ended to result it's end time so n times our index at one start times our index at zero its end time is less than my start time so interval of zero in this case i add result to interval or in this case i add my interval to results so results dot append interval if that is not the case that means there is an overlapping interval so here the last thing i added to result i want to make sure has the maximum and time it covers the entire range so result minus 1 index.1 it's endtime so result minus 1 index.1 it's endtime so result minus 1 index.1 it's endtime equals the max of whatever is my end time right now for the end time of my interval so interval of one so to walk through this same example we just use here it's already sorted by start time so we can start in the for loop we have an empty result and first result is empty so we go ahead and append our interval 1 3. now we move on result is not empty so now we have to check does the last interval i added to result does it and time come before my start time so my end time is after the next start time so that means there is overlap and now i have to see what my interval should range over so six is greater than three so this is going to go over from one to six it covers one two three and two three four five six so all together it is one six now i move on to my next interval and i see that the last thing i added two results had an end time of six which is less than eight so there's no overlap here and then add the entire thing to result and same with 15 18 no overlap so i added the entire result and as we can see this is exactly what we were expecting so i'm going to go ahead and run code after i return result code accepted and submit and it is accepted as well if you have any questions let me know down below otherwise i'll see you next time
|
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
|
1,585 |
hey what's up guys this is chung here so today uh let's take a look at this a weekly contest the last heart problem uh which is number 1585 check if string is transformable with substring sword operations this is a hard problem yeah i think it's really tricky problem it is hard i mean even though the coding part is not that difficult but the intuition is not that easy okay so okay your let's take a look basically we're you're given like two strings a source and target okay and you want to transform string source into the string target by using the following operations you can use as many times as you want basically you can simply choose any of the sub array and then you can like sort you can sort them basically you can sort the uh any subarrays okay and return true if it is possible to transform string ads into the target into the string t otherwise return false okay so a few examples here i mean for example this one right so the solution it gives you is the uh example is like basically first like sort uh 5 three two three five and then we sort uh eight three four to a three four eight and then we got the answer that's why we return true here and this for this one it gives you another example here basically there's no way we can transform that transform this s into t because uh because the 3 4 cannot be transformed to 4 3 okay so and the s length is like 10 to the power of 5 which means you can only solve this problem by using either a linear time or unlogan okay oh and s and t only contains djs from zero to nine okay so that's the constraints here i mean so at the first glance right i mean i think for most people they will try to follow what the problem is asking us to do basically so we will be trying to sort like this uh sort the uh the arrays right basically i think the first approach will always be like what the uh we find the target here we find the target three the first one okay so i think we should always start from this the first one and we find three here and then we uh okay we will try to see okay what's the index what's the position in s okay and then can we sort that can we sort uh reverse these three uh to the current position okay and then if we can right so in this case let's say we do a resource three now it's gonna be a three four five eight two okay now the three is at the current position here okay now we will look at four here can we uh put four here and then eight and then five or two etc right i mean this one the first of the first approach intuition is more like a pancake sorting if you guys still remember that basically we just sort a summary and then we try to make this source equals to target but the problem of doing this is like the overhead is it's too high you know and of and another thing is that i mean since every time we will sort everything let's say for example let's say the we have a very long list here start sourcing target okay and let's say we the first item in the target is two and it happens that the two is the last one happens to the two is the last one in the source ticket in the source like uh in the source string so what we're gonna we're going to basically try to uh flip make sure this two is the smallest basically we have to make sure two is the smallest uh number right uh among all its all the previous numbers okay that's how we can make sure right we uh after sorting two can be placed at our current position then in order to do that we have to basically loop through everything all the numbers in front of it right and then i mean even though we can do it because the uh i think the constraints that we can there's all there's only one uh zero to nine like numbers so that we don't have to let's say there's like uh a one uh ten thousand numbers here i mean basically we don't have to look through ten thousand numbers here instead we can uh what we can do we can like basically create like a hash table or like uh whatever or list of lists basically we store each numbers index right uh in that hash table or word or a list of lists then we will just compare uh since this is two here so there are only two small smaller numbers uh before two which is a zero and one okay so we just check if among zero and one if there's any index that is smaller than two then we know okay we cannot sort we cannot move these two to the front okay i'm actually not remember this so basically in our second solutions we'll also utilize this kind of idea here but okay so let's say we find that we can sort and then what do we sort we store everything okay we're going to sort this the target as are we going to do us s word here right we do a sword and then the sword will be changed and then we're moving to the second one okay now we're comparing the second s here now two is here okay and now we have like a totally different sorted array here okay so that would be a lot of overheads basically you know and it's not a good solutions because we are okay we actually you know by sorting the two here we are breaking the relatively positions right uh between among all the uh all the previously numbers which we don't need to do right for example in this case i mean uh let's say we have like uh how can i say that uh let's see eight four five two okay and let's say the this is s okay and the target is what the target is two eight four five okay this is pretty it's pretty easy right i mean let's see if that's the case right i mean if this is the one i mean all we off we move two to the beginning right but let's say we do a sort right and there's going to be a 2 4 5 8 okay now we have 2 4 5 8 but our target is this so we have to keep going keep doing the sorting which will be uh like too much like overhead actually the correct solution for this problem is that while moving the two to the to its desired locations we should maintain the relatively positions of the remaining numbers so how we're doing that basically every time we're only doing like a swap with this it's like previously numbers basically we swap two to eight here so two will become to here and then we'll become to here will become to here so this is exactly like the bubble sorting right so the way it's because we can do an unlimited times of sorting okay basically we only sort these two numbers now this after sorting five two it becomes two five and then we store this is two and it's come becoming two and four and then we store this one becoming two and eight and i think you guys have already discovered you can only keep doing the sortings until you reach a number that is smaller than him okay let's say we have eight zero four five two basically it means that you can only uh bubble the twos until here so once you once two is here and you have a zero in front of him then there's no way you can keep doing the sortings okay and that's the uh one not one other intuition and okay come back to this problem right how can we do that basically you know we just uh okay i'm going to use this one as an example here okay so we have a eight four five three two and the second one is the three four the target is the this one okay and so first we're gonna like uh pre-process the source pre-process the source pre-process the source string and we're gonna uh store all the uh all the indexes for each number so that it can be used later on and then we will be starting from the target string here one by one we start from the first one okay and the intuition is we always try to uh bubble the three to the front of to the very left okay so why is that okay because you know let's say that we are at three here right at three here and then we are we're trying to bubble three to the very left okay and then for so how can we make sure we can bubble through it up to our to the very left like i said we need to make sure for all the there's no uh basically there's no numbers uh which is smaller than three in this case is zero one two right uh appears on the left side of three right it's pretty straightforward if there's any like zero one two three on the left side then we cannot bubble three to the very left okay so in this case we can okay so after the bubble up right so we have like three then we have a like three eight four five two okay and uh after that basically we're gonna remove this these two numbers from the uh from both the source and target i basically we're done by removing i mean d i'm going to remove those indexes this indexes from the preprocessed like index hash table so that we know okay three is done and this is also done right so now the uh the target becomes to the target becomes two to four here so which it which means now we're processing four here okay now the four becomes to the uh the very left okay now the problem is that like can we move three or four to the very left because remember so here at this moment right there's no more uh three here so that's and since we're at this four and since we're when we're processing the target here we are like processing from left to right so this one is as if every time we're always at the left most side of our of the target string here that's why we can think of this we are always trying to move the uh this number right from the source uh string all the way to the left to be able to match with our v with this position here okay so now can we move forward to the very left yes we can right because there's no uh 0 1 2 3 on the left side we have a 3 here but since we have already matched 3 already that's why the index of the 3 had already been removed from our array or hash table so that's why when we checked the 4 here we didn't see any 0 1 2 3 here that's why we can simply move like the uh the three ah sorry the four here okay now the four is done okay now it's the time for eight okay same thing right now do we have like zero one two three four seven no right because the four and three they have or they are they're all gone so now eight is gone same thing for five is five there okay it's can we move five to the very beginning of the array here yes now five is gone two is gone that's why we have a true here so another example let's say one two three four five and one two four three five okay source and target okay same thing so for one pretty straightforward right because at this moment there's no zero on the left side out of one here so one is gone same thing two is gone okay so now this is the s and t here okay and at this moment we're trying to move four to the left side of to the left at the very left of the s so that this four can match with the target but since as you guys can see there's a three here in front of four which means we cannot move forward to the very left of the current s here that's why we have a force here okay cool so i think that's pretty much the uh the intuition of this problem and as long as you can figure out the uh the nature of this problem it's just trying to move each number to the very left of the updated string right so the way we're doing it with the way and when com trans convert to the coding it means that do we have any unprocessed number right which is smaller than four that's on the left side of four if there is then it means that we cannot move this one to the very beginning of the to the very beginning so that it can be can match the our current target string here cool uh all right so let's start coding here uh like i said let's try to do uh like n of s here and like i said we need to pre-process the indexes right so pre-process the indexes right so pre-process the indexes right so since we only have like uh from number zero to nine here we can simply do a you know an array four like in range like 10 right that's the all the numbers we need and yeah and since uh we're going to pop on the left side uh let's do a dequeue here we're going to do a dequeue since we're going to pop on the left later on yeah okay oh and i think one thing i haven't noticed that let's say we have duplicated numbers right so the reason we're doing the dq here is because let's say we have a two threes here uh in the source like uh string here and when we're trying to match with the target here right every time we have a target here uh and once we find up once the target three is it has been matched okay uh has been matched here let's see for example three here we're going to remove the ones on the we're going to remove the index on the left side first basically where every time we try to remove like the index from uh a source index we always remove the ones on the very left so the reason being is that you know we do this so that i mean uh so that i mean let's say we have a three here right we'll be uh matching the numbers on the left side first because this one has the better chance of matching the three here okay because let's say we have like uh we have four here right we have four and one so now we have a three here and then we have a maybe an another four here and then in between we have like um how can i say how can i think of this maybe uh two five three how about this okay so let's say we have one point four three two five three and then uh when we match the uh one three four here so one is matched okay now let's match three here and basically we are trying to match the ones on the very left okay with three it's kind of obvious right because why is that because if we're trying to match this three here okay then it means that i mean they're like uh there are like then let's see here so this is because you know we all every time when we try to match the compare then the index we always use the where the index on the first on the very left one because you know if we use the index on the later one on the right side then we have a two here but that's not correct because we haven't reached that part yet because we have to match the three here because every let's say we have two three two five three here you know so when we match three here we always want to match with the very left three here so that we have four two five here and then two five or two or five are gone and when we match that the lot the next three here is also valid that's why we have to use the uh dq basically every time we finish a mapping we will pop this index out of the uh the dq here that's why we do a pop left okay so uh all right so that's that and now let's pre-process the and now let's pre-process the and now let's pre-process the let's pre-process the uh the indexes let's pre-process the uh the indexes let's pre-process the uh the indexes for s i in uh in enumerate s we have indexes that's the what's the number c oh see you know so since we're going to compare the smaller numbers here we need to convert this character into an integer so that we can compare them right dot append i here okay so now the since the index is always increasing right so that's why we have a uh a dq with the index from smallest from smaller smallest to biggest so now let's do a uh the target okay we have a target character okay in target uh target number okay in the ins equals uh convert this one to c okay target number so like i said i mean the uh i think we also need to check one more thing here basically you know if the target number does not have any index is left like say for example the example four here when we comparing two here okay so there's there isn't even any uh indexes for two left and then we can simply return false so that's why we have to check is this one if not uh indexes right uh it's target number basically this one is telling us right it's checking like if there's no more indexes in the source string to be matched with then we can simply return faster okay so otherwise if there is then we just need to check okay if there's any uh basically if we can move this card number uh from the source from the updated source string to the very left so the way we're checking it is we if this one can only be moved to the very left if there's no smaller number on the left side of this number okay right so how can we do that like i said since we only have like zero to nine to be able to search we basically we're gonna look use like a brutal force way of searching all the indexes which is smaller than this number so we do a smaller number okay in range t sorry t number that's how we search the smaller number for this number and since we have a hash table right we all we need to know is that okay if the indexes for this smaller number exist and the smaller number okay so see if there are like more than one like appearances for these smaller numbers like i said we always use the ones on the very left because we're trying to move this number to the left side right and what ends the uh and the indexes of the smaller number the zero okay this zero means that if there's like more than the indexes for the smaller number we just need to get the ver left one okay if this one like smaller than the indexes of the target number that's uh zero right like i said we always uh all we need to all we care is the very left one okay if that's the case right we simply return false because we know okay we find the smaller number um we find a smaller number for the card number uh i mean smaller than the card number on which is on the left side which means we cannot move the current that's t number to the very left then we return false and if it can be moved to the very la uh the very left side then we can simply uh pop right basically the way we're popping it is to what we do indexes right number dot pop left right so this one means what it means that like uh it means that i mean after matching the three here okay the three and three here so we uh we need to remove sorry we need to remove the indexes right from the source basically we're removing this number from the source string okay and the way we're removing it we're removing the this numbers index from the indexes like uh list here so that later on when another number trying to look for the trying to search the indexes again we it won't see this uh index or this letters again okay cool so and then if everything works fine we can in the end we simply return true here cool i think this should work all right so this one is true submit cool so it's accepted i mean and as for the uh the time and space complexity right i mean the uh i think the space is also linear because you know even though we have like uh only 10 elements but for each of the elements we could have like many like indexes which is the number of n here right and also the uh basically that's the space complexity and for the time complexity i mean this one is like a four loop so it's on right also linear like on this one is also like uh this is also owen and one wins for inside the loop here um i mean even though we have like uh a for loop here but this one is bounded with 10 here okay which is like constant right so we can also like treat this second one it's all uh o n so yeah basically you know and this is like one here and this is al also want to look for the uh the array here right so i mean space and time complexity they're both like linear which is all of n and yeah i mean that's i think that's pretty much it is for this problem i mean it's a very tricky problem it requires you to make a few like tricky observations like first one is to uh you know sometimes or like i would say most of the times the way they're describing the examples is always misleadings it basically they're trying to hide the true uh nature from this uh of this problem from you that's why they did doing the like the sortings this way right so i mean if you follow this one probably you end up like in a you know not in a bad situation right so i think the first difficulty for this problem is that you have to be able to figure out uh why uh since you can do this the sortings as many times as i mean as you want right so the nature right of make of moving three to the desired position is to make sure we can uh swap or we can swap the three all the way to the beginning so when i say swap you which basically since we can only do as ascended ordering it means that you can only move three to the left when the left one is greater than three okay and we're doing that by also maintaining the orders of the remaining uh of the all the previously numbers yeah and the second one is that i mean every time once you finish matching one of the numbers you need to remove that from the uh from the indexes so that i mean the later the next number will not uh will not be uh using that's like the match number as like as the criterion to determine if y can be if it can be moved to the very left and the third one is the i you know the only the relative position matters i mean let's say for example like we have eight four three here right i mean if you're looking at three here if we have three here okay so we match three we i mean we match four and then when you are looking at eight here i mean you may be like okay the current aid is at uh index two here and the source in that the source eight is index zero and do i need to worry about that okay right i mean it turns out that you don't need to worry about that like i said i mean after we after re removing uh matching three and four here right uh three four eight five two oh sorry after matching three and four okay all we need to care is the relative position of the remaining uh the remaining like the numbers because uh the way we are like uh matching the three and the four is we all we are we're not disrupting all the right the other numbers relatively positioned that's why we can simply ignore the current position of eight and this eight okay so all we need to carry is that can we move the card number from uh in the sort from the source to the left to the very left from the source string okay cool i think that's pretty much it is for this problem i think oh sorry i think i already said that before sorry uh sorry about repeating myself uh i just want to make uh make sure you guys understand this like it's hard problem clearly and okay thank you so much uh for watching the videos guys uh stay tuned i hope you guys like the videos and see you guys soon bye
|
Check If String Is Transformable With Substring Sort Operations
|
the-kth-factor-of-n
|
Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` results in `"12344 "`.
Return `true` if _it is possible to transform `s` into `t`_. Otherwise, return `false`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "84532 ", t = "34852 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"84532 " (from index 2 to 3) -> "84352 "
"84352 " (from index 0 to 2) -> "34852 "
**Example 2:**
**Input:** s = "34521 ", t = "23415 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"34521 " -> "23451 "
"23451 " -> "23415 "
**Example 3:**
**Input:** s = "12345 ", t = "12435 "
**Output:** false
**Constraints:**
* `s.length == t.length`
* `1 <= s.length <= 105`
* `s` and `t` consist of only digits.
|
The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list.
|
Math
|
Medium
| null |
1,544 |
uh hey everybody this is larry this is me going over q1 of the recently go contest make the string great uh so yeah so the idea here is just that uh for me i just did it greedy uh and then the thing is that when you combine 2 j or remove two adjacent characters you keep doing it right uh so the natural um the natural answer then is to yeah the natural way to do it is just by using a stack um yeah so i implement a stack i implement i push the finger on the stack every time and then anytime there are more than two characters and if they're uh g code but not equal you know given these constraints then we pop them both off by we and then removing them and then in this case whenever we get a the next character it would compare it to the characters that were before uh so in this case like it'll be probably b then a will be the next one in stack and so forth um because the invariant is that whenever you get one count to come in you can only remove two characters right itself and the previous one so using that and giving the n is equal to 100 you can do this really quickly so that's q1 and you can watch me sub it live now what oh you
|
Make The String Great
|
count-good-nodes-in-binary-tree
|
Given a string `s` of lower and upper case English letters.
A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where:
* `0 <= i <= s.length - 2`
* `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**.
To make the string good, you can choose **two adjacent** characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return _the string_ after making it good. The answer is guaranteed to be unique under the given constraints.
**Notice** that an empty string is also good.
**Example 1:**
**Input:** s = "leEeetcode "
**Output:** "leetcode "
**Explanation:** In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode " to be reduced to "leetcode ".
**Example 2:**
**Input:** s = "abBAcC "
**Output:** " "
**Explanation:** We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC " --> "aAcC " --> "cC " --> " "
"abBAcC " --> "abBA " --> "aA " --> " "
**Example 3:**
**Input:** s = "s "
**Output:** "s "
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only lower and upper case English letters.
|
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
171 |
welcome my friends to joey's tech in this video we are going to solve a lead code problem which is excel sheet column number the problem is fun to solve so without further ado let's now take a look at its problem statement you are given a string column title this column title string represents the column names or column titles given in any excel sheet the ask is to return the corresponding column number so if the column title is double a then the program should return 27 as the column number because it is indeed the 27th column from the start if you take a simple column title such as c then the program should return 3 as the column number okay let's first discuss the intuition behind the solution but before that if you haven't subscribed to my channel yet then hit the subscribe button and the bell icon because that way you won't miss out on these coding tutorial videos that i create for you take a look here the alphabets from a to set have corresponding numbers from 1 to 26 and just by common sense the number of the column double a will be 27 because it is the first column after column z so the number of columns 8 which is 26 acts as a reference for this set of columns starting with a this means that any column from this series starting with a can be rewritten as 26 multiplied by 1 which is the column number of column a plus 1 which is again the column number of column a okay so if we have to find out the column number of this column title ac then using this formula we can write 26 multiplied by 1 which is the column number of column a because this whole series is starting with a plus 3 which is the column number of column c okay this is going to give us 29 which is indeed the column number of the column title ac so using the same formula for this series starting with b so this expression is going to give us 680 which is indeed the column number of the column title z d now after this double z column the next column of the excel sheet will be triple a let's dissect it a little so for that i am going to write this double set column over here like this and a triple a column like this okay so if you think through it then adding one column to this last set gets you double a okay and does this set changes to a and it becomes a three alphabet column series this is how i thought this through the point i am trying to make is that the calculation of this a will be done in the same way as this set and how this set was calculated it was calculated as 26 multiplied by 26 we just calculated it over here okay and this double a has already been calculated as 27 so let me put 27 over here this will be 676 plus 27 and the result that is going to come out will be 703 which is indeed the column number of the column title triple a thus using the analysis we did triple a can be rewritten as 26 multiplied by 1 plus 1 these two components have been taken from here okay this is the same calculation that we used to calculate the column number of double a all right so the point is that when we analyzed the column series of two alphabets then our piece was only 26 and now for the three alphabet column series the base has increased to 26 multiplied by 26 or 26 to the power of 2 thus by clubbing all these expressions we can rewrite this formula so it will be 26 to the power of 2 multiplied by 1 which is the column number of the column title a plus 26 to the power of 1 multiplied by 1 which is the column number of the column title a plus 1 okay so this is how triple a can be rewritten this same formula is what we are going to implement in a java program and based on this formula if the column title becomes 4 times a then the formula will be 26 to the power 3 multiplied by 1 plus 26 to the power 2 multiplied by 1 plus 26 to the power 1 multiplied by 1 plus 1 this will be the formula for the column title 4 times a i would suggest that you go through this explanation again because it is very easy to crisp once you have understood the concept behind it now let's implement this formula in a java program so this is my intellij id in which i have created this class excel column number i have already created the main function in which we are going to write the code so first we are going to declare and initialize a string variable we are going to call it column title and that is going to be initialized to a string triple a okay because that was under scrutiny so that is why i am putting the string as triple a which is our column title now what we are going to do for convenience we are going to convert this string into a character array so lets declare a character array it will be care square brackets lets call it arr equals to column title dot to care array okay this is going to do the job for us all right now we are going to declare an integer variable which we are going to call result and we are going to initialize it to 0. it is obvious that this result is going to give the column number corresponding to this column title triple a now we are going to start a for loop that is going to iterate over this character array so it will be int i equals to 0 it's going to start from the first cell at index 0 and it is going to run all the way till the last cell so i will be less than ar dot length and as the third component we are going to write i plus within the body of the for loop we are going to write a result plus equals to calculate the column number of this column title triple a we came up with this formula we are going to first write the code to handle this expression 26 to the power 2 then 26 to the power 1 and this one can also be written as 26 to the power 0 multiplied by 1 thus we are going to make use of the math.paw function so we are going to math.paw function so we are going to math.paw function so we are going to write math dot paw and as its first parameter we are going to pass 26 and as its second parameter let's pass an integer variable pow only let's declare and initialize this pow variable to arr dot length -1 -1 -1 okay the length of the array in this scenario will be 3 and thus the initial value of the power variable will be 2 and that's what we need in the first iteration in the next iteration it will reduce to 1 and in the last iteration it will reduce to 0. so as the next line of code we are going to write pow and we are going to decrement it by 1 at the end of each iteration now using this piece of code we handled this part what about this one is the column number of the column title a and how we are going to find out the column number of a particular column title it is simple after the multiplication sign we are going to write int within brackets arr within square brackets i minus 64. all right let me tell you what we did here when i is 0 ar i will be a using this expression i am finding the ascii value of capital a and what is the ascii value of capital a it's 65 if i subtract the 64 from 65 i get 1 which is the column number of the column title a suppose we had b instead of this a then its ascii value would have come as 66 we subtract the 64 from it we get 2 which is the column number of the column title b that's it the logic to find out the column number belonging to a particular column title is complete all we now need to do is print the value of the result variable so we can do that easily using system.out.println within its brackets we are going to pass result and that's it the program is complete let's run the program and check the output all right you can see that the column number given by this program of the column title aaa is 703 this is something that we calculated during our intuition discussion phase let's find out the column number of the column title ap okay it should come out as 28 and there you go it has come out as 28 i know the column number of another column title which is set y it should come out as 701 and there you go the program correctly calculated it as 701 when i submitted this program on the lead quit website it got executed in one millisecond and proved to be 100 percent faster than all the online submissions made in java so with this we have come to the end of this video i hope you enjoyed learning this problem from joey's tech do let me know in the comment section if you have got any doubts related to this problem i'll see you in the next video of joystick goodbye and take very good care of yourself
|
Excel Sheet Column Number
|
excel-sheet-column-number
|
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
| null |
Math,String
|
Easy
|
168,2304
|
126 |
hi guys welcome to tech geek so today we are back with another daily challenge problem the problem for today is word ladder 2 so if you have done the word latter one you must be aware of how this question goes on so if not then give it a try this is elite good hard question he could have 126 basically it's quite hard too it involves lengthy code and an in-depth it involves lengthy code and an in-depth it involves lengthy code and an in-depth you can say in-depth understanding of you can say in-depth understanding of you can say in-depth understanding of graph somewhere because we'll be using graphs in this if you are new to this concept then obviously i'd suggest you all to go through bfs dfs and then come back with the solution let's see what the question says okay so the question says a transformation sequence from word that's a begin word to an n word using a dictionary word list is a sequence of words such that we have been given a transformation that means from a begin word we need to do the changes such that it makes an n word and those changes should be made depending on the words given in the word list we have been given few conditions a condition says every adjacent pair of words must differ by a single word let's say the first word was if abc then the second word could be somewhat like this like any one of them should change only making it a condition that the word that is changed should be a part of this word list okay now for every s i that means for every change in the word is in the word list that use the same thing this should belong to the word list note that begin word does not need to be in word list but n word should be and this s k that k number of changes after you get this n word this should be the end what you have to do is given two words begin word and end word and a dictionary return all shortest transformation sequences or an empty list if the sequence doesn't exist that's a possibility i've been given the first round of example you can see you have begin word hit you have an n word cog okay now you have to form begin word to end word given that you have this hot dot dog this is your word list now hit okay let me explain this here that's better begin word and we have n word and we have the word sorry begin word was hit end word was cog and the word list was hit hot dot dog and sorry it's not also okay let's take this now the word list contains hot dog dot lot log and call okay so if we don't go how the approach is whatever it is first let's see what would be the solution what could be the possible way we could move up with this question you have hit okay as said you can do changes to any one of the alphabet so keeping in mind that this should be a part of your given numbers or wordless sorry not numbers so if you see you could have three approaches practically if you have three approaches that means replacing it replacing i and replacing t but coming to a point you have to make sure that part also exists if we replace h we can have any word that's ending with i t but we don't have any word like this okay so first part cannot be done now replacing i that means we have a word that starts with h but ends with t so do we have such word yes so if we change this i we get hot coming to the third one if we have to replace t that means h i should be just starting do we have any possibility no we don't have so for this if we could say we just had one possibility right from hit we can just go up to hot now coming to hot again what could be the possibility hot first of all you know replacing edge you'll get dot okay this could be one now hot again if you can see you can also get lot another one could be lot also that's a possibility that you are getting you don't have hog something like that again h o something not like that h i know so this is the possibility that you get moving further with this if we have dot we can make it dog by replacing t or we can make it lot again lot could be made from this as well as this now this lot can be made into log again it could be made into hot 2 but we won't go back because we are just going in the same direction this lock can be made into cog one of them is test again you know this could also generate your solution because you have company now coming to this dog can directly be made into cob now see you got these many parts like to move ahead which is the shortest one let's see how many words are there one two three four five this one had five one two three four five this is also having five coming this one two three four five six so obviously this one we are not taking because we need the one that requires minimum transformations right so we'll have one answer as this and the second answer is this that's why you had in the first example you had two results are two returning lists right results were two lists i hope this is clear like what we are doing is we have to change for each and every word we need to see if it's there if not then how that goes on now let's see there could be one more possibility for the same question let's say our word list is modified and we don't have the word cog so what are we supposed to do we need to do all of this stuff or not so coming to a simple point as we said that s k that's the last point should be your n word so when you are making changes you often take care of that this formation is a part of word list so if end word is not in your word list that means your answer will always be a empty list so this is one of your important points that you must keep in mind okay now coming to a formation now as we approach this problem this is how we need to do okay the same thing we saw that's all is required for this question okay i'll just clear it again now how it is required from hit to cog you need to make you had hot dot dog log lord and these are the word list first create a graph now graph you can see how you can create you need to check with how many possibilities it could be like from hit we could make hot now i'm not just creating because that we have already shown but writing is somewhere like this okay this is the initial word this is the possibilities that could if we came from hot now from what where we could go we can go with dog sorry yeah we can go with dot and we can go with lot these were the two possibilities with dot we can go with dog or lot with naught we can go with as this was a different so with lot we can also go with dog dot if you see in the same possibility what could be the possible ways and we can go with law now which one is not traversed what is troubles daughters traverse lotus or dog is not so dog will take us to log sorry cog one of your solution is here or it will take us to lock again you have your dot is being traversed again you have your lot and log so if come to log will also take us to your cog so this is the way you will generate your adjacency list you can say this is one of your adjacency less like from where you could go to which solution which is your adjacent part in a graph build a graph using this and then once you have the graph find the shortest distance but coming to mind when you are doing this just make sure that it has only one difference that's a one letter difference that's the most important thing that you need to keep in mind find the shortest distance would be your optimal approach after this how i'll just uh show with this like we did same with it was hot it came hot with dot number three four one two three four and five it's not again taking the second one it will check now from what if you go to lot come to lot go to log then the slot sorry yeah the stock will go to cause this is also fine so the possibility will be it will check again and then the building of would this would be again the same thing as we know okay but now this is like you're going from top to bottom that means you're going from beginning word to end the word but while searching if you go through this you will have multiple options like here we have three options but you can have more than that what if to reduce we need to reduce these number of because these were small let's say we have abundant number of elements in your word list then obviously the searching criteria would increase so for that case what we could do is we could go in opposite direction that means search through n word and then form your beginning that's what you need to do while searching in your graph you have your graph going your opposite direction simple way just go in the opposite direction and you'll have i'll show you a code now this code will be quite lengthy so it could be confusing try to hold it on your own because there are multiple ways you can do this you can only do it with bfs only do it by dfs there are various things so that's basically i did try your approach build your graph find your shortest path search through end word too big excuse me and what to begin with okay so basically this is your fine ladders is basically your building of the graph once you are doing that using a linkless and hashtag you know we are forming like from head to heart then dot similarly by dog lord this is what you're creating links between them so that's what you need to do you'll create links you'll check for the n word you have your first word again generate it check if you have the beginning word there if begin word is there then obviously create a cue add these elements step by step try to add it like if there could be possibility for one change that's what you are doing checking for the one change if one change is there and if you actually get a change you found that increase the steps okay and if it's not found obviously the result is done your goal is untreated and then you go up for the dfs once you have created these letters you'll go with the dfs you'll be passing the end word you'll be passing the goal that's that particular word and the list that's formed now in dfs you have this that for every level you are searching for the element that is to be found you will search for it if level is zero obviously you'll reverse it that means you are doing an opposite fashion from inward to begin word why to avoid tla that's the biggest thing here we are actually searching for these strings in a fashion that we get the possibilities they are existing first of all and the difference is just one that's what the major thing we are going to do here so that's how we'll be completing it and once this is being done we could check this out we'll check for this yeah we'll check for this that there's a word that comes from end word to begin word we'll reverse it we'll search for it in a fashion such that again this goes in a recursive way of dfs and if not then we'll remove it okay coming to the third fact that once all of this is done we have a set of words okay this is the same part actually that's captured twice so that's what you will be doing in the same fashion now you will be checking for the first string if that's not equal to second string then obviously increment it if not then check and b you will check like if that exists and obviously return if it's equals to 1 if not then y d because it's checking if you're getting a particular string here okay this could be quite confusing if you look at these but according to me that's what you could go you have multiple options how to solve this you can go up with your solution just try it on your own build a graph search it out and then see how it works okay if there are any queries do let me know in the comment box thank you keep falling
|
Word Ladder II
|
word-ladder-ii
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`.
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\]
**Explanation:** There are 2 shortest transformation sequences:
"hit " -> "hot " -> "dot " -> "dog " -> "cog "
"hit " -> "hot " -> "lot " -> "log " -> "cog "
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** \[\]
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 5`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 500`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
* The **sum** of all shortest transformation sequences does not exceed `105`.
| null |
Hash Table,String,Backtracking,Breadth-First Search
|
Hard
|
127,2276
|
1,791 |
all right so this question is find center of the star gra so basically given to the array to find where's the center of the graph so look at the diagram so now you when we look at the diagram right the two is the center so we return two so how do we find it we look at the you know the interval you know piece by piece so to check this one inside you know the next interval uh in but in be honest we don't find it so we look get the other one two there's two inside the next interal yes two three right so we have what the two should be the common value the next one should be what the exactly the same thing right so two is the answer you want to return so how do we actually do this we can actually just you know compare the first value with the next one the next index zero and also the next in the one if they are the same right then we can return one the edes zero right and then if not then we just return what Ed is 0 one so which means it's going to be this one if this one does not the center then this has to be right so here we go so here's so return so that the edge is z equal to edges one Z or edges 0 equal to edges uh one if this is true then we'll return hes z lse PES 01 so this will be the solution to laying one lines i l oh miss spell okay should be okay so time and space are constant right so let's look at another approach so the next approach is put that into the hashmap and then we increment based on our what the frequency right so num I comma you know you increment your frequency and then once you Traverse every array you want to find out the so frequency is equal to what the length of the ages so for example one frequency is one right two frequency is still one at this point right two frequency at two right here three one right get R of this two four frequencies one two again so three then we Traverse the map to see does any value frequency edges. L then you will return the inser so hashmap integer map the new hashmap all right so um I'm going to Traverse the ages so math put edes a what Z m. get or default H just a 0 + one so what does default H just a 0 + one so what does default H just a 0 + one so what does this mean if there's value inside Ed is zero inside the map I get it I get that value and I increment by one and I put that into my map so this will be edges zero and then edges one is one so increment right so I can Traverse the what the key right so in key mea key set so if you know map. key is equal to ed. lens you want to return key which is going to be the center and then if not you know should be what anything negative one shouldn't be I'm going to say one all right NE one something like this so you'll definitely find it right all right time and space uh this is space all of n all of e represent L of Ages right you need to put every single value and then frequency inside the map this is all of e represent of you know the edges this is all of map so the map size is actually you know the worst case going to be all of e right you put every single element inside the map and all of the frequency are one and except you know someone has to be the what num length right so this will be the solution so you know straightforward enough and I'll see you next time bye
|
Find Center of Star Graph
|
richest-customer-wealth
|
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph.
|
Calculate the wealth of each customer Find the maximum element in array.
|
Array,Matrix
|
Easy
| null |
1,091 |
lead code practice so in this video there are two goals the first goal is to see how to solve this problem and the second goal is to see how you should behave in a real interview so let's get started remember in a real interview the first step is always try to understand the problem if there is anything unclear please bring up the question to the interviewer and also at the same time think about some match cases so let's read through this problem so shortest paths in binary matrix so in the n by n square grade each cell is either zero or one so zero means empty and one means blocked so clear paths from top left to the bottom right has lens k if and only if it is composed of cell ci to ck so adjacent c i and c i plus 1 are connected in directional so both that go no and uh so it's like sharing edge or corner so c1 is zero ck is at the bottom right part so um if ci is located in r and c then grade rc is equal to zero okay so let's take a look at the second example so the shortest path from the upper left corner to the bottom right corner is like this and for the question is make sure it's for sure that the grade is not gonna be empty uh and also each of the cell is zero or one so um the solution so the solution is a bfa solution you start from the upper left corner and you try to extend in the eight directions and at the same time you use a visited set to record this the set the cells you have already visited so that you don't need to revisit the cell over and over again so the runtime is going to be o and square and it is uh the length of the grade so it is in buy and gray so i've already done some coding work uh just to save you some time um and also um by the way i also have this uh this sheet to summarize different problems categorized into the different that categorized by data structure algorithm or the company etc and also i have the corresponding link to the youtube video i have so um if you have interest and you want to check some other problem feel free to go through the sheet and also have the system design videos like and also some behavior problems summarized so let's go back to this problem so first of all i defined a private class so the row index the column index and the length of the 2d grade so i override the write the hash code and equals because i'm going to put them into the hash set so uh let's take a look at the real code here so this is a real code um so this is the function i will need to uh i already implemented so i pass in the 2d grade this is the ash case if the upper left corner is already 1 which is a blocker i just simply return -1 just simply return -1 just simply return -1 and then um i get the length of the grade i initialize uh the queue and i put the upper left corner to the queue and initialize the distance as zero so distance is the final thing you want to return if uh the uh bottom right corner is achievable for us to go there so um this is the body of the bfs so every time for each layer i just plus the distance and that goes through other nodes uh in this layer i try to extend it from the current node to the eight directions and here if the node is already at the bottom right corner we just simply return the distance otherwise if at the end we jump out of swallow it which means we have already visited all the non-blocker all the non-blocker all the non-blocker uh cells and we haven't found the bottom right corner then it means the bottom right corner is unachievable so we are going to return minus one so for the extend function we pass in the queue we pass in the current node and we have the r let me pass in already visited nodes and also the grade so we will try to extend in eight directions but um there are some conditions so if the nodes are out of the range or if the node current if the node is a blocker then we are not going to extend to the new node other and also if the node has been visited before we're just going to skip it otherwise we put it into the visited and the queue so that's it for uh the implementation uh so take care about the correctness credibility and speed in the coding part and at the end you do some testing so if it is renewable platform feel free to use the platform to help you debug if it is not runnable you may need to explain the code manually and do some sending check uh explain how this gso code is gonna work so that's it for uh this video so if you like it please help subscribe this channel i'll see you next time thanks for watching
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
448 |
numbers disappeared in an array giving an array norms of n integers their nums i is in the range from 1 to n return an array of all the integers in the array from inclusive one to inclusive end that do not appear in the norms so basically it's a very easy question the question is saying okay this is the array that's given to you and uh it's has n integers so even though it has duplicates um we should consider the length of the array uh equal is the number of the elements that we should have and these duplicates indicates a number that is missing in the range so let's say if this is the array that we have okay it's going to be two four this array is going to have length four and when it has duplicates it means an element is missing here which is a missing element here is three so what we are going to do it's a very easy question we are going to use a for loop first let's keep the length of the array here nouns and then we can change that to a set because uh lookup in set is constant and then we are going to have a missing at least this is what we are going to return we are going to iterate over um the range of the array so for i in range n what we are going to do we're going to see if i is in the nums set and if it is not if not in i said we are going to add the missing dot append i and then we are going to return missing so basically what we are doing is if this is the case that we have here so let's say it's something like this and here so if this is something like this is not going to be a valid case because if we have seven here so the length of the array should be seven two so one two three four five six we need to add one more so now this is a valid uh test case so what we are going to do we are going to um have a for loop that starts from range zero but we should change this to one and we should update this to plus one so it starts from one because we have a constraint here that says the noms and first of all n is equal to the length of the array and second of all it's going to start from 1 to n so the end that we have is going to be 1 2 3 4 5 6 7 and what we are going to have it's going to be starting from 1. so that's why we have the range from one to n plus one and uh what is happening here it starts from index one and it says if it has a one in the set that i that we created here which is going to be something like this it's going to be one and two and five and four and seven and the order doesn't matter at all so what we're going to do we're going to see what is missing here we have one we have two we don't have three this in this hash set and then we check we have four we have five we don't have six in this hash set and we have seven and this is what we're going to return so let's have this example as the test case here and uh the time complexity for this is going to be linear because we iterate over the range of the array and the space complexity is linear as well because we are using this hash set so let's add these to our test case and uh when i run these we get accepted and here is the result that is correct thank you
|
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
|
1,295 |
in this video I'm going to discuss in the following rules and there is no such index in these necessary like minus one minus two which are invalid we do need to think about those so if you go to an example test case you can understand the problem more easily suppose one answer is 0 1 2 3 4 and the index that is go1 2 1 our output X would be 0 4 1 3 2 1 see start reversing from left to right you both enhance our index any first at index and you are getting 0 index so in your target array in the geotechnics insert the 0 here so our target is 0 then add index 1 in 70 100 so our is 0 1 and Indians to insert the - hello our a and Indians to insert the - hello our a and Indians to insert the - hello our a is 0 1 2 and index 2 again we have to in give we have to insert 3 value so our new array will be 0 1 3 to see index 2 for inserting 3 this to which was presented in this restricted to the right hand side this is what has to be done in the programming and that in this one we have to insert 4 so when is inserting at index for index 1 difference for the rest of the 1 3 2 is simply to the right hand side so output is 1 0 4 1 3 2 if you took the example to see non-sequel 2 1 2 3 4 0 example to see non-sequel 2 1 2 3 4 0 example to see non-sequel 2 1 2 3 4 0 and is equal to 0 1 2 3 to do so start reverse a from their pride in both the area that you need 0 1 has to ensure it having there's one who has to be inserted target any become one two I mean these two three has to be inserted target away is one two three and in this three four has to be inserted target is one two three four now it is mixed you know we are inserting defending 0 that means every pigeon we have to insert 0 so I'll put array is 0 1 2 3 4 see does it is case 3 nonstick l21 indexicality 0 still fill in the target array just until the mix we have to give 1 and that's all no other element to further constant is given as non start length indexed or length is ranging from one to hundred num straddling the equal to in destructive and numb so 5 that is particular element is ranging in the lamps are in NZ from 0 to 200 and if particular element in the index that is ranging from 0 to I try to think about an algorithm which can be used to solve this particular problem implement that check whether it is giving correct output or not if it is not even correct output nonito here I am explaining so see we have to insert in a particular position suppose already any element is present in that index they may have to sift so the easiest way to do these kind of inserting a particular element in a particular position is using array list so we will follow we will use array list to store in a particular in this and then we will create the output array using the array list that's what is written here cloud solution is our class name public it returned a is integer array 3 a target array this is our function name eat Aaron mom's hint array index to Erin arms and if this we are passing through our function clear target array then we are creating one catalyst to do this kind of insertion then we will traversing from left to right for int I 0 I less than monster length I plus 4 in title 3 y less than even text or length I plus also because mass and index are in same length what we have to do a dot and he'll diversify common answer 5 that is that in this we have to put that particular mom so fine now we are creating an output array of same line there's a forum list and then or as assembly this or num starting or ending story and then traverse is from beginning to the end of the array list put that element in the output array so for it I equal to 0 I less than bounce dot length I plus output a file if I to a dot K returns yeah that's all so here in solving this particular problem collection is helping us so if you are doing programming in Java then having a good clear concept in collection is very important and very helpful for placement process here you can see the hundred percent a vision a movie series also hundred percent efficient 32.2 MP at 8.2 hundred percent efficient 32.2 MP at 8.2 hundred percent efficient 32.2 MP at 8.2 MP so these type of problems try to cram is from late code will surely help you for placement preparation I am going to post same code in the comment section of my this video if you want you can check there thank you
|
Find Numbers with Even Number of Digits
|
minimum-garden-perimeter-to-collect-enough-apples
|
Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
**Example 2:**
**Input:** nums = \[555,901,482,1771\]
**Output:** 1
**Explanation:**
Only 1771 contains an even number of digits.
**Constraints:**
* `1 <= nums.length <= 500`
* `1 <= nums[i] <= 105`
|
Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected.
|
Math,Binary Search
|
Medium
| null |
72 |
hi guys welcome to the channel this is wagga we're going to do another liquid question and the question and question today is number 72 at the distance you're given two words you're supposed to convert word one into what two and the number of operations you can use is um the number of things you can do is insert a character delete a character and replace a character a g the word horse can be converted into the ros ross by deleting um replacing h with r and then replacing um removing the r in horse and then finally dropping the e so that you have ros ross right um okay repressing the yeah okay yeah that's how you can do it so you replace h with r remove the r and then remove the e right so basically that is the idea in such a situation we could use dynamic programming to solve this problem and that's what we're going to do we're going to dynamic programming is where you use um a small section of the problem to solve the grander problem right um you use a muscle of the problem to solve the mountain of the problem to find the pattern that we you will use to solve the mountain of the problem right so that's what we're going to do in this question many um dynamic programming questions we're going to use a 2d array to solve this question right solve this problem so the first thing we need to do is come here and we could create we could come here write down our word and um let's make this 150 right um because i'm going to create a 2d array so you could just use this um this what document right so the first word is going to be what one is going to be horse and we are trying to convert it into what two which is going to be ros this is the example from here right this is the example from just the first example so we're going to work it out on the word document and then um work out how to solve it on the right document then we use the logic we implement the logic and code right so how we do that is we come to insert get a table and we're going to get a table um the length is supposed to be equal to the number of letters in one word plus one and the row is the same plus the middle box or the about right so you could have one two three four five six uh plus one for the horse and then um one two three um plus one right seven by five table right so we have a seven by five table which you're going to use to replace the number um then the number of operations we need to convert one thing into the next thing right we will basically store the minimum number of edits to do on one substring to convert it into another one right and we'll start off with um an empty string right that's an empty string we come here we do the same we have an empty string and um we could spell out our word we could have horse ho h o r s and e like so and this one is going to be r o and s right so the first thing we need to ask ourselves um we're going to be asking ourselves the number minimum number of operations to convert one subset of a string into another one and so the first thing we do is we ask ourselves how many operations do we need to perform on this empty string to convert it into the empty string the answer is zero so we can write zero there how many operations do we need to convert this empty um ah this empty string into r we need one how many to convert it into arrow we need two how many to convert this into ros we need three right we do the same across right how many we need to convert it into h we need one h o two and this is going to be three and this is going to be four and this is going to be 5 right now the next thing how do we convert r into h right that's pretty straightforward um r into h we can use the operations remember there is um insert delete and replace right so we can just substitute or replace right so we can substitute so the number of operations is one right um how many to convert um into r into h o so we need two substitutions right so this could be um two how many to convert r into h o r now here's the difference right the letters are the same right so all we need to do is actually to do two operations we need to add h in sat what was the name replace no insert or is there an insert or something like that uh the exact name uh inside the character yes it's inside okay inside we need to insert two we just insert h and o right so because r is r right so the number of operations here is going to be two and h o r s e is going to be we need to insert the three letters so in this case we have three and here we have four right and we come to oh how do we convert r o into h o well the answer is no arrow into h we need to delete and exchange and swap or replace whatever it was two right how many to convert arrow into h we need one replacement right so we have one here arrow into um h o r we need two operations two here and um here we need three and here we need four right and ros into h um ros into h is we need three operations right out of us into h we need to delete two numbers and then uh swap one so that's three um ros into h o we probably need two right we need to replace one letter and delete one so this is going to be two and r o s into h o r we need two operations ros we just need to replace the r with the h and then replace the r with s right no we already have an r right so we need two operations it's ros into h o r right um we have an r and i know we need to hmm we need it's actually going to be two right two operations in this case right and then um h o r s e and um h o r s and um and arrow s we need two operations right and horse ross you need three operations right uh because how would we do that we would first three operations first um first we have the ors so we could have um we can't change the order so i think there's another thing there right and i think the answer is given here how would do that we would replace h with r and then we would remove the e so we have ros so there are three operations so that should be the output now we should figure out how we came across how we came up with um what is it how did we come up with this right if you pick a box can you calculate the number that is required on that box based on its position just based on its position so if you check you notice that um for any cell we have the value is going to be um we're going to check if the numbers are the same we are going to like if the numbers are the same like if we pick this r and r right if r and r is the same it's going to be the same as the number diagonal to it so if we come to r and r we find that the number here is two and the number here is two right if we come to s and s the number here is two and the number here is two if we come to o and o the number here is one and the number diagonal is one so if the numbers are the same you look at the number diagonal to it right and you just put a one there right the next thing we need to check if they're different what do we do like in this case how do we arrive at three uh what we do is we check the numbers around it to the left diagonal and up right we get the minimum and we add one right so if we pick this number here three we add we check two three four which is the minimum two plus one for the one extra uh operation is three right we come here it's going to be what's the minimum four three is the minimum therefore we add three plus one you get four right um here there is no here we don't have enough information because we just filled it out and here in the four we take three and we add one so basically for any box we want to look at what we need to do is we need to look at the number to the left diagonal and up and we add one if however they're the same just check that the number diagonally so basically that's how we would solve such a situation and now what we want to do is just put this all this information into code solve it and um we could come here and say edits and edits is just going to be um x for x in range of the length of what one length of word one plus one right like so and then uh for y in the range of the length of word two plus one like so um to explain this quickly what we're doing here is we're ensuring that um our rows initialize with the zero one two three basically we're doing this right we're making sure that our rows initialize with zero one two three until the length of uh the first word plus one to account for the empty string we added here so it's going to be zero one two three four five right so this is what this line does right so basically and we add the one for our empty string which we added right and um that's what the x for x does right for f for each uh number in the range to ladder one right um and then we do the same for our column right uh so for that we could just come in and say for i in range so that you can have the column range and this is going to start from 1 because the first one has been filled right and this is going to be the length of what two and what we want to add is plus one like so right and what we're going to do is we're just going to say edit i at position zero okay edits i at position 0 is going to be edits i minus 1 at position 0 plus 1 right so what we have done in this situation is that um we have gone down and we have set these numbers right 0 1 2 3 right so we say edits i at position zero is going to be um the edits of the previous number plus one right and we start off at the second one because the first one has been filled with zero right so we just take this number so that you can have zero it starts off and then it will be one and then two and then three like that right so we have sorted out the r2 um the base cases for the empty string right so basically that now um the next thing we need to do let's build out the rest of our table right and how we would do that is we could come here and say for i in the range and the range is going to be one to the length of what which what two plus one like so and then we have for the j loop for j in range and the range is going to be one into the length of what uh what one plus one like so right and um recall the reason we're adding one is because we shifted everything because of adding the empty string right um we check if what two is the same as um if the character is the same as the character that we're checking against basically we're checking whether r is equal to r in this case right so we say if what two at position i which in this case because of shifting okay here i'm supposed to type here i minus one is the same as what at position j but because of the shifting it's j minus one we just look at the diagonal value right and we just say edits or edits i j is going to be assigned to what was diagonally and for that it's just going to be i minus 1 into um i minus 1 and this is going to be j minus 1 like so right else in this case they're not the same right we get the minimum of the three right we just say edit of the number to the top to the left and to which is diagonally positioned right so it's edit i j and what we want to assign here is one plus the one operation plus the minimum and the minimum is going to be of added edit i minus 1 into j minus 1 comma and then we could just copy this to save time right copy this copy paste it's i minus one and then i into j minus one right and then after that it's going to be i minus 1 into j right so we get the minimum of um the value to uh the left the top and diagonal right so we get the minimum and then we add one to it and we assign it as a edits i minus j so another thing you could do is um we could make a correction here this is supposed to be word one and we're supposed to set that we're supposed to check the equality they are not assigned right so after all this is done what we need to do is just return and what we want to return is going to be edits and what we want to return is going to be the very last element of our 2d array like so and if we run our code it's accepted and if we submit it's accepted now the space complexity is going to be o of n by m where n is the value of what one and m is the value of word two because you create a 2d array with their lengths right and then we add one of course we can ignore the one and um the time complexity is going to be the same o of um of nm right it's going to be the same it's going to be o of nm for our i was just checking my submission um it's going to be o of n m for our time because we have to go through both arrays right so basically that right and remember it's not oven squared it's n and m because um as you saw horse and ross have different lengths to them so basically that is we could however use memorization to make it more efficient to make the answer more efficient right um to make the space complexity rather more efficient but i won't have a look at that i think this um this method is uh suitable and it's the one that i understand the most right i understand this straight out because if you draw it out on the 2d array this one makes a lot more sense right so thank you for watching subscribe to the channel and i'll see you in the next video
|
Edit Distance
|
edit-distance
|
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
161,583,712,1105,2311
|
1,838 |
Hello everyone welcome to my channel code sir with mike so today we are going to do video number 13 of our playlist of sliding window mechanism ok for now forget that this is the problem of sliding window we will figure out ourselves how this The problem of sliding window is ok, it is medium marked but it is called multiple approach. The name of the question is Frequency of the most frequency of an element is the number of times it occurs in n. Hey, this is what you know, you are given an integer. Hey names. One is named nums and given an integer named k. Okay, in one operation you can choose any index of numbers. Okay, in one operation what can you do by picking any integer of numbers and in any index. You can pick and increment that number by one, okay, that will be one operation, so return the maximum possible frequency of an element, you have to tell what is the maximum frequency of an element, after performing at most K operations, okay, now let's see. What you are trying to say will become clear from the example. Look here, pay attention that it has been given that it means you can do maximum five operations only. Maximum is fine and if you raise any index in one operation then you can do it. You can increase, okay, you cannot decrease by one, so let's see for example, if I increase one once, then one will become two, okay, how many operations are done, four operations are all left, if I increase it again, then this will be Now three operations are left. Once again if we increase it again, it will become four. Okay, now only two operations are left. Okay, now look, this is my four. Okay, now look at two. If you increase it once, it will become two. 3 is one more operation left, increase it once more and become 2, then look at this also, it has become 4, so look, this is the maximum frequency, I have got how many three, four, how many times, it has come three times, okay? So let's look at the maximum number of operations we did five operations. Okay, so if we assume that there are more solutions to this, let's assume that what would you have done, you would have increased one to two. One operation is done, okay, you are saying, let's go, okay, we have got this is our answer, two, whatever it is, see how many times it has come twice, but look at the frequency, maximum frequency, you are seeing two, in this hey, of some element twice. Here is this element, it has come twice, but look, the better answer is three, we have a number one, you can bring such a thing, which has come three times, I am fine, who is that number, that is number four. Because look, by increasing it to four, it took three operations, it is okay, it took three operations, so three operations were used, so save the operation, if you increased it by two, then it also made four, so the operations have become zero, see. These are four, these are four. The frequency is three. This is the maximum frequency that could be found. Okay, this is what I have asked you, what is the maximum possible frequency of any element. After performing at most of the operations, it is clear till now, so see what I am talking about today. I will tell you the solution, it is very informative, you will get to learn a lot of things, it will be a complete journey, in a way, I will tell you my thought process from the very beginning, how I started thinking about it, see, first of all, I will tell you honestly that I have not heard anything about sliding windows. I didn't think that it could be made with a sliding window. First of all, it's okay, so I will not tell you about the sliding window first, but first I will tell you what came to my mind. Okay, look, before starting everything, there is a very hidden thing. Another very important thing, I would like to tell you about this question. Look, when I had given the example here, pay attention here, what I had done, I had increased one to four. Look, four is right, four is already available in my mind. Okay, by increasing two, I made four, look, four is available in my mind, okay, so a question comes on this in the interview, maybe ask this in the interview, he will say that friend, you are already present in these names, let's accept it. There is four present in these numbers, then why did you make one equal to four and why did you make two equal to four? Can there be any such number which I can make equal to one and two which is not present in it? Ho for example, the interviewer will say, for example, th, you can make this one equal to three, this two can also be made equal to th, why can't you increase it, if you apply two operations on it will become two, then if you apply one more operation, It will become three, this is fine, so if we make this also equal to three and if we increment two by one, then this will also become equal to three. Four cannot become three because four is a big number. Right, four is a big number, right, do not decrement it. In the question, only increment has been talked about. Okay, so what is the problem in this, why did we not think that we can also bring a number which is not present in these numbers, so look beyond that, understand well what should be your answer. Look, it takes two operations to move one to three. To move one to three, we took one operation. Ok, how many operations are required in total. Three operations are required. Now look, assuming that you would have chosen two instead of three, 1 4 2, it is ok. Brother, if you want to make two not equal to three, then look, if you make one equal to two, then one operation will be required, and to make two equal to two, zero operation will be required. Look, how many operations were required this time only one operation is required, okay? Look, it is possible that if you are saying that put an element which is not in this number, then let's assume that let's take f, 1 4 2. If we have to make all of them equal to f, then see how much it will be. This will take four operations, this will take one operation, this will take three operations, a total of eight operations are required, okay, because look what happened to the element, which element was already four. Do you remember what was our optimal answer? We had made all of them equal to four. So look, this time the poor four has to move once to bring the five and look in this case, in this the poor four cannot even reach the two, here also the poor four cannot reach the two because We cannot decrement the value, that is why we know the best answer every time, when we increase the value of something and make it equal to an element which is already present in this name. No matter how much you try, you You would like to equal a number which is not present in these names. Your operation will never be less. Operation will always be more than yours. Look here, there were three operations. Here, one operation is required. Here, eight operations are required. Okay, when one operation is required here, then Also see, only this could be equal to two and look at the frequency equal to two, only two came whereas our best answer was three. Okay, so you know what was my main motive of explaining this, I am trying to tell you that when you Let us assume that the number is a b c. Let us assume that you want to make any number equal to any number. Like you are seeing here, I have made all of them equal to four, then four exists in numbers. Look, four is already in numbers. Okay, so what I am saying is that you can call it a target, the target for which you have made the rest of the numbers equal, that target should be present in these numbers, otherwise the optimal answer will not come. It is okay with you, so you do not have to take that tension that the rest of the numbers will be equal to the target. Can there be any other numbers ? Is it our optimal answer that it can ? Is it our optimal answer that it can ? Is it our optimal answer that it can never be? So one of our tensions got resolved that brother, I have to do whatever we have to do with the help of these numbers. This was a very important thing but very hidden. Nothing is clear from here, but I have told you here, okay, this thing is clear, now let's move ahead, what was my thought process, how we solved it, so see, I just told you for a while. First of all, it was made clear that when we increase a number, we will equalize it with a number which will already be present in my numbers, okay, which will be already present in the numbers, like look here, we had equalized these two by four. So what was equal to four, look, four is present in my names, so I call four as target, okay whose equal I want to do, okay, so friend, look at one thing, let's assume that you want, let's assume that you have given a The target was made that you want to make all the numbers equal to eight. Okay, let's look at all the numbers. How many operations will it take to reach one to 8? Seven operations will it take, brother, we don't even have that much. Okay, so let's go, this is a mess. It's done but pay attention to this, will it ever be equal to T? It won't be possible right because it's bigger. Obviously, A should always ask whom can you be mine or not? Always know who will ask who is smaller than this. It can be equal to t because it can be incremented and it can reach t. Okay, so here I thought, man, what does it mean that I sort it, great and sort it. Benefit of Just told you that any number will ask that you can be equal to me, will you increment and ask your smaller number then I will sort it 1 4 8 13 k = 5 ok now pay attention 8 13 k = 5 ok now pay attention 8 13 k = 5 ok now pay attention look 4 rest He can ask one and only one can ask that brother, can you be equal to me? Will one say yes, I can be incremented, it will depend on k, but I can definitely be incremented because in the question, increment. There is an option to decrement, there is no option to decrement, similarly, look at, it can ask for four and can ask for one, they can be incremented. Okay, look from three, it can ask for increment from 8 and then one. It is possible but one can never ask 4, 8 or 13 whether you can be equal to four or not because these people cannot be equal to four, they have to decrement, okay that's why see that is the prime reason for I am fine, I don't know whether Leetcode has explained so clearly why it was sorted, it is fine, but this was my approach as to why sorting was necessary, it is fine for me, I am telling you my thought process, okay One problem has been solved by sorting. Now let's see how to solve the problem by sorting. Now look very carefully, pay attention here. Look, index number 0, index one, index two, index three. Now look, I just taught you this a little while ago. That each number can ask its smaller number, for example, let's assume it is 8, okay, so here on the left side, it will ask the people that friend, can you people be equal to me or not, okay, then one thing. Tell me, what is T? If he asks the forest, then the forest is saying that brother, to be equal to you, I will need seven increments, seven operations will have to be done, but the value of our k is f, so 8, he will not ask this at all, right, this is discard. Done, 8 will ask 4, brother, if you tell me, then he will say four, brother, it will take four operations to become a because 8 my 4 is 4, so four increments will be required, so the value of k is f, meaning four and eight, it can become a window, both. Eight will become eight, look at the frequency, it has come to two, okay, the frequency of A has come to two, okay, so you noticed, here I am also trying to explain the code to you, let's assume that my I is here, so I have discarded which one on the left side. Did you discard that guy who is taking too many operations? If you see that he is taking more operations than this then it is an obvious thing, you come and accept it, now you are on I, you will go first, start from zero right here, start from here till how far. You will go till the time you come, you will go one by one, asking everyone, brother, if I am the target, if the person who has come is the target, then how much operation will it cost you? One is saying, brother, if I will have to undergo seven, then I will discard you, then how much will it cost you, okay? Similarly, if you are asking everyone one by one, then see, it will go off, why not? Because look, I am here, then I will go and ask everyone, then when I will come here, is it okay, then I will go and ask everyone, then it will go off, then friend. Let me tell you one thing, when we have done the sorting, then take advantage of binary search and find it using binary search. If we assume that your index is here, then apply binary search in so many parts and find out which is that element. You will get equal to T in so many operations, okay, so pay attention to one thing, one very important thing here you will learn, see, if we accept that this is eight, it is okay, this is four, my I is here, now it is four. He said, brother four, I am 8, I can become a, I will need four operations, okay four, how many operations will it take, four, it means it can become a, so if it becomes a, okay, then look at us, it will look something like this, right? 8 1 So pay attention to this part, see how much is the total sum of both of them, 16 and how much was the first part of 8 + 12. See, if it becomes equal to eight, 8 + 12. See, if it becomes equal to eight, 8 + 12. See, if it becomes equal to eight, then what is the size of this window? It is two, right, and all of them are eight. So the obvious thing is 8 * 2 that is 16, its sum came and its is 8 * 2 that is 16, its sum came and its is 8 * 2 that is 16, its sum came and its sum was 4 p 8 12, see how much difference happened, then 16 - 12 is a difference of four, what does it then 16 - 12 is a difference of four, what does it then 16 - 12 is a difference of four, what does it mean, definitely four operations must have been done, four increments must have happened or else. Four operations would have been involved, so you can also calculate how many operations would have taken, okay now see what is its advantage, I will tell you its advantage, if we assume that I is here, okay, then I applied binary search here because of the value. Mid mine comes here index number because of the value at zero that mid mine is here so first of all I will see that from this mid to index number i is okay what was my target if from this mid to index number i Till now, if I sum all of them, then it is okay, how many operations will be required, so I told you a trick to find the operation, find the sum of the whole, see how many elements are there i - mid + 1, there are so many elements are there i - mid + 1, there are so many elements are there i - mid + 1, there are so many elements, one or two in the middle, 3 2 - 0 + 1 total one or two in the middle, 3 2 - 0 + 1 total one or two in the middle, 3 2 - 0 + 1 total is three elements, if you make all three equal to eight then it will become 3 * 8 that is 24 right then it will become 3 * 8 that is 24 right then it will become 3 * 8 that is 24 right and what was the old sum 1 + 4 + 8 was 13 and what was the old sum 1 + 4 + 8 was 13 and what was the old sum 1 + 4 + 8 was 13 right then the sum of this window is 24 and the current The original even number was 13. Okay, so how many operations are being taken. Look, it is 24 - 13, that is, operations are being taken. Look, it is 24 - 13, that is, operations are being taken. Look, it is 24 - 13, that is, 11. Now I don't have that many operations. I have only five. What does it mean that it is so big, I cannot take the window mid. Now look at the binary with you must be seeing, so what I did is I sent the mid here, it is clear till here, meaning mid is not mid, meaning here it was the right pointer to J, I sent it here, okay now again. This time we will take out the middle, assuming that the middle is here, okay, now let's do it again. Look, if this time I have taken the mid here, then I will again make the same assumption that if I have taken all the elements from this h to a. Let's make it equal to this target i.e. 8. Let's make it equal to this target i.e. 8. Let's make it equal to this target i.e. 8. Okay, so let's see how even it will be. First, let's see how many elements are there in this window. That's how many elements are there in total. It is true that there are two elements, four and eight. If both are made equal to eight, then it will be 2 * 8, that is, equal to eight, then it will be 2 * 8, that is, equal to eight, then it will be 2 * 8, that is, 16. What is the total sum of these and the older sum? 4 × 8, that is, 12, right. If it was 12, 4 × 8, that is, 12, right. If it was 12, 4 × 8, that is, 12, right. If it was 12, then how many operations will be required, now it will become 16, if you make four into eight, then the even will become 16, right, 8 and 8 are 16 and the old even was 48 p 12, so 16 is 12, that is, four operations will be required and this It comes inside our 'K', so many operations could have been done. In comes inside our 'K', so many operations could have been done. In comes inside our 'K', so many operations could have been done. In doing five and four operations, these four, see, 8 will become 8. Okay, so what does it mean that these four are less than equal to two, see, that means it is valid. It is clear till now, okay, now let's understand the same thing with another example. Okay, look at this example, some more things will be clear from here. 0 I have written the weight index, because of the value, now I want this to be my target index. Okay, this is my target, I want this is the target index, I want all the elements to be equal to four, so we will do the same thing again, we will apply binary search here. Okay, so you can apply binary search till here, or it will also be applied till four. You can do it, there is no problem, remember in binary search, there used to be a left pointer and a right pointer, okay, so I put the left pointer here, I put the right pointer from here, there is no problem, it is okay. So now let's do binary search, see what mid will come out, this mid will come out, I am fine, now look carefully, now my mid has come out, so what I said, if I make all the elements from mid to target index equal to this four. So how many elements are there, let's see the target index minus mid pv total, how many elements are there 2 - 1 + 1 That is two pv total, how many elements are there 2 - 1 + 1 That is two pv total, how many elements are there 2 - 1 + 1 That is two total, two elements are one and these two, if all are made equal to four then 4 * how many elements are two The elements are 4 * how many elements are two The elements are 4 * how many elements are two The elements are 4 * 2, 8 will be even, how will it be 4+ 4, ok * 2, 8 will be even, how will it be 4+ 4, ok * 2, 8 will be even, how will it be 4+ 4, ok but what is the current sum, look at me, the current sum which is the sum of the window, my 2 is 4, that is 6, so how many operations will be required, 8 - 6, that 6, so how many operations will be required, 8 - 6, that 6, so how many operations will be required, 8 - 6, that is. Two operations must have been done, which is obvious, which is smaller than my five. Okay, so let's see how much frequency will come. If both become four, then the frequency will come to two, which was the size of my window. Okay, the frequency I have got now is two. But since I have got two frequencies, remember, in the beginning, L was here, R was here, MIDI A had come out, now when I have got a valid answer, I have noted down the answer, but I would like to get a bigger answer, so I will note down r. Mid mid means I will try to move r more to the left. Okay, so I took r to mid. Okay, remember and if it was invalid, we used to shift it to the right. This is what happened in binary search, either you will go right or mid. Either you will go left, okay here it is valid, so I am trying to increase r further, I took r to the left, this time look at me, this is what will come, ok, this is where mid comes, so let's find out again how many elements will be there in this mid. From this mid to the entire target index, if I make all the elements equal to four, how many elements will there be? Target index minus mid 1 2 - 0 + 1 Target index minus mid 1 2 - 0 + 1 Target index minus mid 1 2 - 0 + 1 That is three elements, all three elements will be four. If they become equal to then 4 * 3 that is 12 will be the 4 * 3 that is 12 will be the 4 * 3 that is 12 will be the total sum i.e. all three elements of the three are total sum i.e. all three elements of the three are total sum i.e. all three elements of the three are four ok and but what is the current sum see so 1 2 + 4 1 2 + 4 1 2 + 4 is 7 ok 1 + 2 4 that is 7 How many operations will it take to 1 + 2 4 that is 7 How many operations will it take to 1 + 2 4 that is 7 How many operations will it take to see it is 12 my 7 that is pa which is valid na see our operations are less than equal to two this means these three can be reduced to four so the size of the window was three meaning all three of my three are my four. I have got one better frequency, I have updated the frequency so that I can get three frequencies, if I make all four, it is clear till now, then you have come to know the main issue of binary search, what you have to do, right, see here. But we will keep updating the frequency and we will get the best frequency but this time remember what was the target index I tried to make everyone equal to four, similarly again we will do the same if I make everyone equal to two, okay If so, what will be the answer? If I make everyone equal to one, what will be the answer? If I try them all one by one, I will try them by making target index. Ok, it is clear that if I make everyone equal to one, then what will be the answer? Everyone If I make all equal to two, then what will be the answer? If I make all equal to four, then what will be the answer? It is ok and the task of finding was solved by my binary search because already mine was sorted and binary search is a very good method, we used it here. But okay, so now a lot of things must have been clear to you, okay now see how the code will be, which is simple story, how to write story to code, what did I tell you that first of all I had told you that brother, sorting has to be done. Let's do it. Secondly, I had said that I will try to target everyone one by one, sorted it, Na for int a e 0 a lesson a i ps plus, it is ok and I will write the binary search somewhere separately, binary search is ok there. But I will send that which is the target index, that is i, that is, whatever element is in i, I want to make all the elements on the left side equal to this element, okay, whatever is on this index, I send the names and what else. Let's send a cake. Even if it is clear, remember when it used to be like it was here, I would have accepted it. When it had happened, I would have looked at so many people, wouldn't I have checked so many people, because yes, if there are 13, then it would be equal to Aa. Sometimes. It will not be possible, then why will you look at the right side, okay, that is, my binary search will be mine, from where will I run in the binary search, L, mine will start from zero and the right mine will be on this I, what is my target index? The target index is ok, what I have passed is ok, it is clear and I will keep updating the frequency that I will get from binary search. The frequency is equal to two will be found from binary search and I will keep updating the result. Maximum of I will return the result in comma frequency and last. It is clear till now let's come to the binary search. The binary search I have to write is here. I am writing it here. It is fine. Binary search is fine. I had passed the index so that all the numbers are included in this. If the elements in the target index are made equal to them, then what is the best frequency I can get? I have to find out that I had passed K and had passed numbers till now it is clear. Now see, pay attention. There is an L in binary search, remember zero. We will start from l, here I told you here that if this is my aa, then we will check so many from i to equal and from aa to less because only those people can be increments. Hey, it is sorted, right, decrement. So we ca n't do l = 0 and r is n't do l = 0 and r is n't do l = 0 and r is kept till the target index only. Target index is ok till now it is cleared. Now remember how binary search used to be done while l i le e r is ok let's find out the mid. How to find the mid. l P-A-A-B-A-B-T-Okay, now look, pay find the mid. l P-A-A-B-A-B-T-Okay, now look, pay find the mid. l P-A-A-B-A-B-T-Okay, now look, pay attention that my mid has come, what did I tell you that my mid has come, let's assume that my mid has come, then all the elements from this mid till the target index will be included. If the target index If we make it equal to the element in i, that is, make this also eight, then what will happen if we make this also eight? If we did not want to do the same, then first let us see how many elements are there from the target index to this mid index and calculate the count. Target index minus mid psv There are so many elements right from target index to mid and if I make all of them equal to the element in the target index, then what will be the sum, then I write 'Y' of that window I write 'Y' of that window I write 'Y' of that window which will be the sum, how much will be the number of elements. What is the count in which all have been made equal? Names of which target index, if it is made equal to the element of mine, then this will be my window sum, right, but which will be my current sum, which is the original sum, instead of saying current, I would have written the original sum. What will be the original sum? Remember, the sum of all the elements from mid to target index is fine, so here you will have to write a separate for loop to do the sum so that you can get the original sum of all the elements from mid to target index. So that you can calculate it, I am saying that why would you do the for loop here again and again? Separately, we have already pre-computed the Separately, we have already pre-computed the Separately, we have already pre-computed the prefix sum so that you can calculate the sum from any index to any index in no time. I will show you that too. I will give but here you should know that what we are doing is finding the sum. Okay, after that, how much operations will be required, brother, the window sum which I have calculated minus the original sum, so many operations will be required if this operation is done. Which I think is fine, if it is greater than k, that means it is an obvious thing, not possible, okay, and if it is not possible, then it is an obvious thing, what will we have to do, L and we will have to make the window smaller, then L will be made mid plus and I will move it, okay and if it is not so, that is, it is possible, then first of all, I will not store in the result which index was the mid or all the elements from this mid to the target index. If I make it equal to the element, then the operations are being done with these, so I store the index, it is the mid index, that is ok, the mid index is gone, but I had said that I will also move r to mid-1. I had said that I will also move r to mid-1. I had said that I will also move r to mid-1. I will try to get a bigger answer which I taught you in this example, remember here when mid came, I got a valid answer but still I made r equal to mid-1 so that I made r equal to mid-1 so that I made r equal to mid-1 so that I can get a bigger window, okay So look, here I have also taken r in else to mid-1. here I have also taken r in else to mid-1. here I have also taken r in else to mid-1. Okay, as soon as my binary search is over, I will have found the best mid index. Okay brother, whatever this mid index is, I will have it from there till the target index. Okay, that would be my best that all the elements will be equal to the element with target index, then what will be its length. Look, the length will be equal to the frequency, which will be the target index minus the mid index, which will be the best mid index, I had stored it in the result minus the result, this much The number of elements in the window is clear, so it was the work of binary truth that it will return the frequency, I am fine, you should understand this thing very well, that is why I have written two examples and you should also do the dry run. Okay, now look at the point, I had taught you how to find the sum. Here, do not find the original sum by doing the for loop again and again. We need a method which can find the sum in my OFV and give it between any two indexes. Okay, so let me show you an example for that and many people will already know that this prefix comes from 'are', because of the names, that this prefix comes from 'are', because of the names, that this prefix comes from 'are', because of the names, mine was something like this: 1 3 7 9 mine was something like this: 1 3 7 9 mine was something like this: 1 3 7 9 10 12 Okay, let's keep the prefix as follows. Take out the sum Prefix Hey Prefix Sum Hey 1 P 3 4 P 7 11 P 9 20 P 10 Okay if someone asks you index number 01 23 4 0123 4 If someone asks you brother index number from one to 3 Tell me the sum meaning, how much will be 3 p 7 p 9. Look, 3 p 7 p 10 becomes 10 p 9, it becomes 19. But see from the prefix sum, you will be able to find it directly. See how in which indexes you were asked the index number. One ID So let's see what comes, meaning what are you doing? Prefix sum i If it is even, then it is 20. Okay, 20 has been written minus the prefix till the index one, which is even. This is four, I have made it four. Okay, it has come to 16. But look, pay attention. The prefix till the index th is even. What does it mean? Do you know what happened that he added so much? The sum has been calculated and given, that is 20, is n't it, and the prefix sum up to the index number one means that the sum has been calculated to this much. If we subtracted these two, then whose sum would have come out. Look, seven and no, only the sum would have come out. 79 16 Look, it is 16 but what happens in this is that this one is missed or index one is missed so here we will add again plus numbers of which index number one e one and okay so 16 + 3 that index number one e one and okay so 16 + 3 that index number one e one and okay so 16 + 3 that This is 19, many people would know this and so what will we do here, see, I erase this and write, if we want to find the sum from mid to target index, then whatever prefix is mine, it is a target then whatever prefix is mine, it is a target then whatever prefix is mine, it is a target index minus prefix a mid so The sum up to this much has been calculated but what do we have to do with plus? Remember the numbers of mid. We need the sum from mid till the target index. Okay, so I have calculated the sum up to this much and if I have done minus then I have got the sum up to this much. If the mid is left then You will have to add the middle, so see the plus numbers of mid, here I did the same, I added the numbers of mid, this was a very basic thing, but I told in detail so that you can revise once it is okay, then see we have I have finished the entire code here and we will remove this prefix, there is no tension in the beginning itself and here we will pass it in binary search, it is okay, prefix, it is okay, we have built our solution very well. I also explained to you why to sort, I thought okay, after that I tried all of them one by one to see if all the elements are equal to this and this, then how much operation will be required. When this and this happens, then all the elements will be the element with index number one. What will be the frequency when it becomes equal to And so on, started finding all the frequencies and how to find the frequency by using binary search because it was sorted. Right, then what will be its time complexity. Look here. It looks off, sorry. Here we have written for loop, here it is n and on the other side binary search is taking log a, so n takes a time to complete. Have we used binary search? After that I told you that we will find out the prefix sum, its size will also be n and the zero element of prefix sum will be equal to the zero element of numbers because there are no elements before it and yes we are in this. If you are finding the sum, then make it long by making it long otherwise it goes out of bounds, such a big value comes, okay so this is done, now let's start filling the prefix sum i = 1 aa < n aa p prefix i = 1 aa < n aa p prefix i = 1 aa < n aa p prefix sum off Aa will be equal to prefix sum of aa - 1 plus whatever is there in the numbers. You will aa - 1 plus whatever is there in the numbers. You will aa - 1 plus whatever is there in the numbers. You will know how to calculate prefix sum. Now let's start. Result equal to 0 taken for int aa = 0 aa taken aa equal to 0 taken for int aa = 0 aa taken aa equal to 0 taken for int aa = 0 aa taken aa plus to know. What am I doing here? Instead of coming here, I write the target index, brother, if I make all the elements equal to this, then what will be the frequency of the target index? Is it possible or not? The result is equal to max, sorry. Maximum of result comma which will come from my binary search I write binary search, here and there I will pass the target index, I will pass the numbers and I will pass the prefix sum. Okay and return the result in the last. Now let's come to our binary. OK in search int binary search S capitalize it OK what are we passing here first of all brother target index what is this int target index I would like to make all equal to the element with this index int And what is vector of int and numbers and vector of lang was our prefix sum okay now let's see first of all let's take out the target element what will be the target element in numbers which is present in the target index okay this will be my target element Now remember in binary search, int was a left pointer, we will start it from zero, either I took it as I had explained, either we take it as I or we take it as L, okay and remember the right pointer was from the target index. Let's just keep it till it is clear, after that see what we have to get here, we have to get the result or else I will write it, we will get the best index, okay, now we will keep it equal to the target index, okay, now see while. = r simple binary search I while. = r simple binary search I while. = r simple binary search I am writing int mud = l + r - l / 2 ok now am writing int mud = l + r - l / 2 ok now am writing int mud = l + r - l / 2 ok now look pay attention here first of all let's count how many elements are there from this mid till target index ok target index minus mid pv so many There are elements in between, if I make all the elements equal to this target element, then what will happen, window sum will be equal to, what will be the count into whatever the target element is, it is clear here also, I write long this much count. Is the window sum found? Okay, if I make all the elements from the target index to the middle equal to the target, then how will my current sum be found? It can be easily found and see the current sum. I have to find between whom and what. Remember, we have to calculate the sum from mid to target index. We have to see what was the original sum of the current one, so I had said prefix sum, that is why we had calculated prefix sum of target index minus prefix sum of mid plus sum of mid because it gets excluded. In prefix sum, I had shown you how many operations will be required to do this, my window will become sum and my current sum is the original sum, I have minus it. If the number of operations turns out to be greater than k, then brother, it is not possible to have such a big window. It is not possible to make l equal to the target element. We cannot do so many operations. Okay, so it is obvious that I would like to make l smaller. I make l mid + 1. I am making the would like to make l smaller. I make l mid + 1. I am making the would like to make l smaller. I make l mid + 1. I am making the window smaller and if it is not so, then in the result No result, best index, whatever is the best index, I store it in the middle, okay, and I am moving J to the left, why in the hope of getting a bigger window, I am okay, and lastly, since I have got the best index. If it is the middle one, then how many elements can come from the middle to the target index. Let's calculate the frequency. Target underscore index minus best index. If I can make so many elements equal to the target index, then the frequency will be as many elements as there will be in the window. Okay, let's run and see, hopefully fully, we should be able to pass all these cases. Let's see C here, not J, but R here. Hope fully, we have not made any mistake anywhere else and I hope it would be clear to you. Let's see by submitting in detail. Should we be able to pass all the disease cases? This is a very good question. After this, now we come to the approach of our sliding window. Okay, so look, now we come to our slide window. The biggest problem I had was that how on earth can someone If the identification is fine, then you used to look for the best candidate on the left side, let us assume that the best candidate was this. Okay, so if we make all the elements in this entire A window equal to 13, then it is okay, then 13 * if we make all the elements in this entire A window equal to 13, then it is okay, then 13 * if we make all the elements in this entire A window equal to 13, then it is okay, then 13 * how many total three elements are there? 3 39 Okay and whatever was the original sum 13 14 8 22 We knew the operation of subtracting from the original, so we used to find this middle from binary search, but look what we are doing ultimately, we mean window only. It just means, okay, so why not a window? If we are talking about a window, then why won't a sliding window work? It will definitely work. And look, literally, when I realized that we are actually looking for a window in binary search too. Look, by shifting the middle here and there, you are shifting the middle here and there, then you are removing only one window, see, the size of the window was this, there were so many elements in that window, so friend, that can be made even with a sliding window, see how. It will be made very easily. Okay, let's take the same example. We had taken this example earlier also. Look what happens in a sliding window. A window has a left side and a right side. In the beginning, both the left and right sides are at the same place. Are right then gradually it increases R increases If that window is right then keep making the window bigger, if not right then keep making the window smaller. By shifting L to the right, if it is ok then a little bit. Let's take an instance, let's say this is l here and this r here, okay so now I have this window, okay find the sum of this window, what will be the original sum 1 + 8 that is what will be the original sum 1 + 8 that is what will be the original sum 1 + 8 that is 9 and if all the elements in this window If I make it equal to at, how much will it be? See, how much will be the window sum? 8 * The See, how much will be the window sum? 8 * The See, how much will be the window sum? 8 * The size of the window is r - l + 1 i.e. 8 size of the window is r - l + 1 i.e. 8 size of the window is r - l + 1 i.e. 8 * 16 will become 16 - 9 will become 7 i.e. the * 16 will become 16 - 9 will become 7 i.e. the * 16 will become 16 - 9 will become 7 i.e. the difference is seven. The original and the window sum are fine, but we have only five operations, so obviously this window is not correct, right, then what does it mean, we have minimized the window, brought l here, okay, now let's see what is the original sum, eight. It will remain eight, okay, and what is the window sum, look at the original sum, the window sum is eight, what are you trying to say, eight of eight will remain, so this eight of eight will remain, okay, look, what is the difference, see, there is a difference, cry both of you. And my operation in between is five, so it means it is valid, so it is obvious, what will we do, we will try to enlarge the window, again we are enlarging the window, okay, now look, pay attention, how many elements are there, two, these two elements. Right, what is the original sum? 8 + 13 is ok and make what is the original sum? 8 + 13 is ok and make what is the original sum? 8 + 13 is ok and make all the elements in all the windows equal to this. The target this time is 13, ok which is on the right pointer so 13 * 13 is 13 which is on the right pointer so 13 * 13 is 13 which is on the right pointer so 13 * 13 is 13 no sorry 13 + 13 that is 26. Okay, no sorry 13 + 13 that is 26. Okay, no sorry 13 + 13 that is 26. Okay, so 26 is 13 and how much has it become, 21 has become 26 - 21 5, it 21 has become 26 - 21 5, it 21 has become 26 - 21 5, it will take so many operations to convert all of them into 13. And look, here I have the value F, it will take five operations and the value F is also one valid. What is the size of the window? It is two, that is, two frequencies will come. Let us make this also 13. And if we make this also 13, then I have stored the maximum frequency. How much is two? Okay, so if this also turns out to be valid, then we will have to enlarge the window. I will try again, I took aa here, now I am saying that if I make all equal to four, then let's see what answer will come. Okay, why are you making the window bigger because look, when I came here, the valid answer was made all equal to 13. Okay, when we made all equal to 13, it was within k = 5. Okay, when we made all equal to 13, it was within k = 5. Okay, when we made all equal to 13, it was within k = 5. Okay, now that it is valid, we used to enlarge the window. Remember, okay, we are increasing the window, so what is the original sum? Look, 13 8 21 + 4 25. Now what is the original sum? Look, 13 8 21 + 4 25. Now what is the original sum? Look, 13 8 21 + 4 25. Now what will be the window sum, if all are to be equal to four then 4 * 3 12 Okay then 12 8 then 4 * 3 12 Okay then 12 8 then 4 * 3 12 Okay then 12 8 5 13 How much difference will come out, 13 will come out which is a much bigger value than the operation, so it is not valid, so it is obvious. I will try to make the window smaller. I have made the window smaller. Now we have to remove it again. Okay, what is the original sum? 13 + 4. Okay, what is the original sum? 13 + 4. Okay, what is the original sum? 13 + 4. Okay, what is the window sum? Look, we will make all equal to four. Okay, 13 4 Sorry 4. 8 becomes 17, how much difference is there, nine brother, it is obvious that nine is also very big, if it is a case then it is also not valid and if it is not valid, then again we used to shrink the window. Remember, then L will come here and then same. If you keep doing things, you will notice that only a simple sliding window is working here. Right, first the window must have been this, then I must have expanded the window, okay then when the window did not work, then I minimized the window again. Remember, then made the window bigger. Then we tried to enlarge the window, but it did n't work, so we minimized the window again, we did this, okay, so we are just shifting the window, now see what I told in the beginning, what will happen in the sliding window. The left pointer will be at zero, it will remain here, okay, and the right pointer will also start from zero, right now the window is small, if mine is valid then we will expand the window. Okay, if it is valid, we will expand the window. Okay, it is clear till now. And at the same time, Na current even means the current which is the even of the window, they will keep taking out, as well as now when r was here, it was one, even is okay, then when r became bigger, then r came here, so now the current element A has come. If we make 1 x 8, then we will keep finding the sum of the window easily, okay, then when it increased, it came to 13, we made 13, okay if we shortened the window, now let's see what is the sum of the window, 1 + 8 + 13 and if we make the what is the sum of the window, 1 + 8 + 13 and if we make the what is the sum of the window, 1 + 8 + 13 and if we make the window If you are shorting then l come here and see that it has been removed from the window, so it has been made -1, see that it has been removed from the window, so it has been made -1, see that it has been removed from the window, so it has been made -1, okay, that means I will keep finding the sum in the same variable and keep updating it so that the sum of the window is available to me all the time, okay in this. You will not need the prefix sum and at the same time the window will also start getting even. l = t, this is l = t, this is l = t, this is r in the starting, this is also in the starting, see the current sum, what is mine, the current sum is kept zero in the starting, okay, what did I say that r is Will start from zero, r lesson will go till Nums of R is my target, so at the same time see, we will go on finding the current sum also. Current sum Ps I, Nums of A, OK, current sum has also been calculated, now see, pay attention to what I said that if jo j - a what I said that if jo j - a what I said that if jo j - a pv jo window. Now my j mai aa nahi i.e. r my l pw is this window. If nahi i.e. r my l pw is this window. If nahi i.e. r my l pw is this window. If all the elements of this window are made equal to this target, then how much will be the sum into the target. It will be this much, okay and this is the target will be equal, that is, the window. I would have calculated the sum separately here, how much would be the window sum, see r - a point into target, this is see r - a point into target, this is see r - a point into target, this is also used to be calculated in binary search, remember, I have calculated the window sum and what is the original sum is mine, this is equal to the current sum is correct. If is, then how much will be the difference, that is, how many operations will be required, we were doing the same in binary also, remember window sum minus which is the current sum, my original sum is fine till now it is clear, so if the operation which is mine, if it is greater than k. What does this mean that the window will have to be made smaller? Okay, that means we will have to shrink the window, so if we shrink, then the current sum will also have to be updated. Current sum is minus is equal to two. Remember from where will we shrink, there was an l pointer right from l = 0. It was an l pointer right from l = 0. It was an l pointer right from l = 0. It started ok so the numbers will be removed and it's an obvious thing l will pps because the window is shrinking ok as soon as I get a case and for how long will it shrink until this case is not valid then wait I am writing the operation here, it is okay as long as this operation is of my greater day, then yes, the operation is being updated here, so I will keep adding this operation again and again. We will keep removing these target operations. Okay, as long as my operation is of greater size, I will keep shrinking it by applying a while loop and as soon as I come out of the while loop, that means if a valid case has been found, then the result will be equal to the maximum of the result comma which is now. I have got the window R my a pv will be this frequency we will return result in the last ts it is clear till now what a great approach it was but pay attention the approach is very similar is n't it what is r actually target index is binary search In the code that we had written, we did something like this, see, this is my nothing, this is the target index, what is R, this is my target index, okay and just call binary search here, see this, a while loop. It seems that the window is shrinking, it is just shrinking and the window here is also increasing. My window is fine, so look now you must be thinking that this is the window, which is the L point L pointer, any element. It will visit only once, it will visit any element only once, not multiple times, because L is here now, later L will come here again, it will not even look at one, in the future, it is okay, similarly R is also there, isn't it? Any element will be visited only once, that is, all the elements will be visited only twice, once by L, once by R, that is why the overall time complexity will be 2n, or you can also call it A, ok. Don't think that because of this time complexity has increased, there is nothing like that, ok time complex window is working here, it is exactly the same code as binary search but what have we done here, the target index is also the same in binary search also. Had taken out the current sum also in binary search, were taking out the window as well, okay, here and there we were shifting the middle, to find the window, here we are shifting the window, right? We are doing it from one side and syncing from the other side, till now the slide window has been cleared and it has come out quite easy. Okay, now one last thing, understand that this is over, if you submit it then your code will be accepted. Okay, now consider one more last and important thing, this sliding window can be improved a little bit, before that let me tell you this thing, look here, how I removed the ops, R ma l pv in target, this is the same as the window. Gya minus current sum I had missed writing Okay so I have written the same code Look slightly improved code Look at the same code I just wrote ops equal to Remember what was that R mine L pw into target minus which is current sum As long as Os is greater This window will keep shrinking till it lasts for a day. In the end, the result is equal to max of result comma r - A + 1. Till now the code is of result comma r - A + 1. Till now the code is of result comma r - A + 1. Till now the code is exactly the same as what I did above. Okay, the code is exactly the same. Look, I have removed it now to understand the improvement in it. So let me try to explain the improvement to you with this example. My input was names, we have to sort it, sorted it, okay, now look, pay attention, let's assume l is here, r is here, okay maximum. I store the result here that my maximum frequency is coming, okay, now look at the window sum, this is my window sum, my one came and the current sum is also my one, then how many operations will it take, okay window? Let's see what is the size of k, then my k is lane equal to k, so this is a valid window, so what is the size of the window, then the frequency is one, I have stored it. Okay, if it is valid, then let's try to increase the window r my. Now go ahead and look at the window sum this time. What is the window sum this time? If we make this also four then it will become 4 8. this also four then it will become 4 8. this also four then it will become 4 8. Right 4 + 4 that is eight, but Right 4 + 4 that is eight, but Right 4 + 4 that is eight, but what is the current sum, the original sum is 4 one 1 + 4 that is what is the current sum, the original sum is 4 one 1 + 4 that is what is the current sum, the original sum is 4 one 1 + 4 that is pa. Okay, how much will the total operation cost? 8 - 5 3, which is lesson equal to k, so this is also a 8 - 5 3, which is lesson equal to k, so this is also a 8 - 5 3, which is lesson equal to k, so this is also a valid answer. Right, so what is the size of this window, it is two, so I updated it to be two. Okay, now paying attention is a very important part. Window again I am trying to increase because the last window was valid okay now look pay attention if this time in this window also I will make all equal to eight because r look is pointing to eight so 8 * 3 24 8 P 8 24 will become 8 so 8 * 3 24 8 P 8 24 will become 8 so 8 * 3 24 8 P 8 24 will become 8 3 24 How much is the current sum 13 is 1 P 4 P 8 Okay so look this time it is 11 I will have to do so many operations which are of greater number Okay that means this If there is no valid window, then when there is no valid window, remember, I used to use a while loop here and then shrink it until it becomes valid. Okay, but think for yourself, why do you need to make the window smaller? You are concerned about size, aren't you concerned about size and you have already got the answer of one or two sizes? So if you shrink, you will go smaller than two, so it is better if we assume that right now you have shrunk. If you do this then look, you will get only two or less than two, so why do you need to do that, just move it once, this is invalid right now, just move L once, just take the while loop once. There is no need to shrink L completely. Okay, see what will be the benefit. There is no need to take the Vail loop. Now let's see. Come here, now move ahead. Okay, look, first of all, yes, since it was invalid, so move ahead to L. Look at the size of the given window. The size of the window is still two. Okay, now look, pay attention. Then we have moved ahead here. Okay, now look at the size of the window. Look, it is three. If you make all equal to 13, it will become 39 and the original sum will be the same. Look at how much it is, 8, 12 and 13 become 25. Obviously, 14 is coming, this is also not valid. This is also not valid, so what did I do with simply L? I brought L here, simply brought it here and look here, now the size of the window remains only two of two, then when I move forward, it becomes out of bounds, then my for loop is finished, the answer is still look, it is only two. Aa and only two are its correct answer. Okay, so because you think for yourself, accept that L is here and Aa is here. If it is invalid, then it is okay. So we will have to increase one, we will increase it only once while loop la and proceed further. Will not increase, okay, but if it was valid, then L would have remained here and R, but it is increasing every time, this is also valid, so do not increase L, R will just keep increasing, okay, R will keep increasing and you because the frequency. It is obvious that your correct result will be stored here, so why are you taking the tension of shrinking it again? It is okay because see, if L is fixed at one place, if we assume that This is a valid case, let's assume this index number is fi and R which is my index number is on sen. If this window is valid, okay then we will move aa forward. So remember that aa was here from here, so what is its size. It is three, okay, if it is valid, then only a will increase, so it has come in eight. If it was valid, then the answer is how much would we have made it would have become four. The size of the window between five and eight is four, okay, now let's accept it. r When it came here on nine and is not valid, so just increase L once, na 5, 6, increase L just once, then do a wild loop and do not shrink because if you shrink, it would be obvious. It will be smaller than the result because look, the window is getting smaller anyway. Look, the window is still four. If we assume that it is not valid, then if you move L further, it goes to seven. The window is getting smaller and smaller. If the size of this window becomes three, then you will never get a bigger answer than this, so I am saying that you do not have to take the tension of shrinking the L, just remove the while loop here and put an if here that if it is valid then it will come. So anyway, I will get the answer from here, the best one is fine, it is clear till now, just remove the vial, you can also do if, your answer will always come anyway, okay, do a dry run and see, I have also told you the slight improvement quickly. Let's finish this question by finishing the sliding window. So let's finish it quickly with the sliding window. Okay, so what was said in this that first of all you always have to sort, you have to sort the numbers and of numbers and I told this in the beginning itself. Had given why sorting is beneficial for us n = numbers beneficial for us n = numbers beneficial for us n = numbers size result = 0 let's assume int l = 0 size result = 0 let's assume int l = 0 size result = 0 let's assume int l = 0 ok long current sum = 0 current sum I will keep finding sum = 0 current sum I will keep finding sum = 0 current sum I will keep finding this for int r = 0 r e < n r this for int r = 0 r e < n r this for int r = 0 r e < n r + what was told I am writing exactly the same thing, + what was told I am writing exactly the same thing, + what was told I am writing exactly the same thing, long target is considered to be the numbers of r and if yes, we have to keep updating from current plus equal to two numbers of a, okay now see int operations is equal to how much will it be, remember what I said. That if the window size j minus sorry r my a pv is made equal to the target then it will be even. The target is right and minus the current is even, this will remove my operation and so on as long as the operation is of greater day. I will keep shrinking the window, okay, so the reason for taking the operation again and again, I put this here. Control So I'm going to subtract the current sum from minus it's numbers of - A - A - A PW is fine, let's return the result till now, it is clear and if you put if instead of while then your answer will work and it will be accepted and I had shown you that by doing a dry run from the example also, it is fine, see, it has been accepted here if Let's put it and submit We should be able to pass all the test cases Any doubts raise in the comment section I will try to help you out see you in the next video thank you
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
1,992 |
welcome back guys now let's see the second question of bi-weekly contest second question of bi-weekly contest second question of bi-weekly contest 60 uh like first of all i will explain the question what the question is like we are given certain ones and certain zeros in a matrix and there is and if one is present then one will be present in a group and that group would be a rectangle okay so like and what we have to find is for each group we have to find the top left and the bottom right one in the group of one only we have to find like the top left and bottom right and then we have to return a vector of all the for all such groups we have to find this four length array r17 and 2c2 and they will represent the top left and bottom right points and we have to return an array for all such groups so what i will do is like let's see the approach what i will do is i will check i will go to each and every column then i will check like each and every element i will go ahead and have then i will do a pfs like if there is a one in it let's suppose here one comes then what i will do is i will do a bfs and if a one comes here since i am moving like this in a for loop okay like i'm moving column right i will do move like this in a for loop like i equal to zero then j equal to 1 2 m similarly i equal to 1 j equal to 1 to m okay so this is how i am moving so if i encounter 1 that would be the top left one okay so i will i would get this two index like r1c1 i have got then what i will do is then i will run a bfs on the from this node from this cell i will run a bfs then i would reach to the nearby cells and what i have done is like the last cell that i visit through bfs would be the one that i would be that i would consider as bottom most right cell okay so this would be it and then what i would do is i simply put these four points into a vector and i would return that vector so now let's see the code so i've done as i have said like this is the function that i have made inbound to check whether the neighboring uh neighboring cells of a from a particular cell liner line within the range or not okay so this is and this isn't of much use you can directly see the code uh like i have let's reach here so yeah if visited already visited one we encounter then we would continue and or if the land of i j is zero then also we would continue otherwise i have made a queue for vector sorry q of pair and what i have done is i have visited for that node and like simply i have run a bfs so i can i will explain a bit of that also like what i have done is q dot push the pair currently we are searching for then similarly what i have done is like i will take that first pair and i would pop it and then what i would do is i would move to the neighboring cells and check whether they lie inside within the range or not like what i have done is dx d by a plus 1 minus 1 similarly a plus dx of k what i have done is like basically i'm checking the nearby cells of a particulars from a particular cell if they arrive within the range if they are not visited and their land is the end of xy value is also one then i would go to them then i would run a bfs from there like basically i will push them into the cube so and also as i told that i am taking the right most bottom right point like at last so when the q dot size becomes zero then i would take this point which has come as my bottom right point and i would insert all these points that i got into the vector then i simply return it so yeah this was the question thank you very much
|
Find All Groups of Farmland
|
sort-linked-list-already-sorted-using-absolute-values
|
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape.
|
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
|
Linked List,Two Pointers,Sorting
|
Medium
|
148
|
785 |
and so today we are looking at leap code number 785 is graph by part type and this is a very popular question we can see that facebook in the last six months has asked it 16 times ebay bite dance amazon and uh so yeah let's get into it so is graph bipartite first we got to figure out what is a bipartite graph so given an undirected graph return true if and only if it is bipartite recall that a graph is bipartite if we can split its set of nodes into two independent subsets a and b such that every edge in the graph has one node in a and another in b the graph is given in the following form graph at index i is a list of indices j for which the edge between the nodes i and j exists each node is an integer between zero and graph dot length minus one there are no self edges or parallel edges graph it index i does not contain i and it does not contain any element twice okay so right off the bat we can look at this input that they're giving us and they're giving us an input of a graph in an adjacency list this is essentially an adjacency list so here at the zeroth index of this array the edges are one and three it's connected the zeroth index is connected to node one and node three here at the first index so the one index here it's representing this node its connections are zero and two so you can see the one node here its connection is to 0 and to 2 and so forth and what we want to figure out if it's bipartite what is bipartite it means that every node every edge has to be in an opposite group okay so if we put zero in group a then one has to be in group b if one is in group b then two has to be in group a if 2 is in group a then 3 has to be in group b and if 3 is in group b then 0 again has to be in group a so every edge here has to be able to be in either group a or b but it cannot be in the same group okay so let me make this a little more clear we'll draw out the input here so here we have zero is connected to one is connected to two is connected to 3 and this is connected to connected back to 0. and if we look here we can see that if we put 0 and a 1 and b 2 in a and 3 and b then every edge here is connected either to a or b but not to itself not to a and if we look at the other example here this is false this is not bipartite okay because here we have 0 1 2 3 but we also have this connection between 0 and 2. and that makes it not bipartite and we'll draw it out here just to make it a little more clear so here we have graph 2 which is very similar to the first one and we're going to have zero it's connected to one which is connected to two which is connected to three and three which is connected back to zero but we also have this connection over here between 0 and 2. now let's take a look at our example that we did before if 0 is in group a 1 is in group b 2 is in group a and 3 is in group b we can see that we have a connection between a and that means that it cannot be bipartite okay so that's the key thing that we want to figure out is if there is a connection between a and a now one other example i want to take a look at i want you guys to take a look at is what if we have a tree so remember a tree is just a graph without any cycles okay so what if we have one two three just do one over here and then we have four and five okay we can even have a six here so now we have these six nodes and we wanna figure out is this bipartite well let's take a look at this if this is in group a this is in group b this is going to be in group b this is a and this is a so there are no nodes in this entire tree that are connected to the same group okay every edge here is either connected to a b or an a but not itself a is not connected to a anywhere in this tree and b is not connected directly to b and one thing i want you to know is so if there's no cycles and we have a tree then it is a bipartite graph however if we have a cycle okay if we have a graph and let's say we have a connection between 6 and 3. that is also bipartite because again there's no connection between a and a or b and b this connection right here is between a and b okay so if we have a level order cross edge okay so this is going to be this is our l1 l2 and l3 and if we have a cross edge that crosses levels okay then it can be bipartite however if we have an edge that is in the same level then it cannot be bipartite because here we do have a connection between b and b okay another way to think about this is if there's a cycle in the graph and it's an odd length cycle then it cannot be bipartite but if it's an even length cycle then it can be bipartite okay so it's really important to make sure that you got a clear grasp on that on what we're trying to figure out in this graph okay so let's try to code this up so is bipartite okay so what we want to do is we want to traverse over this graph and we want to figure out if there's an odd length cycle in this graph that means it is not bipartite we want to return false and if we can traverse through every single node in the graph and not find an odd length cycle then we can assume that this graph is indeed bipartite okay so we're going to go ahead and we already have our input as a graph so we don't need to build the adjacency list so we can just go ahead and create our visited launched visited i'll just make this an object and then we're going to want a distance okay and this will make more sense once we get into the traversal part of the code and so what we're going to do now is we're going to just follow our basic template for traversing through a graph okay we're going to let our vertex equal zero vertex is less than graph dot length and vertex plus and what we want to do here is check if we have visited this vertex if we have not visited this vertex then what we want to do is we want to check well first yeah so we want to check if is graph bipartite and we're going to go ahead and put in the vertex the graph the visited and the distance and if the graph is not bipartite if we traverse through this graph from this particular vertex from this starting node and we find that it is not bipartite at any point in that traversal then we want to just go ahead and exit out of it and return false and if we traverse through the entire graph and we cannot find an odd cycle then we can assume that the graph is indeed bipartite and will return true okay so that's the main function code not to not too complicated and now we just want to create a helper function to traverse from every particular vertex and check do we have an odd cycle okay so what we're going to do is const graph bipartite we're going to have our node our graph are visited and our distance okay and we're going to do a breath first uh search traversal method here so we're going to go ahead and create a cue and we'll put in that node and then we'll also add the visited of this node and set that to true and we're going to set the distance to zero so distance at index of node we're going to set that to zero because it's going to be the root node so the distance to the source node is going to be zero now we're going to do our very familiar breadth first search traversal q dot length okay and we're going to shift off uh the node from the queue so we can call that current node let per node is going to be okay and we're going to add this current node to visited we'll set that to true okay and now we want to traverse over the neighbors from this current node so we can do four let neighbor of graph atker node okay and if we have not visited this neighbor then what we want to do is add this neighbor to our visited and we want to update the distance okay so any neighbor that we have the distance from the source will be whatever the current distance is plus one the distance from the node plus one okay so we can do distance of neighbor is going to equal distance of ker node plus one okay so our source node plus one and then we can go ahead and push this neighbor onto the queue now what we want to do is we want to check if the distance from the neighbor is the same as the distance from the current node then the graph is not bipartite it means that we have a level order not a level order a same level cross edge okay so if we have um distance of t c distance of neighbor equals distance of current node then we want to go ahead and return false it is not bipartite okay and if not then we want to return true okay let's go ahead and run this and yeah we're good okay so some things that i want to go over is this right here the distance of the neighbor equals the distance of the current node and what i would recommend is really stepping through and understanding why this line works the way it does okay um if you just use this graph with four nodes in it's not too bad make some separate variables and really step through to make that clear because what we really want to check what we really want to make sure is that we don't have a cross edge in the same level okay and that if we have a cross edge in the same level then we can also assume that the cycle is odd and we can assume that it's not bipartite okay so i hope you enjoyed it and i will see you on the next one
|
Is Graph Bipartite?
|
basic-calculator-iii
|
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties:
* There are no self-edges (`graph[u]` does not contain `u`).
* There are no parallel edges (`graph[u]` does not contain duplicate values).
* If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected).
* The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them.
A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`.
Return `true` _if and only if it is **bipartite**_.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\]
**Output:** false
**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
**Example 2:**
**Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\]
**Output:** true
**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}.
**Constraints:**
* `graph.length == n`
* `1 <= n <= 100`
* `0 <= graph[u].length < n`
* `0 <= graph[u][i] <= n - 1`
* `graph[u]` does not contain `u`.
* All the values of `graph[u]` are **unique**.
* If `graph[u]` contains `v`, then `graph[v]` contains `u`.
| null |
Math,String,Stack,Recursion
|
Hard
|
224,227,781,1736
|
690 |
hi let's talk about employee importance so you are given a data structure of employee information which include the employee unique id their importance value and your direct subordinate id so this is employee class which is this and you are given the list of employee so you do you need to find out the total given integer id let represent of the id of employee return of total importance uh value of their of this employee and all their subordinates so imagine id is one and this is id one for sure right and then the sub ordinates is two and three and then just add three and then add another three which will include eleven right and i'm going to teach you the fast the most uh efficient way so i'm gonna uh have a hash map that uh key is integer and the value is employee and i will tell you why give me one set all right so integer is the key is uh i'm gonna store the employee id and the value employee will store the employee uh itself so i need to try verse employees correctly yes employee and then employees then math output and right so this is actually how i put my map the input into my mac and i'm going to have a um semicolon right here and then later on i will have to add every single um every single employee into my map sorry into my cube so i have a queue so q it should be a linked list so i'm going to say q and for e you put the link to this then uh what i would do is i put the id uh into my queue so if i have to put id into my queue i have to find out the employee id right so i will say uh q dot over and then map like that uh get the i id sorry so this is how i actually know which employee id i should uh stay on the queue and then keep adding so i will say wow uh well uh q is not entity i'll just keep doing this and since we're returning in try we need to have a return value that will be initial view and return result so i will have to pull the employee out from q so uh q dot then before uh i do anything for the subordinates i need to add so rest of the equal plus equal node are important then for any uh integers sub uh subordinates uh since this is uh the subordinates is list of integer right so for integer the inside of sub that would be no stop subordinates then i would just keep adding to the author keep adding to the queue so map get stop and that will be entire solution and then they just run it and all right i made a mistake q instead of q and there will be bit so all right so uh there should be no problem on this i'll summarize this later so let's talk about timing space so for the space you need to store every single input into the map right so that would be all of n and for the value i would say that maximum the worst case or the value traverse everything single employee in the map uh which is i mean you add into the queue uh you add into a queue and then you pull and then you when you find out you at uh you add again that would come uh that would there will be all of them for the worst case and um for the summary so whatever you want right you need to put into map so employee you will put into employee will put into the map so key is the id value is employee and then you have a queue which will keep adding your id from your id to the end right so you put this id the employee id uh into the queue and then you keep traversing uh or you end up once the follow is uh is your like you have no subordinate to traverse and that will give you the final result and uh just making sure you don't have an infinite loop in the subordinates and that will be the um the solution for these questions so if you feel helpful then press the like subscribe if you want it and leave a comment if you have any questions alright and peace out bye
|
Employee Importance
|
employee-importance
|
You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees `employees` where:
* `employees[i].id` is the ID of the `ith` employee.
* `employees[i].importance` is the importance value of the `ith` employee.
* `employees[i].subordinates` is a list of the IDs of the direct subordinates of the `ith` employee.
Given an integer `id` that represents an employee's ID, return _the **total** importance value of this employee and all their direct and indirect subordinates_.
**Example 1:**
**Input:** employees = \[\[1,5,\[2,3\]\],\[2,3,\[\]\],\[3,3,\[\]\]\], id = 1
**Output:** 11
**Explanation:** Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.
They both have an importance value of 3.
Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11.
**Example 2:**
**Input:** employees = \[\[1,2,\[5\]\],\[5,-3,\[\]\]\], id = 5
**Output:** -3
**Explanation:** Employee 5 has an importance value of -3 and has no direct subordinates.
Thus, the total importance value of employee 5 is -3.
**Constraints:**
* `1 <= employees.length <= 2000`
* `1 <= employees[i].id <= 2000`
* All `employees[i].id` are **unique**.
* `-100 <= employees[i].importance <= 100`
* One employee has at most one direct leader and may have several subordinates.
* The IDs in `employees[i].subordinates` are valid IDs.
| null |
Hash Table,Depth-First Search,Breadth-First Search
|
Medium
|
339
|
486 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge predict the winner um so basically here we have an array of numbers and we have two players that are playing a game um player one and player two we just give them those names and um they take turns and we are told that player one starts first so they play the first round and both players start with a score of zero obviously and then at each turn the player takes one of the numbers from the array they can take either from the start of or from the end so from the left or from the right okay but only one and then that would reduce the array size of one by one yeah and the player adds the value they chose to their score so player one for example let's say they pick two at the end and so their score is now two then player one plays let's say they take maybe one now their score is one and their players two plays and they take five and so this is seven right however we are told that players play optimally so that means that they will each try to maximize their score um so basically that means in the case where uh player one chooses let's say two like here then player two will have to choose one of these players two will obviously decide to choose five okay so that's the idea here because if five is bigger and the goal of the problem basically is to the game ends when there are no more elements so all the array elements have been chosen and it's now empty and the goal of the problem is to return true if Player 1 wins the game okay and player one wins the game if score of player one is bigger or equal to score of player two so if the difference between This chords is bigger equal to zero here if both scores are equal we player one wins so that's the idea and looking here at the constraint it's pretty small so let's see how we can tackle it um so the first thing to think about here is the strategy to just pick the max of the left and the right let's say four maybe one is not actually a good strategy because it's not enough to determine the winner because maybe there's a value in the middle that is bigger and that will increase the score if we take let's say if we choose a bigger value but we would have gotten 9 if we chose a smaller value okay and so with the absence of like sort of a greedy heuristic then we can just um and because we want to determine if player um one can win the game in any possibility we don't care about like if we just try to do that this optimal way of choosing maybe the max we don't know if there is another possibility where they would have chosen the smallest value in the one in the game right and so that means let's try all of them so that's what we'll do let's try all possibilities and see um which one will give us the max score okay and so how do we do that well let's take the smallest example here so first let's have a decision tree player one plays right so it's the turn of player one so let's actually have a state let's have turned so this would be the turn it's one if it's player one and two if it's player two and then we need the score of both right the score of the S1 the score of player one and S2 the score of player 2. okay and of course we need to also know what's remaining in the array so let's just call it remaining okay um and let's actually just put remaining at the beginning um just so that you can see what this will look like okay and so let's start out then with the entire array and the tone is one and the score is zero for each okay so one has two choices it can either take the first element or the last so let's have both if it takes the first element then we would have 5 2 we would now it's the term for two the score for S1 is 1 and the score for two is still two and then the other possibility is for it to take two so we have one five and the turn is now two and the score is um two right and then the score for this one is zero so now it's the term four two it has two choices this one or this one so it takes let's say five let's say it takes uh five yep so we have two uh now it's the term for one and then the score now for two is score for one still one for score for two is now five the other option is for to take two and so we have five remaining um now it's the term for one and we one has still one and the score is two okay and we continue now there is only one choice and so the array becomes empty um now it's in the for two but we are done and then we increase three and then the score is five and here player two wins so here we return false okay now here in this case we have only again one choice for and so um the arrow becomes empty turn of two one is um uh the square is now six um so here two um and then we get um for two is still two okay so now you're here we can say that P1 wins but is this one a possibility this one actually a possibility well the problem says that each player plays optimally okay so that means given these two choices for player two given these two choices they will choose the most optimal Choice which is of course this one so this actually um would not be P2 will not choose this because then they won't win right um because it's their turn so it's all it's only if P1 doesn't give them any choice right to win then they can um then they can win right and so that means they will choose here so you can already see here when it's P2 player two turned what P1 needs is P1 needs for all choices to be loose to be losing for losing choices if one of them is winning player two will choose it because they play optimally okay and so that this is one of the first insights let's keep that in mind um but for player 2 for Player 1 if it has two choices and one of them is winning it will of course choose the winning one okay and so here using this um tree here you see that we have two choices each time we have Choice one where a player will choose um to take the left okay so take left and choose choice to what it will take left right okay so now what we want to return is if it's the turn for player one let's call it turn equal to one so this is player one turn then we only need one of these two choices to be true so we can return true if C1 or C2 so if one of those chases is true then it will take the most optimal one which is winning but if it's turned for player 2 we need both choices to be losing because like in this case since this one is a losing Choice player 2 will only take this one okay and so for player one to win both choices need to be losing okay so which means here that we need C1 and C2 to be true um Okay so now with that we can actually start doing our solution we have the state that we need the Val the parameters for our state or our recursive function and we know the two cases that we need it's either take left or right and then we know that we depending on the turn we choose we take either r or end and then the base case what is the base case well the base case when we don't have any remaining elements so we need the list is empty so if not remaining so in Python if it's empty what should we return um well it depends on the score we just return if score one is bigger or equal to score two that means player one okay this is winning one thing I want to clarify here for C1 and C2 remember this is returning true only if score one is bigger and so end here means with Choice one player 2 loses and with Choice 2 player 2 loses as well because the state of the function returns is whether player one wins which means whether player 2 loses okay and so here it means whether player one wins and when or player one wins so if the turn if the is the turn of player one then if one of them is a good choice to win they can take it but if it's the turn of player two then both choices have to be wins for P1 okay for to be a win for P1 because if it's if one of them is a win for P2 will take that choice okay I hope that's clear now what is the time complexity for this solution well we are using a recursive solution where we have only two choices okay and how many Choice how many what's the depth of the tree it's going to be n because we have n elements in the each time we reduce by one and so um and we have two choices each time so this would be 2 to the power of n because we have two branches each time and we have n branches um so with n big or equal to two like in the constraint this should be a good solution it should pass um yeah so let's implement it and make sure it's good um okay so let's implement this solution so what we need is we need our recursive function um let's call it play um and let's pass the parameter so the remaining elements of the list the turn score one and score two and we said our base case is if the list is empty we want to return whether square one is bigger or equal to score two okay and then we have Choice one which is take left so Choice one is take left element um and then Choice 2 is going to be taking the right element okay so to take the left element what does this mean so basically it means you take the element at zero and the remaining are from one to the end um and then what's the turn well turn is two if it was player one's turn otherwise it's player ones if it was player two Stern then now it's player one start now what does the squad increase by well the score for one increases by the remainder at position zero if the turn was player one start otherwise it doesn't increase and similarly for score 2 it increases if it was player 2's turn otherwise it doesn't increase okay and we do the exact same thing for Choice two so we go here Choice two except we want to pick the last element so in Python to get everything except the last element you can do it like this um and then what we need is we need um same thing the term changes and then score one increases taken by the last element if we take the right element if it was its turn otherwise it increases for uh score two for player two and we said that we want but we want if it was player one's turn right if it was turned of player one then we want any option where they win they will choose it and they will win so we wanna return C1 or C2 however if it was player 2's turn right then we want to return both needs to be wins for player one remember C1 and C2 means what meanwhile are true if in that Branch player one wins and so here this means both branches player 2 loses and so which means player one so this is true if which means Player 1 has to win player 2 doesn't have any choice and we can actually get rid of this else just because we return here and so in now we call our recursive function which is play with just the array right so and then the turn starts out at one and this course starts out at zero so if I run this um we didn't this is C2 sorry um it looks good let's submit um this is natural normal uh makes sense that it's slow because it's O of 2 to the power of n but let's see if we can optimize this a little bit so the first thing we want to change is just make this a little bit nicer without the array and so let's just have this B left and right and so what we are done when left is bigger than right so we did all of them and then here left increases by one because we just move to the left right stays the same here left stays the same and Right Moves by minus one so still the same we just changed the variables and so here we need to pass zero in the length of the numbers minus one because that's the rightmost uh index except here we need to get the element at the left um same thing here and here we need to get the element at the right so all right and same thing here so I front this and this should pass okay looks like it passed now one thing I want to show here is that do we actually need to pass both scores so let's try to sort of reduce the number of parameters we have here um so score one and score two if player one we only want to check if this is bigger if score one is bigger equals score so that's the main usage that we have so we can actually just check this okay so we don't need both we can just pass the difference right so difference between scores with basically score one minus score two like this so if we do that then we can do diff so how do we do that then here it's going to be Plus numbers left if turn is one otherwise the difference right otherwise if it's turned for player two it's going to need to be diff minus limbs left because remember we are taking the difference of score one minus Square two and similarly here except this is going to need to be right and this should still be passed except here we only need one variable and we can submit okay so it looks like this uh sorry this past okay now that we did this optimization one thing we can think about is do we actually need this turn as well this third variable and do we actually need to pass diff as a parameter can we just have it returned and check here if it's big or equal to zero right because why am I saying this because if we can return div then we can cache using left and right so that we don't repeat computations okay because left and right each are over are can be at most n so if we can make this be the state of this be zero to n for left and zero to n for right then we can actually have a noven squared solution okay so that's the idea here instead of having o of 2s to the power of n and so the idea is we don't need to do the turns because if it's player two's turn since we want to maximize the div then we can just subtract okay and so to do that then here let's call this Choice One what we can do is just do left minus that well it's the term for the other player we just subtract because when it's the turn for player two subtracting minus twice is going to be adding and so here we can just have a get rid of the turn and also since we want to get rid of the disk actually just returned the max of the two because we want to maximize the difference so that it's bigger than zero so it's best to maximize um the difference right and so here we can just return the max for the difference and let's just make this clear that it's a difference let's say diff one okay so we take the max of default and div2 and here this can be we can get rid of the third and since it's the subtracting the difference we can just take the number in right minus once the term for the other player and we can get rid of this okay and here this is what we already did so we could get rid of it okay and now it's a lot better um and we can okay let's see here right minus one and now you can see we have only left and right as the parameters okay so let's actually pass only those two and check if the difference is bigger equal to zero that means player one wins here except here since we want to return at the actual difference we only need to return um let's change this to be equal when it's equal so there is only one element we just need to return that element okay and so if we submit this passes but we can actually optimize it further we can have a cache in Python you can just use cache if you want you could use a memorization table like a map that has the parameters are left and right or you could use also a table with the parameters are left and right but to be faster in Python we can just use this cache annotation and this should be a lot faster and you can see it already if I submit it quickly passes okay now what is the time complexity for the solution well here the only States and since we cash if we get a call again with the same values we'll just return the cached values and so that means here it only depends on the range for left and the range for right so the range for left since left is going to be at most the number of elements in the array so it's n elements and for rights the end and for right the range is also n 0 to n because at most you would have the number of elements or more accuracy 0 to n minus one and so since the state of our cache is just both at most is going to be over squared time complexity and similarly for space complexity because we also use this cache that needs at most N squared slots because we have n by n then it would be all of N squared space as well okay so this is a more optimal solution um and I know we want to throw multiple steps to understand it but this is the actual way you solve this type of game theory or min max problems is you don't need to actually be explicit about the turn you can just um basically have the difference and um uh and um and subtract the for the opposite player and add for you for yourself right um I hope this may this was clear uh please like And subscribe and see you on the next one bye
|
Predict the Winner
|
predict-the-winner
|
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally.
**Example 1:**
**Input:** nums = \[1,5,2\]
**Output:** false
**Explanation:** Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
**Example 2:**
**Input:** nums = \[1,5,233,7\]
**Output:** true
**Explanation:** Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 107`
| null |
Array,Math,Dynamic Programming,Recursion,Game Theory
|
Medium
|
464
|
303 |
hello and welcome well continuation press add patterns with the range sum query immutable which is quite a mouthful so um we are giving an integer array of norms and we want to calculate the sum of elements the sum of the element of numbers between the given indices and we can say that we are given the number minus 2 0 3 minus five two no minus five two and minus one and the first query that we're giving is to find the sum between the index zero and index two and we can see that minus two plus zero plus three is indeed um three minus two one which we can see here and we can also see from the second problem the second query rather index 2 up to index 5 and if we sum all this it is indeed -1 and if we sum all this it is indeed -1 and if we sum all this it is indeed -1 so basically that's the problem that we want to solve now let's give ourselves more room so we are given the numbers minus 2 3 minus 5 2 and minus 1. and basically the first intuitive approaching i think is that when we are giving index 0 up to 2 we can just basically loop from index 2 in the x 0 up to 2 and if we're giving from index 2 to 5 we can just loop and find all the numbers or the sum of the numbers from index 2 to 5 and basically by giving from index 0 up to index 5 we can just run another loop again now this is the most intuitive approach but you consider this get repetitive a bit for instance if we're looking for the sum of index 0 to 2 we already have this and remember that this problem says that to be given multiple queries at a time is there any way we can do this efficiently this is going to run in linear time for each query is a linear time operation and constant space linear time because we are basically just looping through the given number and since the number can go as large as the entire number like case of zero to five now basically we can go from the beginning to the end of the array so that's a linear time operation and we're not using any extra memory right so that's constant space but we have to know that well we can undo this problem is said to undo multiple queries so we have to think of ways whereby we can do it better and we can say that if we have computed the sum from index 0 to index 2 then we're going from index 0 to index 5. basically we are recomputing it from the beginning again is there no way where we can we could have stored or have access to the sum from index 0 to index 2 rather than starting all over again when we have this problem and yes there is a better way and that better way is the prefix sum so basically the prefix sum means that we at every index and this is the second approach by the way the prefix sum and prefix sum just basically mean previous sum it means that for every index right we are going to store the previous sum at every index so basically this is um the first index right the previous sum from the previous sum of all of the numbers before index zero we don't have any previous sum so basically this is zero because there is no number existing before this first number so this is going to be zero right then we move over to the second index and the previous sum before the first index is basically just this first number and we save it here now we move to the second index the third number and the previous sum is minus two plus zero it is still minus two basically there is nothing to sum it up with and then we move on to the fourth index now let me just put this disclaimer here so it is a bit easier to remember so basically this is the third index and what is the sum of all the previous numbers before the third index this is just 3 minus two this is one next we move to the fourth index and basically the sum before all of this fourth index is going to be minus five plus one is going to be minus four and then we move over to this one and the sum of all the numbers before minus 5 is going to be 2 minus 4 that is minus 2. now our prefix sum is going to have an extra number to accommodate for the sum of this last number right because basically at this point we are getting the sum of all the numbers before but what about this number we've not added it to a sum so we have to accommodate for that and we're basically going to say that okay minus two minus one this is going to be minus three now this is what is called the prefix sum at every index we are getting the sum of all the numbers before that index we are not including that number right minus two does not have any numbers with this prefix sum there is basically nothing to sum so that's zero which is at the second index the only sum before the only number before it is minus two plus nothing is minus two three right the sum of all the numbers before index two is minus two plus zero as minus two the sum of all the numbers before index three plus minus two and so on and so forth now how does this error pose this helps us in that whenever we have a query of you know find the sum of the numbers ranging from index 0 to index 2. basically what is the sum and we can just look at okay the sum at index 2 is going to be here right because we know that this sum at index 2 does not include the number at index 2 basically we are computing that number at this we do not include the sum of 3 at this so for every rights number for our rightmost number we are going to increment this by one because we can see from our array that there was an increment right so if there if we have been asked for the sum of the number from index 0 to index 2 basically we are going from okay so what is the sum at index 2 it is 1 right minus 0 and we can see that this is one like it's giving a sample input and then basically we're asking again okay what is the sum between index zero and index five and we know that the sum at index five is going to be index five plus one includes the value that's index five this only includes the number before index five but plus one includes you have to look at this index plus one because we've incremented the array right so this is going to be minus three minus what do we have at index zero and this is basically minus three now while we might not seen it so am i nothing because we already have the grand sum at the rightmost and we have the grand sum at the left most so if we take it away basically we're just saying okay what is the difference between this and that's going to give us the exact number we don't have to loop over every operation we don't have to loop over all of the operations anymore because we already have the sum and that is the prefix sum up which we're going to be writing the code for the two and then you can just um compare and see how it's it is right so the first approach is where we adjust um basically doing the normal looping through the intuitive approach right we have to declare this sum so that we can have access to it here and then we're just going to return the sum of the index at the leftmost onto the right so this is just basically a python operation i'm not sure if this sum exists in other languages wherever those you are just looking for the sum ranging from the number at the left up to the number at the right and this is just the basic intuitive approach if your language doesn't use the imbued doesn't have any imbued sum function then that means you would have to use the normal for loop to traverse from the leftmost index to the rightmost index and we can see that this runs this works right but since we want to make how can we make this more efficient we can make this more efficient by first finding the prefix sum so at the first index we know that no sum exists yet so it's just going to be zero right and we're now going to run through all of the elements in the sum and then we're in the norms in the nums array and we are going to append right we're going to append the last element in the array plus the current norm so basically this is saying that if we have um let's go back to our example we have zero we have three we have minus five we have two right so what this is saying that serve the nums the first index is zero now we are looking through this entire array and i said okay what is the last element in the array zero does the current number this is plus two this is minus two and then our prefix sum is going to look like this we have zero first after the loop we have minus two then we run the loop again and what is the last element minus two plus the current element now is zero so it's going to be zero plus minus which is minus two basically the prefix sum which is showed in the code walkthrough now after we have done this we can now compute the sum which is just going to be as simple as saying um since we already have the prefix sum at each level so what we're doing now is we're just going to say that um the leftmost element right were returning the right most elements plus one don't forget the plus monsters by cruising array minus the left most the elements that is at the left of this new prefix sum and we're taking it away from the element that's at the right of this prefix sum so this is just the code as you can see is pretty straightforward and we're going to run this and you can see that it even runs faster than the intuitive approach i hope this was helpful please subscribe to support the channel and i'll see you on the next video bye
|
Range Sum Query - Immutable
|
range-sum-query-immutable
|
Given an integer array `nums`, handle multiple queries of the following type:
1. 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`.
* `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 ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`.
| null |
Array,Design,Prefix Sum
|
Easy
|
304,307,325
|
279 |
hi let's solve today's daily challenge that is perfect squares in this question we are given an integer n and we need to return the least number of perfect square numbers so what is perfect square they have defined here but we know what a perfect square is basically consider all the numbers from 1 to n and square them correct so those squares we have to use and we have to return the least number of these squares that sum up to n all right so um let us understand this test case that is n is equal to 12 so it is equal to 12 now let me write all these perfect squares here so that is 1 square 2 square 3 square right so on so it will be 1 4 9 and if I also write 4 Square here it would be 16 5 Square 25 and so on now what I have to do is I have to make this correct so I can say if I take one see repetition is allowed here right if repetition wouldn't be allowed then there would be cases in which it will be impossible to you know make up this number but here repetition is allowed so that means if repetition is allowed so one answer is very obvious that is I can take one 12 number of times right so 1 + 1 + 1 how many of times right so 1 + 1 + 1 how many of times right so 1 + 1 + 1 how many times 12 times so this is a valid answer now I have to check for other options as well now if I go to four then um one solution would be to add 4 and add eight number of ones right so 1 + 1 and 8 * 1es would of ones right so 1 + 1 and 8 * 1es would of ones right so 1 + 1 and 8 * 1es would be added so here total of 12 numbers are used here total of nine numbers are used let us move to another approach let's I do 4 + 4 and rest are one okay so if do 4 + 4 and rest are one okay so if do 4 + 4 and rest are one okay so if that uh is the case it is8 and the number of ones we will have is four here right and we'll be able to make 12 so now these are six numbers okay so we are boiling them down um then we can have 4 + 4 + 4 this also gives me we can have 4 + 4 + 4 this also gives me we can have 4 + 4 + 4 this also gives me an answer and it is three another option I can use is using nine right so 9 + 4 I can use is using nine right so 9 + 4 I can use is using nine right so 9 + 4 you can clearly seees 13 so that is greater than n so obviously this will not be an answer now I can do 9 plus but I can surely add one how many number of times three number of times so 9 + 1 + 1 so here we are using four 9 + 1 + 1 so here we are using four 9 + 1 + 1 so here we are using four numbers so now if you see there are no more possibilities here because 1625 are already greater than n so we could only have um have it played with these four these three numbers correct so out of these possibilities I have to written the least number of numbers that we have used the number of squares that we have used and that is three so this will be the answer in this case so now I hope you have understood what the question is asking us to do right now uh from this you can clearly see that we have to consider all of the possibilities and when we have to consider all of the possibilities one solution is very clear to us that is recursion now another reason recursion would be coming to our mind in this problem is because now see what are we doing we are only checking minimum number right so let's say um I do 12 minus 4 right so I have 8 so can I say that 1 plus whatever be the number of um minimum operations I have to do for eight right minimum number of squares that I have to add eight that I can add and I will get an answer correct so that means there are you know sub problems that we can solve so thus we can use recursion here all right so that would be our very first solution now again uh let me first draw the recursion tree for you all right okay so here is the recursion tree right so what are we going to do we are taking this n and then we are going to iterate in all these perfect squares now the limit would be to iterate in it is let's say this is I right what integer that I have to consider so I into I right it should be less than equal to this number in uh n right only then we will be you know um able to take these squares right other squares we don't have to iterate for them because they are already bigger than this number so how will they help us to solve this question right so we would iterate in these number of possibilities that is root 10 times we have to iterate now here n is 12 so I can consider only 1 4 and 9 and then if I consider one what will happen n will become 11 and if I consider four what will happen n will become 8 if I consider 9 N will become three right and if you keep doing so on and so on so um here in the recursion tree whenever your n becomes zero right you know this I have got an answer right so whenever n becomes zero this will be the base condition for our recursion as soon as n becomes zero you have to store the number of steps that you have to go down the tree and uh store it let's say in our answer variable and keep calculating the minimum after doing this these recursive calls right so this is basically how you have to do recursion right let me also quickly show you the code for this so here you can see the code all right uh so we are using recursion here and what are we doing we are using this function right so this function is a recursive function and we are only taking one parameter that is n and then we are checking this is the base condition if it is less than equal to Z then return zero because we have already made done all kinds of operations okay and if uh and all right and then what we have to do we have to store answer is equal to n because see maximum number would be n only right so instead of storing int Max we can store n right because it's also valid answer that is by using one n number of times correct then that is also an answer so and that is the maximum value the values then if you consider other squares it will only be decreased right so after we initiate our answer variable then we will simply iterate how many times from I is equal to 1 to I into I less than equal to n basically root in number of times and then we will be calculating that particular Square value whe whether in this case it is 1 149 right for these three values we have to iterate so we'll calculate this here and then we will calculate the answer how first we will take whatever was the minimum value right whatever was the previous answer value and then we would do 1+ answer value and then we would do 1+ answer value and then we would do 1+ right why 1 plus because we are considering this number right we are considering if this is a possible answer so we have to include this number this particular square that we are using one and one so that is one square right and then we are recursively calling for n minus square right so that you can also see from here what are we doing we are iterating for these and then we are taking let's say if I take this Square then what I have to do I have to take this step also right so this step is one so 1 plus I will call for 12 minus this Square which is 11 right so I will call for what is the minimum number of steps for 11 please return me that and then 1 plus the minimum to get this number and that will return as an answer right so I hope you're understanding and then after the end we have to Simply return answer so this is basically the recursive solution now for the time complexity of this recursive solution uh we can already see first of all what we are doing we are iterating here how many number of times root 10 number of times and then how many times this recursion would happen at most it can happen n number of times why because I know one can be a possible answer and it is a repetition so I can have n number of ones to form this integer n right so at most n recursion calls will be there right so it will become um otk 10 power n right so that will be the time complexity for this right that is basically uh n power n by 2 now uh let us come on the board and obviously the solution will give me tle right so I need to optimize it how am I going to optimize it whenever I have a recursive solution I know I have to check if dynamic programming is possible right so one thing is clear we have sub problems correct but do we have overlapping sub problems so that we have to check now you can clearly see we definitely have overlapping sub problems and that you can see from here right let me take a different pen let's take green so here n is equal to 3 is present here n is equal to 3 is there here n is equal to 2 is present and let me find another two here n is equal to 2 and yeah here n is equal to 2 so there are many overlapping sub problems so if I've already calculated for n is equal to 3 why do I need to again make recursive calls here and calculate it so now here I can simply do my DP right so if I look at the code for the recursion I can see that this part has to be common in the DP as well right so I have to check for all these values right if an answer is possible and instead of ANS right see here doing top to bottom DP is very easy right I'm going to discuss bottom up DP all right so essentially what we will do we will make our DP array right and first thing to note here is that it is only one integer that is changing right only one value that is changing so it will it is 1D DP so I have to only take okay wait so I have to only take one array and this is my DP array what should be the size of this DP because I have to written an answer for n integer right so my DP of I will represent for that I integer what is the minimum number of squares required right so if I um for n is equal to 12 my DP size should be n + 1 right so 12 my DP size should be n + 1 right so 12 my DP size should be n + 1 right so uh it is 0 1 2 3 4 5 6 8 9 10 11 and 12 this will be my DP array and what does DP of I denote DP of I denotes for this particular value how many what is the least number of squares that I require right okay so now it is clear what DP of I is going to represent and what should be the size of DP AR now what should be the base condition right the base condition is here in the recursion you can see it was n less than equal to Z but obviously um we don't really have to calculate for n less than equal to0 but for n is equal to0 I can surely put here an answer which will be zero right so there is only one initialization that is DP of 0 will be zero because I have to make zero and zero can be made using zero only zero number of squares correct so this is formed now I will iterate from here okay and I will iterate in these possibilities right I less than equal to n these number of possibilities so first I'll be trating like this so for DP of one what should be the answer so I have only one possibility that is one here right so I can only use this and I can already see um the minimum required square is one only here so we insert one then we will come at this two right we have to form what will be here so what do we have to do again consider all the possibilities for this case again we only have one right and if you try to explore the possibilities then there is only one possibility 1 + then there is only one possibility 1 + then there is only one possibility 1 + one so here you have to insert two then you will come at three now at three again you have only one right you cannot use four so again it will be filled with three now whenever you okay when you come at four now you have two possib ities considering four or 1 how will you fill this so you will basically fill this so let me write here DP of I supposed to be minimum of right DP of I comma 1+ that is you're taking a number comma 1+ that is you're taking a number comma 1+ that is you're taking a number plus DP of I minus remove that square all right and this minimum value we have to calculate now here at four initially all these values will be filled with zero okay now initially it will be zero but we have to initialize it with the maximum number right so before looping for this we will do what we will take DP of I is equal to I for initializing it with the maximum value and then we will be here right so we don't have to fill them with zero it's actually that number itself that can be the maximum right very sorry for that all right now we have DP of I is equal to I and then what we'll do we'll start it rating for the possibilities so here we have two possibilities that is using one or four so what you will do you will calculate minimum of DP of I 1 + i- calculate minimum of DP of I 1 + i- calculate minimum of DP of I 1 + i- square so if it is 1 right so 4 - 1 if square so if it is 1 right so 4 - 1 if square so if it is 1 right so 4 - 1 if you do you will come at this index so 3 + 1 right and 4 comma 3 + 1 is 4 right + 1 right and 4 comma 3 + 1 is 4 right + 1 right and 4 comma 3 + 1 is 4 right so still the minimum is four then if you consider four here right this is the second possibilities then we have four comma minimum of IUS square that is zero you come to this Index right so you add 0 + 1 which is 1 so this is the minimum 0 + 1 which is 1 so this is the minimum 0 + 1 which is 1 so this is the minimum required number then you will come at five and you will do the similar thing and this way you will keep filling the array and you will have to return DP of n as an answer because it is the an integer that you want the least number of squares for right so this will be my answer so this is basically how we have to do DP and this is bottom of DP so let me go and quickly code it out okay before we code it out let me discuss the time complexity of it so what we will be doing is first iterating from all the values from one up till n number right first we initialize DP of 0 as 0 then iterate from I is equal to 1 to n right and then uh it is similar to this right explore all the possibilities and store it and only difference is this is also same that is DP of I should be I and this will become DP of I minus the particular square number we are at okay now let me go and quickly code this up okay um sorry I was discussing the time complexity so for I up to root n and let's say in our Loop will be from J is equal to 1 that is explore all the possibilities up to root 10 from recursion we know we have to go up to root n only because all the values after root n are of no use to us correct so this will be operating up to root 10 number of times and this for n number of times so the total time complexity becomes n root n right and space complexity will become biger of n because we are using the DP array now let us go and code this up right so let me do the very first thing that is declare my DP AR all right and it will be n + one size AR all right and it will be n + one size AR all right and it will be n + one size and initially I'll keep every value as zero and I'll explicitly write here although at zero index we already have zero value but DP of 0 should be zero this represents our base condition of the recursion now I'll start iterating as I said iterate from int I is equal to 1 I less than equal to n and I ++ then 1 I less than equal to n and I ++ then 1 I less than equal to n and I ++ then do what initialize DP of I with the maximum value the max maximum value can be I that integer itself and then we'll iterate in J is equal to 1 all the possibilities and the possibilities exist up to root n right so J into J less than equal to n and we have to Simply do j++ here after that the whole Simply do j++ here after that the whole Simply do j++ here after that the whole thing is same as that of recursion so we'll first calculate in square and the square will be J into J this time and we have to calculate okay we can only see here we are dealing with Index right so to make sure that we don't go out of pounds we have to check if um IUS Square value is in bounds right that it is it should not be less than zero correct so I will simply check IUS Square should be greater than or equal to zero only then we have to calculate DP of I right which is minimum of the previous value and 1 plus if we consider this Square what is the minimum number so that we will get from I minus if we remove this Square from this all right so that is the whole Logic for it and let me quickly go and return DP of n here right so that is the whole thing and now let us run this so it's accepted so this is basically how you have to solve this question
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
1,335 |
hello friends today let's show minimum difficulty of a job schedule so we are given a list of jobs and we want to finish it using d-days finish it using d-days finish it using d-days we have some construct constraints the first thing that we must divide these drops in the order so that means we cannot for this example cannot conduct the job of six and one in a day and conductor 522 in our day we must conduct in the order so that means we must finish its preceding previous jobs in order to conduct the current job and it says we have to finish at least one tax every day so that means if the d is greater than the length of the drop difficulty array we cannot finish it we just return negative one okay so how to solve this problem actually it just asked us to divide or partition this integer rate into d parts and the maximum within each partition the sum will be the minimum we want to calculate minimum so how to do that um typically for this want to calculate the minimum or maximum we want we will think about dynamic programming but what is the relation how can we get the uh relation or the formula to calculate the dp let's see we'll see if we can make sure that all the jobs can be finished within d days then we can also finish these jobs in d minus one days demand is two days till one day why because as we can cut it into d partitions we can also cut these drops into d minus one partition for example if d equal to three we can divide these drops into three days we character like uh two uh twice and then we partition these jobs into three parts but we can also cut six jobs once and position these jobs into two parts so on so forth so can we use the previously calculated values in order to get the following values of course we can let's see how to get the relation between them well let's see regarding these days if we already know the we want to finish some tasks within the i plus one states so let's say if we want to um like conduct like five tasks during this day then we must calculate the maximum difficulty within these five tasks and we plus the like uh the rest tasks we conducted in the previous i days right so we must calculate uh like um during previous days the minimum difficulty to finish the k tasks so in that case on the i plus one states we just needed to calculate the maximum difficulty and the use previously calculated results so let's use some specific notations so if we finish k tasks in the previous i day i days and we already got get this value so in the i plus one stay we have to conduct a k to the j tasks and we calculate the maximum of all these tasks and we plus this minimum so this one so in that case we can get the dpi plus one j that means we finish jtags within i plus one days if we can if you can understand this relation then the whole relation or the whole formula we can get it now so we can define a dp array dpij that means the we finish j jobs are within the i days and that's the minimum difficulty so the relation is that we finish k minus one jobs in the i minus one days and the yin on the i stay we finish k2j jobs so we just needed to calculate the k2j jobs minimum oh sorry maximum and plus previous calculator result so as you have a feeling that first we need to iterate the days from one to uh d right or from actually from zero to d um and then we needed to like do the j right because this is the j uh so the j should be from i to an n is a number total number of the jobs so why from i because we at least finish one task within a day so it at least will be i and then we how to get this k is this k from i2j or from j2i so the div difference is one the case from smaller to larger the other alternatives from larger to smaller we choose the uh following one or we choose the later one we let this k from larger to smaller from j to i why because if this k from j to i we are sure that we can get the maximum difficulty within the task k2j so we can get that value and we can use previously calculated value which is dpi minus 1 k21 so that's the reason why we start this k from j2i because in our case we are sure that we can finish this k2j task within the i stay and we get this maximum so you should uh pay attention to this order so we get the relation but we also uh notice this initialization the initialization that we finish all the tasks within the first day we can always do that so that means the 0 db 0 j from zero to and n is the total task there will be their maximum difficulty among these j jobs so this is inner initialization this is the relation okay now let's write the code you will understand it better so first we will get and which is the job difficulty actually we i will change this name to jobs so that will be drop stolens a quick check if d is greater than and we just return negative one because we cannot at least finish one task within a day then we will get the dp which will be the size of d and um so do the initialization for into i start from zero i less than an i plus okay so we need the maximum till now so we call it max o the first it will equal to zero and then we update this max or that will be the max or in the jobs drops i okay so dv zero i will be the max or right this part means we finish all the jobs on the first day then we will get the other part so it will start from one because we already calculated zero it's i less than and i'm sorry it's not an sd i plus and then the j right the j will from i j less than j plus now we also need the k and i say the k will start from j and the k greater or equal to i k minus so let's see uh here right here we need the two things the things is that the minimum actually it's the minimum because we will update the dpij here that will be the minimum so what is the initialization value initialize the value that means we actually this is i the i stay right so we finish all the j minus one jobs uh on the previous iman's one days so on the i stay we only do these jobs j so there will be one possibility this is one possibility but if we conduct a more than one job within this i stay we should get the maximum difficulty within all these tasks we conducted on that day so the maximum will first be dropped j and when we move this k we can get the max right again the max within the jobs k so we can update the minimum right this minimum will be the mass minimum so how to write here that will be the use the previous i minus one days to conduct i minus 1 works and gets this maximum oh sorry plus this maximum don't forget so you should understand this part deeper means that we can learn more than one jobs on this i stay so in the end just to return dp uh that would be d minus one and a ninth one okay i think we have finished okay thank you for watching see you next time
|
Minimum Difficulty of a Job Schedule
|
maximum-candies-allocated-to-k-children
|
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`).
You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`.
Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`.
**Example 1:**
**Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2
**Output:** 7
**Explanation:** First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
**Example 2:**
**Input:** jobDifficulty = \[9,9,9\], d = 4
**Output:** -1
**Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
**Example 3:**
**Input:** jobDifficulty = \[1,1,1\], d = 3
**Output:** 3
**Explanation:** The schedule is one job per day. total difficulty will be 3.
**Constraints:**
* `1 <= jobDifficulty.length <= 300`
* `0 <= jobDifficulty[i] <= 1000`
* `1 <= d <= 10`
|
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.
|
Array,Binary Search
|
Medium
|
907,1886,2000,2027,2188,2294
|
1,372 |
hello everyone so in this video let us talk about one more medial problem from lead code the problem name is longest zigzag path in a binary tree so problem statement goes like this that you're given a root of the binary tree don't worry I will show you with an example as well but a zigzag path for a binary tree is defined as a account according to the following conditions choose any node in the binary under Direction left or right then if the current direction is right then you'll move to the right side of the current node otherwise you will choose to the left node lifted now change the direction from right to left or left to right at every node and then repeat the second and third process until you cannot move more inside the tree now the exact path is defined as the number of node visited minus one cool and return the longest zigzag path contained in that tree you just have to return the length of it so let's take this as an example what you can see here is if I take this what you can see is that if I start from here I will first move if I'm first moving let's say right then I have to move left okay but this is of length 2 only but what you could have also done is that if I start from this node I will move to the right then left then right then I have to move left so there's nothing so the total industry and that is the maximum length of zigzag path you can do over this trade so you can start from any node you can end it any node depending just the condition that you have to make the longest path okay that is the pump statement for this particular problem now uh so what you'll actually have to understand is that the constraints are pretty large started your phone so you cannot do this in a very Brute Force way for every node find out what is the largest uh length of the you can say uh zigzag path from that portfolio you cannot do that so in that scenario what you can see is that I have to somehow store some value now what is the value I want to store the value I need to store here is that what is the longest path I had made for a particular node such that and what is the node I want to go to next if I have reached here let's take some small examples to understand it more clearly let's make this node only or let's make this tree or just uh okay let's make the streets more so that it will become more clear so this is the tree right there so there's some here and there's some node here like this okay so we have to somewhat store some value and that value will be what is the maximum let's say path I have created till this node okay that's the whole idea let's start from the very first note okay just leave for the very first one if I just go to the very right I have landed on this road if I have landed on this node let's say I go to this right I'm going to right of this particular node so I have done one length of traversal and I have landed reaching this by right by doing a right move so what it eventually means that for this particular node I have a maximum length of one and I've reached it by going the right now I have two options for this person node if I go on the left of it so if I write then if I go to the left of it what it means I am moving the zigzag manner so the length will become too just try to fill these values for this particular tree if I go to the right left hand side my zigzag path will become of length 2 and I have reached there by going to a left because I am going to the left what but if I want to go this path this is invalid because I have to somewhat make a zigzag path so there are two cases either I will follow the zigzag path like this and you have these values which are giving us the length or if I go in the opposite direction which eventually means that I will start from this node if I start from this node and I am going to the right hand side what it means that if I am going to write inside this is of length 1 and I've reached this node by traversing one on the right hand side I hope you understand what I'm trying to build here so what it eventually means that if at any node I have two options if this is right on the left side I will increase the value and make it just switch it I will make it left and if I go in the if I land on the right direction node like if I land on the Node which I'll write and if I go to the right again I will make it one again and I will make it right again why because now I am assuming that this is the node I will start from I'm starting from this node and I'm going one step on the right and I've taken this right path so this is one of the lengths that I've created and this side this I node I've landed by doing one right path now if I go to the very left I will do the same procedure if I want to go if I have let's say r on this node if I go on the left hand side I will Mark as increase increment this value I will make it left now if I go to right hand side I will again make it one hour now from left again I have two options if I go on the left hand side or let's say if I just reverse it if I go on the right hand side then again I am following the zigzag path so I will again if I land on the left side I will make it 3 and make it r but if I go on the left hand side which means that I have taken this at the very first node then this will of length one I have blended oil and I've landed it through our left path I hope you understand how this complete tree is somewhat building and how I'm using two values for every node what is the longest value I can reach by doing a zigzag part to this particular node or what is the path what is the let's say Direction I have landed this note from I have landed this node from a right doing a write let's move so I have to next do our left move test so that is how you can just do a let's say compute tree and whatever is the maximum value among all of them because this is how you will building a tree and you have this value whatever is the maximum value you will find out here you can just create a global variable to store this maximum value you can just print it out I hope you understand what is the order ID that used to use to particularly solve this problem or and that's the order letter that I have also used let's take this small example understand all of that let's move on the code part now actually so if I just show you the code part what we have done is that we have made a global variable that is Maxi that is throwing out the very maximum value among all the parts so whatever traversal I will do whether it is this tree this so I am just doing a single traversal of this trade depending upon whatever node I have to just Mark out this lnr okay so I will just do a single transfer with this tree and whatever the maximum value this is the first value I'll just store it in Max it okay so what we have done is that if I just go a little deep I just put this here but I will just make this up now what you can see here is that what we have done is that we have called this function so from the root so if I have two options let's say if I go on the right hand side if I'm going on the right hand side I will call this recursive function that will just do the Traverse of this tree so if I am going on the let's say right hand side so right hand side then this is the next value and these two values are these two values so the very first value will tell us okay so I have learned this okay reversed okay so this is the length whatever the length I have traveled maximum to reaching this particular node that is this length and is the direction so I have taken 0 as the left and right as 1. so I have gone to the right direction I have reached this node going to the very right by doing a right traversal so I have then r equal to 1 so which means that direction I've reached this particular node by doing one which means that I've reached here by doing a right move similarly I can call this because of function again for the left hand side of the tree as well going to the left hand side I have done one traversal so the length is equal to one and I have reached there by going to the left Direction so this is zero so I've called this recursive function twice and I've returned the maximum that I have found out by doing uh the cursive function because of traversal and finding out the max okay now for every position if I have reached the very node like uh like the end let's say you can say Leaf node and return null or let's say later because I didn't void but now and if I have reached any particular intermediate node I will first find out the maximum of this particular length that is here what is the maximum value I have 5. till now that is here studio now for every node depending upon its direction I have to move do to like recursive false like so let's say depending on the direction I will because I'm doing a traversal okay over this complete tree so I will go left towards left right over every tree every let's see what value so how I will do it how I will fill this value will depend upon the direction means that this direction this l or I so if let's say I land upon r means that this is one so I have Direction left is equal to 0 and right is equal to 1. so if else which means that the action equal to 1 which means that I am right then if I am right then what I will do is that if I go on the left side of the tree left side of tree I will increment my length and I will change the direction like from left right and so from the from our node of right okay and if I go to the right hand side I will not change the direction and I will make it as one similarly if I'm on the left node which is let's say having a value let's say this 2L so if I go to the left hand side okay so then if I from left as you can see from left if I go to the left hand side then I will not change the direction and I will make it as one but if I go to the right hand side then I will change the direction and make my length plus one okay this is the overall idea that you have to use depending upon what node I am on and what direction I want to go next deep down your tree and then this will just build these two values for all the node values and I will just maximize it over all the values and that's so this is just a traversal over this whole tree so this will do one Traverse so this will do one traversal which is like o of N and O of n but still it is O of n Only the because if you just add both of them it is still open so that's the overall tank option for this particular problem as well and if you still have any doubts requirements on in the combox for this particular video I will see you in iPhone decoding and bye
|
Longest ZigZag Path in a Binary Tree
|
check-if-it-is-a-good-array
|
You are given the `root` of a binary tree.
A ZigZag path for a binary tree is defined as follow:
* Choose **any** node in the binary tree and a direction (right or left).
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction from right to left or from left to right.
* Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return _the longest **ZigZag** path contained in that tree_.
**Example 1:**
**Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\]
**Output:** 3
**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right).
**Example 2:**
**Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\]
**Output:** 4
**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right).
**Example 3:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 100`
|
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
|
Array,Math,Number Theory
|
Hard
| null |
105 |
That hey guys welcome to taste mulayam nivedita and in this video we are going to solve the problem statement of construct mind retreat the giver is here you have been given a pre-order of binary tree these pre-order of binary tree these pre-order of binary tree these orders have been placed ok and you have been told that You order these two pieces, what you have to do is to form the bandages, okay then how will you construct Vindictive, first we will see okay, then whatever approach we will take, we will construct exactly like this, we are going to code like this, okay Then our bean will remain, first we will see how we can construct first, okay how can we build Minditzok, what have you given, your free mode is on, what have you given, pre-order okay, given, pre-order okay, given, pre-order okay, thanks, that is enough. Now what can he see? What is this man? First there is your note, fraud is on the left side, then there is the right side and what is your favorite left and right side. This is yours, so here is what to do now. From these two, the binary tree which is the original point, this is yours, this is your favorite order, this is the inverter, what you have to do is you have to make bi-repeat and give it, okay, so make bi-repeat and give it, okay, so make bi-repeat and give it, okay, so how can you solve this problem, how can you celebrate the tree, okay? First, from where will you get the note, here you will get it through pre-order, from where will you get the note, here you will get it through pre-order, from where will you get the note, here you will get it through pre-order, okay, so first how will everyone's route be made, the first route which will be the first element will be made from this, then let's contact here that it will be yours, I am now on the left of the second one. What will be made, okay, where will we see what will be made on the right, we will see this from the inverter because what is on the left side of the note and what is in the art, from where will we know, you will know from these orders, okay, so three, we, I, you, first or Then you have to find out what is the free here, what is the nine in the last of the tree and what is the phase to the right of the free, then you came to know that in the last of the three you are going to have only nine and your shifting throat is going to be in the right of the second. The one is the one and the second one is okay, now who will be here in these days, which note will be that, I will see next okay, then we will come, its three is done, what will be our next note, what will be its nine, okay now what will be the not on the left of the nine? How will you know what happened on the right? You will know from this inverter that if you are looking at this then you have to look at the note, there is nothing on the left and the latest in the tap is 315 in its diet, so look at the ad, this is the nine of this. Know the position here, nothing happened in this line or Naukri left and from the right of nine, Mithlesh to 200, all the advanced ones are to the right of this, here you will see that to the right of this line, all of them are fine. We will need to add this, then we will come to twenty, okay, so one, now here we will see what is on the left of twenty, what is on the right, we will come here, see friends, here in the last of the ante, your nine is 315. And the sediments on its right, what will happen to you here will be twenty and on the right of this, you have a bath but there is no fee, so we will make the phone here, so okay and what will happen to the right of that, you are going to be consumed, okay, the sum is formed. Now let us look at what will happen in Vipin's last, what will happen in his height in feet, where will we get it from the inverter, we will go after feet and take the height in feet is ninth and in his last there is ninth and in his right 20170 is ok so let's see. What is your 3rd in the last of Ko, but what is your 3ed in its right side, which is your sever in the right side of the house, this is right, let's go right, then next near superstition seven, now I will go near one, we will see what is there in seventh class and art. What is there in the seventh along with it is in the loot itself for as many minutes as it is on the left, so if we take the seven, look here, it is at the end of the seven and on the left, it is okay with all the notes, so this has become our entrenchment, so okay, it is the root note. In his NET chapter note add this ride is 2820 so there is a different selfie admit bell essence this is on the right side left ventricle left 56001 what is blind alarm set up saver here also there is rice or ka became now how will we do all the code Now what will we do in the cord, what will you do, here first of all we will make a fruit note, neither will the root become fat, it will be a healthy element, nor will it be a pre-order, what is going to healthy element, nor will it be a pre-order, what is going to healthy element, nor will it be a pre-order, what is going to become of you, a root note will be made, what will we do from here, the root We will make a note, we have made a root, now the element of the next intake, what will we do with the element of the next index, we will find it from here, we will fry it in this add, fry it here, we will fry it in this add, okay next, what is yours, what will you do with the skin first, this note Is it your right? First of all, this week, we will look for it, we will fry it, we will find it here in these wards, then this is my position, we have found it, okay, its position is here 0121, okay, whoever will be on the left of it on this side of the forest. Whatever will be on the side will be on the left side and whatever is here will be on the right side. Whatever will be after this index will be on its right. We have come to know from this, so what will we do here, will we make free vegetables, will we make vegetables, what will we make here? We will take it, we will prepare the vegetables, what will happen in its stomach, what all tricks will be there in its night, what vegetables will we make, okay, we have made that, now what will we do, then look for the next element, look for the job, look for the oak no, so here nine where Jhalsa position. We will find it, we will make it completely white, along with finding its position, what will we do, its meaning is day full of enemies, nothing will happen from the enemies, it will be null, okay here it will be yours, it was already made in the last which Now what will be the channel in this collect, there is no tap, it is going to have all these notes in its right subri, so Noida, all these right subs are free, it is tight, now then if you search for half an hour, you will see an opposition, this You will find the position, then what will happen from this position, this will become a vegetable on the left here and this will automatically become on the raised side, okay, after this position, we will look at the food and understand it well. Okay, so here we will come, write what? We are going to show the deposit of what we have done, first of all, here all the elements will be noted in the order in these wards, they will be noted in the same manner, the size of both will be there, so here we have checked the friend, is this a laddu request? He must be sure that you will stop the turn somewhere, okay, now after that we are making constructive, constructing here, treat this function, hit call, here we construct the battery, okay, search Google, here is what we have done. Tax Governments, for one thing, we have taken that we take bonus from zero and what is this, see here what is this, I mean this is the starting index, this is Indian injection, okay this is stick and Indian, so we will see here that on foot you will check, I will give you You are doing it here, you are walking from here, you are looking at the light again and all the notes till now, then you are looking for this note here, this is what I do here, then what should I do here, love is the subject and right in everything. According to the position where you are getting the position, you make all the notes which are in the last part of the position as black and the ones which are to the right of it, you are making them after rights issue as white. So here you will see what you will do is this starting index. And it is in English. Okay, so till the time this is your great day for starting index, let's go from here or from here and till Inter, then see, it will be a problem, it is okay if it is formed, at that time people will do the work by tapping. Okay, now after that we will create a root note, here we will create a root note, how will the root be created, the first element of the free mode on will be created, so on starting, we have started with Physio here we have created another root from the duty element. Okay, I have prepared the roti, I have just added a plus, now your daily position has increased, now due to Jyoti's virtue, you will save the point of the Parliament, it is tight, so whatever it is intact, next three four, that's why we have put a plus here, okay, now what can we do? Now we have to find out which position it is in these orders. Okay, so we have taken someone from the net who will find only one position and give it to you. Okay, so here we will check from the starting index to the ending injection. Okay, that these The order has been hidden, we will check if there is anyone on the route, if so, what will you do now, I will point his position, write it down and break it, from here you are done, what do you want to get, his position has been found, now we What will we do? Here, by using this question, what will we do and we will make safe vegetable and we will make right vegetable, then relax, really, what will you do, we will go to the starting index and from the position till minus one, it was till before that we will take till minus one. All the ingredients are taken right till minus one. Now we have to make the last salute to night sweet dream. What have we used the notification here also? This is in inverter and night safari but what will happen from this plus one to indigo index level? Here we have taken this plus one that I have taken light so this is done, your Rajdhani Night has become vegetable and what has become of you is like safari has become and here we have used reaction so this time- What will happen to you sir, when will the time- What will happen to you sir, when will the time- What will happen to you sir, when will the final go in, what will we do, will we return route, ok so this is our code, we complete the course, after hearing this, we submit it, quote that the system will die, it is also taking time. that no one thanks you
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
1,281 |
all right so we got another leak code for you here uh this is 1281. subtract the product and sum of digits of an integer all right so it says given an integer n return the difference between the product of its digit and the sum of its digits so basically they're going to give us this integer here um and then we are going to uh get the product so multiply them each digit and then we're also going to get the sum so add each digit together and then subtract those two like this so i think this should be fairly straightforward um we'll see i got a way to do this with uh reduce i don't know if that will be uh the fastest possible way but let's uh check it out so the first thing we want to do with the end here is to um split it up so make it a an array here and uh in order to do that we have to turn these uh the n which is a number right now into a string so let's say let str and then we'll say equal to n dot string uh n dot uh two string like that and then we're gonna split that up like that and we'll just split it at each number like that all right and then what we're gonna do here is we're gonna get a multiply and a add and then uh in separate variables and then subtract the ad from multiply so how we're gonna do that is like this we're gonna say let multiply like this and we will say str dot reduce so this is the reduce function in javascript and we're going to say a and b like this and then here we're going to return uh a times b but in order to do that right now we have them as strings so we've got to turn them into ins again so we're going to say parse int like that and that'll be of a and then we'll say it times and we'll say parse int let's uh move this over oh no that won't work of uh b here like this all right maybe i'll make this a little smaller actually so we can see this hopefully you can still see this uh parse end of b like that and that is going to be our multiply now if we copy this down here like this we can change this to add and we can change this to uh addition like this and hopefully when we return down here like this and we will say multiply minus add like this all right so hopefully this works let's check it out all right so that was accepted and let's try submitting it all right so that looks like it worked and it wasn't uh super slow it says faster than 75 of uh these submissions so that seems good and i'll see you in the next one you
|
Subtract the Product and Sum of Digits of an Integer
|
can-make-palindrome-from-substring
|
Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5`
|
Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome.
|
Hash Table,String,Bit Manipulation,Prefix Sum
|
Medium
|
2165
|
48 |
everyone welcome back and let's write some more neat code today we're given an n by n matrix so this time it's a square matrix for sure representing some image and we want to rotate that image by 90 degrees clockwise and we are required to do this in place so we cannot allocate more memory we can't just make a copy of the matrix and rotate it like that so the challenge here is definitely doing it in place you can see that they had a original matrix like this what they did is they took the one and put it over here so 90 degrees basically what they did is took this entire first row and moved it into the rightmost column right and so they did that by moving this over here moving this 2 over here moving the 3 over here and so the problem is when you're moving this one over here you have to save the three temporarily right so you just save the three or once you move this one over here you can take the three save it and move it over here and we know that this entire right column is going to actually be put in the bottom row so what is actually going on is this 9 is actually being moved over here right that's where it ended up in the result and then this seven is being rotated over here so that's where the seven ends up the one ends up over here the three ends up over here the nine ended up over here so these four let's say have been rotated so far so now we don't have to touch them but you can see there's a little bit left in the outer layer so let's just worry about the outer layer so far we don't have to worry about the 5 but in the result we know the 5 actually doesn't move you know you rotate it but what about this four now it's basically the same thing that we did over here right we are rotating this so basically we can think of it as being in the top left right let's the original square we were rotating was like this now the square we're rotating is like this it's still technically a square you know if you turn your head a little bit but this is what we're doing we're rotating this so this 4 is of course going to be moved over here to this two and then and before we get rid of the two we want to save it and move it over here to the six and so in the original we have a two over here but we know that 2 is going to be rotated right because this is the rotation we're doing and before we get rid of the 6 we want to save it in a temporary variable and move it over here replacing the 8 but we don't want to lose the 8 yet because it needs to be rotated as well it's going to be rotated over here to this 4 and since we rotated the 2 we know there's going to be an empty spot over here for the 4 to be placed in and that's what you have over here the four the two got moved over here the six got moved over here and the eight got moved over here so this is still a rotation and lastly we just have a one by one we know that you know it can't really rotating it will just be the exact same so let me show you the general algorithm to solve this problem we're going to do this in n square time meaning we only have to look at each cell in the matrix once remember the dimensions are n by n and we don't need any extra memory so the memory complexity is going to be constant we're doing this in place in our given matrix so i like to set some boundaries so we know that this is our left boundary and this is our right boundary initially because we're going to rotate the outermost layer first right the outermost square and then we're going to move inward right we're going to do the inside of the matrix and the top boundary i'm going to place over here because that's the top remember the origin over here is zero by zero this position is three to three it goes like this and as you go down it increases and the bottom boundary is going to be down here so immediately we're gonna start the rotation now how is the rotation gonna go well let's start at the top left because it's the easiest right we know that this is the general rotation that's gonna take place right because we're going clockwise and then we're going to do that right and we know we're going to keep doing that with every element in the top row so we did the first element in the top row then we're going to rotate the second element in the top row and how is that going to look well it's going to be pretty similar so since this was the second position in the top row we're going to move it to the second position in the last column right so in this column we're going to rotate this one to this position so the second to last position in the bottom row the main thing to notice though is that this is offset by one from the top this is offset by one to the from the right and so the position that it's moved to is also going to be offset by one from the bottom which is where the last rotation took place and then this is going to be moved over here and so as you can see we have one last rotation to make right with these four elements and they actually do form a square if you tilt your head enough this is a square rotation a matrix rotation but notice how since we already rotated this one we're actually not doing four rotations for the outermost layer we're doing four minus one rotations we're doing three rotations right so even though the outermost layer was n by n we actually did n minus 1 rotations right so we did three rotations and let's say after we complete the outermost layer right let's say we've completely rotated that you know we had to rotate this part and this part so once we do that then we know that we actually have an inner matrix that we have to do so we did the outermost layer but now we have to do the inside how am i going to handle that well it can actually just be treated as a sub problem because we know no matter what it's going to be a square matrix so all we really have to do is take our pointers and then shift all of them by one so our left pointer will be shifted here our right pointer will be shifted here our top pointer will be shifted here and our bottom pointer will be shifted here and so now the last rotation seems pretty obvious right it's so it's going to be one rotation it's going to include four elements and then we will have our result now one last thing i wanna show you and then after that rotation has taken place we know we can update our pointers one more time but at this point what we'll notice is our left pointer is over here and our right pointer is here we know that left should always be less than right and since these pointers have crossed each other we know that we can stop the algorithm right we don't really have a matrix left to rotate one last thing i want to show you about the rotation is we know that the five the top left is going to be put in this position right the 11 so we're going to cross that out so we're going to really replace this with a 5 but then what happens to the original 11 that was placed here well what we can say is oh let's move the 11 to a temporary variable and now let's put the 11 over here so we're putting an 11 over here now but what happened to the 16 that was over here well we have to put that in a temporary variable a 16 and then move that 16 over here so let's replace this with a 16 but what happened with the 15 that was over here well we move that to a temporary variable and now that temporary variable 15 is going to be placed over here so the 15 is here and we don't have to move the 5 to a temporary variable because look we already put it over here so we're needing a lot of temporary variables i can show you a slight improvement to this which isn't required or anything but i think it makes writing the code easier so we know that this 5 is going to be rotated but let's do this let's do the rotation in reverse order so instead of removing the 5 over here first i'm gonna take the 15 which we know is going to be placed over here and i'm going to put the 15 over here and i'm going to move the 5 to a temporary variable okay so are we going to move the five over here now nope that's not what we're going to do this in reverse order so since the 15 has already been moved let's take this 16 and move it over here so now let's replace this 15 with a 16. and now we know that we need to make a rotation from 11 to here so let's put an 11 over here and last but not least we know that the original five had to be put over here and we stored that five in a temporary variable so now let's move that five over here and so we did the exact same rotation but do you notice how we did it in reverse order right we went counterclockwise and the thing that the reason that was helpful is we only needed one temporary variable which will make the code a little bit easier for us but it's not actually required the overall complexity is still the same the memory and the time complexity is still the same so now let's get into the code so the first thing i'm going to do is set our left and right boundaries so left is zero right is going to be the length number of columns minus one but we know that the number of columns is the same as the number of rows so we actually don't need this and i'm gonna run our rotation while left is less than right and i'm going to go from index so let's say we're in our top row i'm going to iterate through the entire row except last element so how many rotations is that going to be that's going to be from left to right minus one or in other words we can say from in range right minus left so this is the number that we're gonna do so if left was zero right was three we would do three minus zero which is going to be three iterations even though we have four uh values in our first row so i also wanna have some top and bottom pointers and these are actually gonna be the same as left and right so top is gonna be the same as left and bottom is going to be the same as right because we do have a square matrix it's not just a generic rectangle it's definitely a square and the first thing i want to do is save the top left value right because the way i showed you the rotation we only need to save one variable so it's the top left i'm going to get that from our matrix so matrix of top left and just like in the drawing what i'm going to do is move the bottom left into the top left so in the position of the top left i'm going to move the bottom left into that spot the next thing i'm going to do just like in our drawing i'm going to move the bottom right into the bottom left we are doing this in reverse order basically even though the rotation is clockwise the direction we're going is counterclockwise so the bottom right is going to be moved into the bottom left we also want to move the top right into the bottom right so in the bottom right position we're going to replace it with the top right and the last thing we have to do is move the top left into the top right but remember we overwrote the top left position but good thing for us we saved it in a temporary variable in the top right we're gonna replace it with the top left there's just one thing we forgot to use so we forgot to use our i variable so you remember how this was the first rotation that we make right and then we move from our top left position we move one spot to the right from our top right position we move one spot down from our bottom right position we move one spot to the left and from our bottom left position we move one spot up and then we do a rotation from here right and then we're not done yet from there on we move another position to the right another position down another position to the left and another position up and then we do a rotation from these values so we can actually handle this pretty easily in our code we can use this i variable to handle that for us so we can add the i value to the left index which will shift us one position to the right and this is also the top left position so we're going to add i to this as well this is the bottom left position and we know that we can subtract i from the bottom which will shift us up by one and this is that same value so we're gonna subtract an i from that as well this is the bottom right and to shift that to the left we can subtract i from the right index and this is actually this is also the bottom right so we're going to subtract i from that as well this is the top right and as we uh continue doing rotations we're going to add we're going to move down in this column so we're going to add i to the top index and this is the same top right so we're going to add an i to this index as well so basically as i is incremented it's going to be handling more and more rotations it's going to shift these cells that we want to rotate accordingly and so this will basically perform a layer of rotation so after we've completed an entire layer what are we going to do we actually need to do one last computation we need to update our pointers right because now we're going to do the sub matrix so our right pointer can be decremented by one our left pointer can be incremented by one and that is the entire code so it's going to complete every single layer once every layer has been completed our loop will stop and we are not required to return anything like it just says over here we're doing this in place inside of our matrix so we don't return anything this code is good to go and as you can see it's pretty efficient about as efficient as you can get for this problem and i hope this was helpful i hope it showed you a relatively easy way to write this code but you also understand what's going on if this was helpful please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
1,007 |
what's up guys how's it going today we're going to be going over another interview question today our interview question is called minimum domino rotation for equal row and this is the question that's currently being asked by google right now okay guys so today the interview question we're going to be going over is called minimum domino rotations for equal row and right now as of late february 2020 this is actually the most frequently asked question at google according to lee code so this is a really important question to know and our problem description says in a row of dominoes a i and bi represent the top and bottom halves of the ith domino a domino is a tile with two numbers from one to six on each one on each half of the tile we may rotate the ice domino so that a i and bi swap values and they want us to return the minimum number of rotations so that all the values in a are the same or all the values in b are the same and if it cannot be done they tell us to return negative one okay so we're given basically uh i guess they tell us i think in the notes yeah they tell us that we have six dominoes or between one and six dominoes and we're basically asked to make all the values in the top half of all those dominoes or all the values in the bottom half of all those dominoes be the same and if we can do that we want to do it in the minimum number of swaps possible where a swap is simply flipping one of the dominoes where a i and bi or the top half and bottom half values just swip swap so in our example here example one they give us this nice little diagram and if this was our input meaning that this these are the values of the top halves of the dominoes and these are the values of the bottom halves of the dominoes we'd output two and the reason for that as we can see in this diagram is that this is the original configuration of our dominoes here we could swap the second domino and the fourth domino have them both turn right and that would allow our top half top halves of all the dominoes to have the value two which is what we want here and that is the minimum number of swaps uh that would allow us to create you know a set of dominoes where the top half all have a specific value or we could have done it so that the bottom halves all have a specific value but that would have taken more swaps so we don't want to do that and they tell us here that the explanation is the first figure represents the dominoes as given by a and b before we do any rotations which is what we just said and then the explanation at the bottom here says if we rotate the second and fourth dominoes we can make every value in the top row equal to two as indicated by the second figure which is again what we just reviewed so we'd return two here because that's the minimum number of swaps that it takes for to configure the dominoes in such a way basically that all the values in the top half have the value 2 and that's minimum in this case for example 2 here these were our values so again we have well now we have 5 dominoes and these are the values of the top and bottom halves respectively a and b we'd output negative 1 and the reason for that is there's just no possible way to make any swaps so that the top half of all the dominoes have the same value or the bottom half of all the dominants have the same value and they tell us that in this case it is not possible to rotate the dominants to make one row of values all equal and just as notes here we're told that a i and bi will always have values between 1 and 6 inclusive okay and then we're also told that the length of a and b is always between 2 and twenty thousand inclusive so we could have between two and twenty thousand dominoes so with that being said how do we solve this i think the key to this problem and the important thing to realize is that regardless of how many different dominoes you have there are only so many different possibilities that we can try right there only there's so many limiting factors so we actually think about this problem here right that we're given with this diagram we could have had twenty thousand dominoes it doesn't really matter the limiting factor is that we have basically uh four different possibilities right the top value right the top left value we can try and make all the dominoes match that right so that's one possibility we can try and make every single value in a match two right that's one possibility the next thing that we could try and do is we could try and make every single value in a in the top row match b b0 that's two possibilities the third possibility is that we can try and make every value in b match a zero and the fourth value is that we could try or the fourth possibility is that we could try and make every single value in b match b zero so regardless of how many different dominoes we have that's really the limiting factor we have those four different possibilities every single value in a has to match a0 or every single value in a has to match b0 or every single value in b has to match a 0 and finally every or finally every single value in b has to match b 0. so once we realize that this problem becomes a lot more simplified and it's really not that hard to try and simulate all those four different possibilities so what i'm going to try and do here with this problem is i'm going to first write the code that will simulate those permutations or those possibilities those four different simulations really and from that we're going to return you know like what would ever give us the minimum number of swaps if it's possible to do that so before even writing this helper function i just want to flesh out what that structure would look like and then we'll go and write the helper function that'll actually help us determine how many number of swaps we need to actually solve this problem so to kind of sketch out those four different possibilities we said the minimum number of swaps right so in min swaps we're going to say is equal to math.min we're going to say is equal to math.min we're going to say is equal to math.min and now we're going to give those two different possibilities that we just talked about or the first two right so the first two is going to be whatever this function that we're going to write returns so num swaps when we're trying to make a and b both adhere to a0 right that's one value that's one possibility the next thing that we said we could try is what about the number of swaps that it takes to match b zero for a and b right so that's one you know two things that we can compare right so the how many swaps does it take to match all of a with a zero how many swaps does it take to match all of a with b zero and then we could do the same sort of thing but just for the other two right so now we could say min swaps is going to be equal to math.min math.min math.min of whatever our min swaps are currently and the number of swaps that it takes to make b0 as our target for a and then we're going to do the exact same thing except we're going to well first we want to reverse these right b and a and then similarly here for just consistently let's do this so now we've actually gone through all the different simulations of the possibilities that we have right we could say make everything match a0 passing a and b make everything in a match b0 make everything in b match a0 or make everything in b match b0 so now those are the four possibilities and then finally here what we have to return is we want to return if our min swaps is equal to some impossible thing right because we need to account for the case where this is not possible we need to return negative one so i'm thinking we can basically make this function return something like integer.max value if it's something like integer.max value if it's something like integer.max value if it's not possible so if our min swaps is integer.max value let's say integer.max value let's say integer.max value let's say let's return negative 1 and then otherwise we could just return however many swaps it takes so now all that's really left to do basically is just write that helper function that will help us determine how many number of swaps it takes to get to a point where you know whatever uh possibility we're on to make the entire top row or bottom row match that specific target value we want so we could say public this will return an integer meaning the number of swaps that it will take we call this num swaps and we said we're going to have a target value and then we're going to have two integer arrays a and b so again what this is really saying is it's saying how many swaps will it take to try and make a match this target value of a0 similarly how many swaps will take to make a match the value for the target of b zero so on and so forth okay so initially we haven't made any swaps right so you just say int them swaps equals zero and now we want to do is we want to walk through the dominoes and just see if it's possible to actually make swaps accordingly such that we can actually get to you know some number of swaps that it takes to make the entire target uh appear in all of a so we're going to say 4 into i equals 0 y is less than a dot length i plus and now we just want to check if a of i is not equal to the target that we want and if b of i is also not equal to that thing then it's impossible right so that's saying if the target at a doesn't match or if the domino at a of i doesn't match our target and swapping wouldn't help then it's impossible right there's no possible way we can make all the pop all the dominoes match that value so we'd return integer.max value and b so we'd return integer.max value and b so we'd return integer.max value and b of i is not equal to target then we return integer.max value but what if we're in integer.max value but what if we're in integer.max value but what if we're in the case where a i is not equal to target but then here that would mean that bi equals the target well then that's awesome all we do is pay one swap right we have to make one swap and then we can make that row have that target or i should really say the specific domino that we're on have that target so we would just say num swaps plus and so basically if we ever get to a point where we finish this loop that means that we've successfully swapped all of our dominoes to the target value that we want and we would just return the number of swaps that it took to do so now to review this code again wholeheartedly what do we have what we're saying the minimum number of swaps to make the target a appear in all of a mind with the number of swaps it takes to make the target b0 appear in all of a that's initially our number of swaps so that could be integer dot max value if it's impossible or it'll be some number if it is possible then we're just going to say okay simulate the other possibilities to get b to have the target a0 and similarly have b get the value or the target b0 and then once we've you know simulated all those different four possibilities we're just going to return if our minimum number of swaps is not our max value or integer not max value that means it was possible right so we'll return the minimum swaps and if it wasn't possible we'll return negative one so let's talk about our runtime quickly the runtime really is just going to be of n right we could say of n where n is the number of dominoes that we have because even though we're doing this four different times four is a constant right so no matter how big our dominoes are or how many dominoes we have we're only going to try those four different possibilities so that constant doesn't scale with our input so we'd say that this is o n where n is the number of dominoes that we're given and then i would say that the space complexity similarly uh or i guess not similarly but would just be constant right because we just have a couple variables and that's all that we need to solve this problem so i'd say that the runtime is of n where n is the number of dominoes that we're given and say the space complexity is constant row one so let's run this let's make sure that works how awesome it does so guys that's how to solve minimum domino rotations for equal row again this is the most frequently asked question according to lead code at google right now if you guys enjoyed this video and found it helpful do me a favor leave the video like and subscribe to the channel for more and i'll see you guys in the next one me
|
Minimum Domino Rotations For Equal Row
|
numbers-with-same-consecutive-differences
|
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6`
| null |
Backtracking,Breadth-First Search
|
Medium
| null |
150 |
Are Hello Guys Welcome To The Video Serious When Coding Luta Problem Solve Evaluator Reverse Order Situation Half Velvet The Value Of Merit In Expression But Not In The Normal Station In The River Pollution Water Pollution In The Morning Prayers For Simple Language Normal Rate Is That Options and Friends and Family Support Yeh Poochha Phase Mike The Amazing Between and You Have the Number From Z3 Plus Price Giveth But in River Pollution in the Midst RPM First Number at the Beginning The Richest Man in the Number and Operator Name The Place Where the Volume Two Different Ways of Writing Examples for Two Hours Ago That Suppose You Have Another Expression Late Than You 've Told - Two Plus Two It's Normal - 200 've Told - Two Plus Two It's Normal - 200 've Told - Two Plus Two It's Normal - 200 Want to See the Number on the First Person to the Operator - The Subscription for the First Operator - The Subscription for the First Operator - The Subscription for the First Part - 2 Nothing But A 238 383 And After Part - 2 Nothing But A 238 383 And After Part - 2 Nothing But A 238 383 And After 10th Class Science Which Will Give Us This Is Finally Lord River Water Pollution And Yet Another Way Of Writing The Operators And The Right Two Different Things To Problem Solve Problems 12358 Very Simple Example For The Big Problem Know What To Do You like this are you can user data structure of set which is you have the other side verify N X N Problem comes very simple and can cause problems Subscribe now to the number 66 number 90 number 9 that your next be the number three software * Simply book number three software * Simply book number three software * Simply book number three intersect now comes very interesting after this course you hand operator for the first time you have operated In The Volume To You Know That You Are The First Number Subscribe Reverse No Tension subscribe for you The On The Number 90 Result Final Result To Understand You Have Completed After Two Numbers Page Number Subscribe Quelin The Tank Vitamin A Pleasant Surprise Operation And Remove The Number From Distant Asks Result Mixture - Site - Distant Asks Result Mixture - Site - Distant Asks Result Mixture - Site - 1the Take Place To Forward To The Next Operation Per Then Select Operation School With Multiple Equation Science Suite A Top Two Numbers - 11-10-2012 - 11-10-2012 Is Give Numbers - 11-10-2012 - 11-10-2012 Is Give Numbers - 11-10-2012 - 11-10-2012 Is Give - 130 210 Just This Chapter Remove These Two - 130 210 Just This Chapter Remove These Two - 130 210 Just This Chapter Remove These Two Numbers From This Thank You Have To Push - Numbers From This Thank You Have To Push - Numbers From This Thank You Have To Push - 132 Is The Result Of The Number - 132 Is The Result Of The Number - 132 Is The Result Of The Number - 132 Forward This Point To The Next Multiplication Number 6 - Multiplication Number 6 - Multiplication Number 6 - Group Only Device Education - 132 Is Gold Very Group Only Device Education - 132 Is Gold Very Group Only Device Education - 132 Is Gold Very Small Number And Can They Consider All Mo0 And Anywhere 05-10-2013 Values And Anywhere 05-10-2013 Values And Anywhere 05-10-2013 Values And Few Applied Operation C Plus Or Any Rate Language In Just 120 Days To Consider Any To Take Off The World Cup 2010 To Forward The Next Election 2012 Result You Number To Asks Result 2018 100 It is the number at 17-A register number then 100 It is the number at 17-A register number then 100 It is the number at 17-A register number then adjust Pun interest in a plate Pun operator plus what do you 800 just give the result sure to forward subscribe to the Page if you liked The Video then subscribe to the channel Ajay Divided Over 100 M Going to Class for Spring Expedition to Consider All the String Into the Question Is the Dark World Subscribe to the channel Number to the Number You Give What You Want to the Number Two The number to the number two that no what do you take the result of A plus B plus 3 will be equal to five member result which you have to push in the so let's taken in a positive step in the positive result subscribe channel Must Subscribe Malik - - Must Subscribe Malik - - Must Subscribe Malik - - Subscribe Number One Day - 2 More Than Subscribe Number One Day - 2 More Than Subscribe Number One Day - 2 More Than 3 - No Which Will Be Given In Place 3 - No Which Will Be Given In Place 3 - No Which Will Be Given In Place of A Minus B Cube Minus Subscribe The First Number From Number Nine Officer Service To Be A Final Note I Have Written Letters For Multiple Equation - And Division Number To Subscribe Notice 102 And Subscribe Is So Friend To Interior Conversations Sdo I Don't Drink And This Function Will Convert String To Intimidate And Vikram Asks Entertainer Set Finally What We Can Do You Can Simply Return Add Topic To Final Result Will Be Eliminated and value in which studied and the top most of the satanic can they stop no residence on then accept thank you for giving special edition
|
Evaluate Reverse Polish Notation
|
evaluate-reverse-polish-notation
|
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).
Evaluate the expression. Return _an integer that represents the value of the expression_.
**Note** that:
* The valid operators are `'+'`, `'-'`, `'*'`, and `'/'`.
* Each operand may be an integer or another expression.
* The division between two integers always **truncates toward zero**.
* There will not be any division by zero.
* The input represents a valid arithmetic expression in a reverse polish notation.
* The answer and all the intermediate calculations can be represented in a **32-bit** integer.
**Example 1:**
**Input:** tokens = \[ "2 ", "1 ", "+ ", "3 ", "\* "\]
**Output:** 9
**Explanation:** ((2 + 1) \* 3) = 9
**Example 2:**
**Input:** tokens = \[ "4 ", "13 ", "5 ", "/ ", "+ "\]
**Output:** 6
**Explanation:** (4 + (13 / 5)) = 6
**Example 3:**
**Input:** tokens = \[ "10 ", "6 ", "9 ", "3 ", "+ ", "-11 ", "\* ", "/ ", "\* ", "17 ", "+ ", "5 ", "+ "\]
**Output:** 22
**Explanation:** ((10 \* (6 / ((9 + 3) \* -11))) + 17) + 5
= ((10 \* (6 / (12 \* -11))) + 17) + 5
= ((10 \* (6 / -132)) + 17) + 5
= ((10 \* 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
**Constraints:**
* `1 <= tokens.length <= 104`
* `tokens[i]` is either an operator: `"+ "`, `"- "`, `"* "`, or `"/ "`, or an integer in the range `[-200, 200]`.
| null |
Array,Math,Stack
|
Medium
|
224,282
|
535 |
hey everyone welcome back and let's write some more neat code today so today let's solve a very popular interview question i've actually been asked this question in a phone interview it's called encode and decode tiny url and the good thing about it is it's actually pretty easy so it's definitely a good problem to understand in case you get asked it in a interview so you might have heard of tinyurl basically it takes a long url and then shortens it for you so in case let's say you had this long leak code url and we would actually convert it into a different url so instead of instead of instead of it is now and it is now and it is now and this is basically the code that we use to decide or to map it to the original url so we want to be able to encode and decode right we're trying to do both so we want to be able to take the original url and then get the new short url and we also want to be able to take that short url and then get the original url from that and other than that there's not really any restriction of how we do this problem so we're actually able to solve this pretty easily so you might have already realized right this is not too difficult right where we want to be able to convert or rather encode and decode from the original to the new one right so the easiest way to do that would be with a hash map right you probably have thought of that we can use a hash map to map these strings and to code and decode them so for example we can have a hash map or an encode map so let's say we're taking that leak code url right that leak code url which is a string right we're going to take that and into that we're going to map the shortened url let's say the shortened url is initially one rather than this uh longer string right so this is a string that's just one and now don't forget we also want to be able to decode the new shortened string into the original string so we want to be able to take one which is the short string and we want to be able to get back leak code right the original url this is all we really need to do now you notice i just put a one here right what's the algorithm we're gonna decide to shorten our urls with right the easiest way is just count so for example the first url we're given is leak code and we can say leak code is gonna be one because it's the first url that we're shortening let's say we got another call the next url we have to shorten let's say is youtube we can just go linearly right in order now youtube is just gonna map to two right that's just it that's how simple it is and every time we get a new one for example let's say we got twitch or something we would say twitch is gonna be three right that's the number it's gonna map to right and you might think well is this good enough right what's the restrictions of this is this solution efficient and stuff well yes it's very efficient right you can see the conversion for encoding and decoding since we're using a hash map is going to be o of one in both cases so this is efficient right but what about other restrictions right for example let's say we had a big one right like let's say we want to keep our url length or extension length 10 digits right you can see this one is about six digits right but let's say we wanted to keep it ten digits what's the maximum number of urls we could shorten then if we want it to be ten digits well we would get something like this right nine right basically ten nines in a row so this is ten nines in a row that's basically 10 billion roughly 10 billion urls we could shorten right this is not something we need to worry about but maybe in a real interview they'll actually ask you s stuff about this right since we're only using numbers we're doing base 10 right so we're basically getting 10 to the power of 10 roughly that's how many urls we could shorten let's say we were using characters and digits we'd get maybe 62 right characters and digits and we'd take that to the power of 10. so in this example you can see they're actually not just using numbers they're using characters we could choose to use characters too but clearly we can see 10 billion is a lot of urls we probably won't need to encode that many but in case we did we clearly see we have an even better solution if we use characters included in our tiny url you know this is basically a very big number we would never need more than this many encodings but either way we can solve this problem without even worrying about this either 10 digits is enough probably and we can code this up now it's not too much code so now you can see the code this is basically we're given a class all we have to do is fill out these two functions in code and decode this is how our class is going to be used it's just going to be instantiated and then it's going to be called you know we can you can call either of the functions decode or encode and we're always going to be given valid inputs so the first thing i want to do is actually set up my hashmap so i'm going to use the constructor in python to do that's what i'm doing with init so i'm going to set up the encode map so it's initially just going to be an empty hash map and the same is going to go for the decode map it's initially just an empty hash map so we also technically need a base url i'll just call it http and right and so basically and right and so basically and right and so basically we're going to append our encoded url to the end of the base every time we update our map so now let's start with the encode function let's say we're given a long url now it's possible that the long url has already been encoded before so we would need to check our map to determine that so let's check so if not if long url not in encode map if it's not already been encoded then we're going to encode it if it's already been encoded though then of course we can return it we can return the encoding of that long url which we can get from our encode map right and just take it convert it and then return that short url but if we haven't done that already we have to do that and how are we going to do that again remember we're just going to be taking basically we're going to start at one and then continue from there so really what we're doing is taking the length of the encode map right every time and we're adding one to it now that's going to give us an integer but we know urls are strings so we're going to convert this integer into a string which we can do pretty easily in python and this is going to be the short url right really it's going to be the short url extension because we're adding base to this so now we have the short url right base plus that self base plus that so we have the short url now let's actually add it to our map so we can take self dot in code map let me actually update that here self dot and code self dot encode okay so self dot and code map will take the long url and assign it to the short url we're going to do the same thing for the decode map we'll take the short url and map it to the long url and with that we actually have completed the encode function right that's it's just that simple we just need two maps and we can convert back and forth between the urls and the decode function now is actually even easier than that because basically we're guaranteed that this is a short url that's already been encoded before right it's just for some convenient for us they're only giving us valid input so all we have to do is return the decoded version so we can say self.decodemap self.decodemap self.decodemap and then basically decode this short url and then return the long url this is really all we have to do because we're always given a valid short url it's always going to be able to be decoded this is it this is the entire solution it's pretty simple you can get more advanced with this problem uh you can take a look there's actually another problem the system design version of this problem and you can definitely explore more design choices than we even covered so that might also be worth looking into but i hope that at the very least you understand this problem it's very common in interviews so hopefully you get asked this problem and you're able to pass that interview so thanks for watching if this was helpful please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Encode and Decode TinyURL
|
encode-and-decode-tinyurl
|
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL.
There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the `Solution` class:
* `Solution()` Initializes the object of the system.
* `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`.
* `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object.
**Example 1:**
**Input:** url = "https://leetcode.com/problems/design-tinyurl "
**Output:** "https://leetcode.com/problems/design-tinyurl "
**Explanation:**
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after decoding it.
**Constraints:**
* `1 <= url.length <= 104`
* `url` is guranteed to be a valid URL.
| null |
Hash Table,String,Design,Hash Function
|
Medium
| null |
1,630 |
hi guys so today's question is medium complexity that is so this has been solved and the number of test cases passes 102 and this is the redeemable complexity quotient so let me take to the proper description a sequence of number is called automatically which consists of at least two elements and difference between Dev of two consecutive elements are the same new formula sequence is automatic if the difference between all the element is same like this is a cosmetic sequence because three minus 1 is 2 5 minus three is two seven minus 1 7 9 minus seven simply seven minus seven is one zero the following sequence is not arithmetic so what I have to do give an example so starting from the left to right means from zero to two index that is 4 6 and 5 you have to save this sequence is arithmetic or not similarly the next query that is from 0 to 3 that is zero four six five two nine if it is arithmetic or not and you have to return an answer so in your mind what you have to do you have to think if you are taking some query so this area is automatic or not so what you have to do to increase their value like to get new query that is 0 to 3 and it will do three times because and then are of the same length and I will add in the list of elements all the numbers right which lies in this query after that I will sort it after sorting it I will iterate the list and see if the I will add all the difference in the set and set value should equal to one because all difference between all the elements should be equal to only one element will be there I will return
|
Arithmetic Subarrays
|
count-odd-numbers-in-an-interval-range
|
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.
For example, these are **arithmetic** sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not **arithmetic**:
1, 1, 2, 5, 7
You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
**Example 1:**
**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.
**Example 2:**
**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]
**Constraints:**
* `n == nums.length`
* `m == l.length`
* `m == r.length`
* `2 <= n <= 500`
* `1 <= m <= 500`
* `0 <= l[i] < r[i] < n`
* `-105 <= nums[i] <= 105`
|
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
|
Math
|
Easy
| null |
352 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem data stream as disjoint intervals this problem is tricky Dicky but it's definitely not a hard problem in my opinion but that's okay because there are probably medium problems that actually do qualify as hard problems that just means that leak code is sometimes inaccurate with the difficulty but we are given a data stream input of non-negative integers stream input of non-negative integers stream input of non-negative integers and we want to implement a summary ranges class we will have a Constructor with no parameters we will have an add num method that will just be past a value that we want to add to our stream now this is the interesting part we're going to have a get intervals method which is going to return a summary of The Stream ranges that we have seen so far these are going to be a list of disjoint intervals each interval is going to have a starting and an ending point and the answer needs to be sorted by the start value which will be easy enough but these intervals the way we're going to Define them is going to be by the contiguous values that we have added so far for example when we add a number when we just add a single one so far we have now a single range that goes that starts at one and ends at one as well when we add a 3 we also have a single range well this is our second range now we have two ranges one to one and three to three so a range can just be a single value these two ranges cannot be connected though because there's a gap between them they are not consecutive we know that numbers generally go in this order one two three four we have the one and we have the three but we don't have the two so we can't connect these we add another number seven and that's going to do pretty much the same thing we're just gonna have seven and then finally we add a two this time the though instead of just creating a separate range for two we know it's not only connected to the one but it's also connected to the three so this by adding a two now we have taken this interval and created a new one which is starting at one and going to three and then we add a six the six will be connected to this interval so now we will have six to seven and when we call our get intervals method these are the two intervals we would want to return this should be a seven sorry if that's not clear but at this point you probably know what we're trying to accomplish the question is how exactly can we do it and how can we make this as efficient as possible well let me tell you a pretty easy way to solve this problem that surprisingly does pass on leak code how about we just have a hash set for all the values that we add and then when we want to actually create the intervals we take this hash set so add num will be running in constant time that's pretty good that's about as efficient as we can get it now the get intervals though we need to then take the hash set convert it to a list slash an array and then take that list and then sort it and then using a sorted list it's pretty easy to come up with the sorted intervals the idea would be suppose given a list like this we would just iterate through it starting at one we'd see okay one what about the next value is that consecutive yep so we have one two what about the next value is that consecutive to two yep so now we have this range and then what about six well six is not consecutive with this so therefore this defines a range one to three and then we start at six look at its neighbor seven yep these are consecutive and we don't have any more values so that's the end of this range so we'd have two ranges so this is pretty easy given the way I talked about but taking a hash set converting it to an array and then sorting it is not going to be super efficient it's going to be n log n so the question is can we do better than that well first of all let me quickly show you the code for this if you're curious this is what the code would look like and it does pass on leeco you can see that most of the functionality is in our get intervals method while we do have nested Loops this is actually a linear time algorithm because we're incrementing i n times but this is where the time complexity comes from sorting the actual list itself but can we do better than this yes we can there are definitely multiple ways to solve this problem I think Union find is a intuitive way you might think of because that's essentially what we're doing with these numbers we're kind of unioning them together and then with those disjoint sets well in this case we have disjoint intervals but a another intuitive way is to use a tree map the intuition behind this solution is that we could actually have an array every time we add a number we'd add it to the array we'd add it in sorted order because we want to preserve the sorted order of our array because then we can easily get the intervals in that case though inserting a number in sorted order yes we could do binary search which is log n but inserting a value in the middle of an array is still going to be o of n in the worst case and of course getting the intervals from that sorted array would still be they go of n so we'd have Big O of n in both cases my argument is that we can do slightly better we can't really improve get intervals but with a binary search tree we can add a number not in O of n but we can get that to log n that's kind of the whole point behind binary trees that they're a bit more efficient than arrays when you want to actually add values to them so that's the idea we'd have a binary tree and we'd add values to it in log n time and then when it comes to actually getting the intervals we would iterate through that binary tree in sorted order which is a linear time algorithm pretty easy to do and then we could build all of those intervals so that's how we can kind of make this a bit more efficient so now let's code it up so while I usually code in Python in this channel we know that python doesn't really have a native tree map so I'll have to switch it up this time actually I won't and python there is a package sorted containers which has the sorted dict and that is provided on leak code and we can use that as our tree map you can see here I talked about it on neetcode.io so that's what we're going neetcode.io so that's what we're going neetcode.io so that's what we're going to start with we're going to have our tree map in our case we actually don't need a map we could just use a tree set but unfortunately Elite code does not provide that so we're just gonna have to go with our tree map in Python it's called a sorted dict and in terms of adding numbers to this tree map it's pretty easy as well we can just take the key which is the value in this case and I'm just going to assign it to true because that's a pretty easy way to do this we're not actually going to use this value it's just to indicate that this value has been added to our Cream app now for getting the intervals we want to build that result output of ranges and we need to be able to iterate through every value in our tree map in sorted order you can do that in Python pretty easily just like this just by iterating through it this will be the key value which is what we wanted in the first place so going through every value we want to know if this should be a new range or this can be added to the previously added range so if it can be added to the previously added range first of all result has to be non-empty first of all result has to be non-empty first of all result has to be non-empty and the last value that we added to the result the last range will be a pair of values and from that pair of values we want the second one we want the ending of that range so we're going to go to index one so this is the ending of that range if the ending of that range plus one is equal to the current value that we're looking at n that means that this value and this value are consecutive therefore we can say to that range the range that we were looking at negative one the last range that we added we're gonna update the ending value of it now which is at index one we're going to update that to be n because we can extend that range a little bit now but what if this is not the case then we know that n is going to form its own range it's going to be a brand new Range so we're going to append to the result this new Range starting at n and ending at n as well and once we've done that for every value in the input we're just going to go ahead and return the result so let's run this to make sure that it works oh whoops I think we forgot to import sword addict I forgot that you actually needed to do that in leak code which makes me think we probably could have used a sorted set as well if we imported that but oh well I'm too lazy to re-record this now maybe you too lazy to re-record this now maybe you too lazy to re-record this now maybe you can do that on your own time but let's run this and as you can see yes it does and while it's not super efficient in terms of run time in terms of Big O run time it's about as efficient as you can get and I think that's more important than what leak code actually says if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a interviews check out neatco.io it has a interviews check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
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
|
472 |
good evening everyone today we are going to do the daily lead code challenge of 27 January 2023 that is question number 472 concatenated words we are given an array of strings without duplicates and we have to return all concatenated words in the given list and what is the concatenated word it is defined as a string that is comprised entirely of at least two shortest word in the givenary let's understand by example what they are trying to say so in the example what they want to say that there's a word called cat there's a word dog and when cat dog or combined it becomes cat dog so cat dog is the concatenation of cat and dog concatenation means adding of words cat plus dog is added to form cat dog that is what they want to tell you and you have to return this concatenated word if there is any in the string so in this case cat dog was the concatenated word available so we returned it so this is all you have to do so please try to think around the question and think of approach and try something and then come back to the video so if you have tried the most easy solution which should have come to your mind act we have only we will have a blank string and then we have two choices whether to include cat and whether not to include cat then after that we again have two Choice whether to include this dog to make it cat dog and whether it should not include dog that then it becomes cat again and in the blank string then we have another Choice whether to include dog and whether not to include dog so after ultimately you will get some answer and you will backtrack and see whether they are in the string and you will get the answer as CatDog but if you see the time complexity in such cases we have two choices for every element for every string element so the time complexity will be exponential that is 2 to the power n for The Brute Force so will that be a optimal solution no because it is a Brute Force solution and it is having very high time complexity so we should optimize it so please try to think an optimal approach which is better than this okay and then come back to the video so I hope you tried thinking of an optimal approach but if you was not able to find out well see the video see what we can do we can think of this word as cat and we will divide this word into prefix and suffix prefix is C and suffix is 80. and we will check in our we will make a set and inside let's check set we will check whether we are having a prefix C the set will say no then we will move on when then we will make a prefix as CA and suffix will become T then we again check in our set it will say no and then we finally get the whole word cat and we are not finding overall word so we will neglect it after that we will move to dog for dog prefix initial is D and suffix is OG we will check inside whether there is a word like this no then we will check do and then we will check G then again it is not in the set now it will start to make sense when we move to CAD dog we will check one by one first we will check C then add dog then CA then T Dog then when we will check cat we will say that it our prefix is in the set cat word is in the set and other word is dog that means our suffix is also in the set that means cat dog is the answer but let's say there is another condition when you are not having this dog here you are having d and you are having OG separately and then you have this CAD dog word in that case this suffix will not be there so is the answer wrong no it's still it is still the concatenation of rest of the strings so what we will do we will divide this suffix again to our function we will pass this suffix to the is concatenation function which will be checking whether it is present in the set or not and we will pass this word dog into it and now this dog will be divided D and OG and we will check whether it is in the set yes D is in the set and OG it is also in the set so then it will return true so ultimately our answer will become character so that is what you have to do you have to apply make a concatenation function but it will check whether it is a concatenation or not which will divide the words into prefix and suffix and when you are dividing the words into prefix and suffix you have two condition first is either prefix and suffix both are present or the concatenation of suffix is present that are your two conditions so let's see in the code and you will understand it better so let me just zoom it for you and we will start coding so coding this is pretty much simple if you have understood the approach till now what we will do we will start with creating the end and equal to words dot size this will give us the size of our word string after that we will make an unordered set of string and we will name it as St and what we will do to get all the words inside this set we can I will give you a shortcut that is begin comma words comma and comma word this will get all the elements from this word string into our unordered set it is an inbuilt STL call of C plus after that you will make a string result to store a result and we will start iterating in the loop as I told you I less than n i plus and inside that we will get our first word is equal to words dot I this will give us the first word that is Cat in the second example as I told you and after we have gotten this word we will check it in a is concatenation function this concatenation function inside that function we will pass our word and this set will tell whether it is true or not if it is true we will push it to our answer we will push the word to our answer and if it is not true it will not push to our answer after that we will return a result strength that's all you have to do so now let's complete this is concatenation function to complete this function what we can do what will be the data type of it will be a Boolean data type because we have to return whether it is true or false we will check first we should pass the parameters what will be the parameters first you will pass the word so for passing the word you will write string word and next thing you have to pass is unordered set that is you will check in the set now that's why we are passing set and we will pass it by reference to avoid any time complexity issues and after that you will make a int n is equal to word dot length this will give us the length of the words and we will start iterating for enter is equal to 0 I less than n i plus now what I told you we will make a prefix string prefix and how to get the prefix string we will simply use the still called that says word dot sub s t r and we will pass the starting index and the initial ending index that will be the total length of the ending index that will give us the substring prefix and for suffix what you will do you will write word dot substr is a STL call which will give you a substring where you have to pass the starting induction endings in this length you have to pass and after that suffix will be I plus 1 up to n and for n you don't have to pass anything you leave it blank and it will consider it from that index to last index now what the next thing I told you it is the most important part of this question that we will check whether our prefix is in the set if it is in the set then it is very good and also we will check whether our suffix is in the set or not and we will check others our suffix is in the set or not if these two conditions are true will that be enough to complete our answer no we also have to check for the condition when we are having elements like these yes or no when the concatenation is of other parts when we have to devise the suffix and then we have to check the concatenation as I told you by giving this example so to write that condition we will create an R or if this is true or we have to check whether our prefix is in the set that should be the first condition prefix should be in the set that's our important condition also we have to check whether is concatenation we have to pass the function again and we will check it for suffix we will pass the suffix and we will pass the set and then we will check whether it is true or not then we can say true or false yes or no return false if it is not true so what is happening here as I told you in the example the first cases of this when suffix was in the set cat and dog was in the set but the next case is when the suffix is divided into parts and then it is part of the concatenation when D and OG were different that condition is covered here first is suffix is part other is the concatenation is the part that's what we are checking so let's just run and check whether it is working or not so yeah it is running let's just submit it so yeah it is accepted but one thing to notice here what will be the time complexity it is a loop of Port N it is O and loop okay that's fine but when you run here in this Loop you will see that it is running for n times and when you are calling this function again then it is running again n times so it will be like let's say it is running for M times and M into m that is what is happening and if it is called again it will be the M Square to the Power Square that will become M power 4. and that will be a huge complexity and but it is still less than exponential time complexity but we should reduce it how can we reduce it can you think of anyway the best approach to deal with such condition when we are calling the is concatenation function for again and again we can already store it somewhere and that concept is called memorization I used to call it memorization because it is basically memorizing the steps which are done I don't know why it is called memorization if you know please commentator so for that we will create an ordered map which will store what it will store the string and its value that whether it is already done or not and we will have to also write here that if it is already find in the string we will check whether it is true or not map dot end then we return map dot word to our function and this is true and we have to make here return map dot map word to true this is basically the storing of data to avoid calling the same function for the same element again and again it reduces our complexity to be it will change our M Power 4 to M power 3. because there might be cases when we do not have to call this is concatenation function again because we already found the word in our map and we also have to declare our map here by clearing it and then rest this already because we have declared it globally so let's try to run this and check whether it is working or not so yeah it is also accepted so this is the memorization way or memorization way to reduce the time complexity generally they won't ask you such time complexity but if they ask do you know the answer how time complexity is calculated and how it is reduced and what is the benefit of this memorization here so I hope you liked the video to brief you with the question again we simply had to return the concatenated words and for that we just check whether we divided the word into suffix and prefix and we were checking whether suffix and prefix both are present or whether the concatenation of suffix is present and prefix should be there in any case if prefix is not there then it is not concatenated and further we optimize it by using memorization by creating an unordered map to store the strings already done so we don't have to call this is concatenation function again so this was all you have to do in this question I hope you liked the video please like share and subscribe thank you so much for watching bye
|
Concatenated Words
|
concatenated-words
|
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`.
A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.
**Example 1:**
**Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\]
**Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\]
**Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats ";
"dogcatsdog " can be concatenated by "dog ", "cats " and "dog ";
"ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ".
**Example 2:**
**Input:** words = \[ "cat ", "dog ", "catdog "\]
**Output:** \[ "catdog "\]
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 30`
* `words[i]` consists of only lowercase English letters.
* All the strings of `words` are **unique**.
* `1 <= sum(words[i].length) <= 105`
| null |
Array,String,Dynamic Programming,Depth-First Search,Trie
|
Hard
|
140
|
1,748 |
elements that appear exactly once in the other so return some of all the unique elements of columns so RN will contain duplicate elements so you just need to neglect those elements so yeah you could see in this example two and two are duplicates so they're not unique let's say you will not count them for example the only unique elements are one healthy and that is the usual approach to solve the problems like um pre-commative so yeah you take each pre-commative so yeah you take each pre-commative so yeah you take each element and compare with all other elements so then all people then add that to them so what's the optimal approaches I will use uh today of type integer comma integer applicants the first key is helping with the Enemy and the value is sentimental count of the academic so in this case initially you have one right so one and the count is one let's connect to two again because 2 is not present in the hash mapping inside and count will be one then three will start present with so in 30 grand count is also one then you again come to two now uh you insert you need to insert the current hash but no it's already present you just need to increment the count from one to two how do you put it I'll tell you so once you have the hashment now you run the follow quality and you check whether Mac Dot get off num uh index that is equal to 1. that is equal to one that mean it's a unit emulator and you add that to the sum plus equals to column dot get off um particular um sorry particular element so this is a basic approach or we will for this so initially we have to declare so integer comma integer let's name it as counter because we are counting the occurrence of elements next okay for each number in nums you have added number to the hatchback so dot put off put on none particular element that is key and the value is something right over here you have to check so if the value was at that particular element is invited then the quantity one right and if it is present in the array already then hit increment the code here in this case initial it was included by one so how do we write that foreign dot get or default of non comma zero plus one so in this case if the number is present in the hashna then it will take the value of that particular number if it is not present it will consider 0 and it is default okay half num comma 0 Plus 1. yeah so often adding all the elements to them now again for in Num in nums so you have to check if count now dot get off now that element is equal to one that means that uh then sum plus equals to now I have to add that particular element sum so at last we return the sub it's been successful submitted if you haven't yet please drop in the comment section we'll come up with another video next question and please subscribe to the channel and keep running thanks
|
Sum of Unique Elements
|
best-team-with-no-conflicts
|
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array.
Return _the **sum** of all the unique elements of_ `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 4
**Explanation:** The unique elements are \[1,3\], and the sum is 4.
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** 0
**Explanation:** There are no unique elements, and the sum is 0.
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 15
**Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
|
Array,Dynamic Programming,Sorting
|
Medium
| null |
228 |
hello guys welcome to my YouTube channel today we are going to show that daily need for Challenge and ask for the challenge here go ahead use the level problem summary ranges so let's read the problem statement you are given a sorted unique integer array nums now make nums very given name who sorted a range a b is set of all the integers from A to B inclusively a plus one a plus two till B so B element is list of the ranges that cover all the numbers array exactly so how many smallest shortcuts is and that is the each element of the terms is stored by exactly one range okay and there is no integer X as that X is in one of the range but not in nums okay so study elements like each element of the array should exist in exactly one range here so that is present in the range foreign starting in uh the digit of the range and the ending digit of the names go is this is the representation of the range V1 micro signal is foreign okay so this is the base conditions so it means we do not have any range it will return the empty character of the string is starting which is starting number of that of the current range so initially the current range will start at num zero foreign it's working fine so thank you for watching my video other videos so please subscribe to my YouTube channel and like this video please write it down in the comment section thank you
|
Summary Ranges
|
summary-ranges
|
You are given a **sorted unique** integer array `nums`.
A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive).
Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,2,4,5,7\]
**Output:** \[ "0->2 ", "4->5 ", "7 "\]
**Explanation:** The ranges are:
\[0,2\] --> "0->2 "
\[4,5\] --> "4->5 "
\[7,7\] --> "7 "
**Example 2:**
**Input:** nums = \[0,2,3,4,6,8,9\]
**Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\]
**Explanation:** The ranges are:
\[0,0\] --> "0 "
\[2,4\] --> "2->4 "
\[6,6\] --> "6 "
\[8,9\] --> "8->9 "
**Constraints:**
* `0 <= nums.length <= 20`
* `-231 <= nums[i] <= 231 - 1`
* All the values of `nums` are **unique**.
* `nums` is sorted in ascending order.
| null |
Array
|
Easy
|
163,352
|
315 |
Hello everyone welcome back, so suddenly Agni-Pawan himself is going to discuss, there Agni-Pawan himself is going to discuss, there Agni-Pawan himself is going to discuss, there is a problem in the record height range, account of roll numbers after safe and basically this is the problem, what to do in this problem, we are an area and we have to tell everyone who has a On the right side of the element, how many glutes does he have? Like, the value is skin lace, we have to edit an account to tell their account, like if this is the area, then what is it, we have to create a new one and send it, okay, in which how many tasks are there from five? 50241 is the work of two elements, I am on the right side, if you look at 2532 two, then there is not one bar, which wave is on the right, if you look at the coin of Vansh, then there is one, then take care of it and if you look to get it, then it is the duty in the night that this is our return. It will be 210 Jai Ho, this is basically to be done in special, so see how we will approach, there are many ways to call this question, we can do it from BSP, its complexity is ok, that off fans, chicken open squash in Yogi and we can do it using any balance. You can do it on BSP, like by using those entries, it will be off in log in or in log in is a chick and we can do it by brute force, it will appear active in the group, okay, it will come from here and there will be a jail loop and We will check how many questions are there, okay then that will be given to the fans, which one is there, so these are the three approaches, if you know each approach, please explain then tell me, not in the comments, I will make a video on this question on battery, how is this thinking. In this question, in this video, we will see its approach, how we can solve it remotely from smart, so the information of inversion account will be very similar to that, if this weight loss question is done then it will be better understood, if not then now is the time. I will think that I will first try that version account, okay, then it would be better to do this one, but if I give it to you, then how will I shift my death? Okay, now we and Chaat, what do we do, in this street monastery, we first Let's call WhatsApp on the left, then you take less, divide it into 2 parts, we call one here, type it and then enjoy, those who come to us, this is whoever is here. Everything has changed, it is a small function, so it is medium hot, we will meet both of them again, okay, how are you, so first of all, this is ours, first of all, we will take America, okay then it will disappear, I had hit you on the net as a boy. Erase induction 0213 you will get tiger hero plus three y2mate okay so that means divide from here to here so a the five two and a moment will take us with us we will take which is and which is like which I have 501 cigarette and that which I have his right It should be on the side, meaning the find You have become this, divided into 2 parts, then I fry it for a minute, then when I take it out, then add zero flash 1512 pure debt zero, okay, so this is ours, divided here, this face and you, okay, you Petition five and here which place are you and in this section write down zero and there is now see here a judgment has come so now we will set our march okay what will we do in the fun by the way basically we work in the office we Inch extra in ascending order, which makes it ours, it is not uncivilized to use dry ginger but the question is, why will we do it depending on why because we have 5261, so we have to do this from five to molar elements, which ones will be there, please do that. We need a bowler, we will keep it depending on our hotspot. Okay, so let's see how we can make an amazing counter. In this, we will start the song, like Jo Maharaj, Dhamara Retention, this person was making it, so it has 012 and the second result is lying in the whole. So. Look here, when you match them, our I is here, Jio's is here, our smoothness is Amazon, our I is here, this is 0.5, which is my latest chicken, meaning you will have to 0.5, which is my latest chicken, meaning you will have to 0.5, which is my latest chicken, meaning you will have to transact it. Now see how many degrees are there that this side is the first one on this side. So that means that here we will get the rights like it is from here and so this is ours so whatever this is which is zero, we have to increase one song because it is 503 torrent that CIA will move ahead and we advise our And if we go to the tele, then go where it will be, it will go to 521, okay, so here this is what will be made of ours, this will become a bicycle, and just 15 account ingredients have been made, this massage, what will we do now, come here, okay, so here two and This cream that now here we see only the Greater Himalayas here and here it will be like the friend of I care of is greater that means Sikh time is select one and one has to be taken from one drops on the right side that here that this business and this Our fronts will be formed only in descending order, which one do I like and after that now if we have to match them then this will be our I and this will be our yes, okay hey oh man the I of I is our layer and like Here, what will we do, we have kept it in our report because whatever it is, it will come well, you see, friend of I, which is this Greater Noida Raj, 512, the previous song again on the right of Zinta Industrial Unified. This has become one of our answers, so our 5a but there is another updated one and our six or five will come which is bigger size, we have such and eye treatment here, okay, then let's see friend, you come i.e. then let's see friend, you come i.e. then let's see friend, you come i.e. two. To give greater and like what is this 2.1 a which one so this is ours here we will write that when he grows up like this and then here she has come here she will be our avatar will be tied okay so yes if we give this thing then this man Our Jogiya will die, right, this first ₹ 5000, so this is something die, right, this first ₹ 5000, so this is something die, right, this first ₹ 5000, so this is something that he will become a father, 6525 Vada, 12th March has also passed and our answer has been given, ticket 251 for the second work and this is all right, isn't it ours? If you are giving blessings, then let's understand that basically because what are you doing? First of all, you are putting your smartphone, okay, Moksh, you are putting it on short leg, okay, you called on mod right, then you are doing sleep function, not function, what in March? If we are doing then our Yaar of I, which is there, has increased from the Yaar of things, okay that is the whole account, okay, whatever account is there, some Air of Finance Minister has proposed that I want and we will read plus on Sector-51 Index. we will read plus on Sector-51 Index. we will read plus on Sector-51 Index. Equal to good, okay, we will do it, we need it, like support is not coming, rough gel will be added, okay, like right, whatever right will be Bwari - okay, like right, whatever right will be Bwari - okay, like right, whatever right will be Bwari - Z plus one, why am I doing this, because look, support in descending order is like this. If something happens here, this confusion will come, then something happens here that we had some such jobs, okay, this support is given here by the commissioner and he agrees to show me how much we will increase the Internet as big as today. 5G can be made along with it and this is because this will be our dependent warden which will be our descending order so if it is lying with this then it means after this because that is the rest and if this is then that means if it is bigger then comment in us comment Do like ride point if we have here i.e. Do like ride point if we have here i.e. Do like ride point if we have here i.e. writing - he here take it plus one because - he here take it plus one because - he here take it plus one because if this is right - ju0 ha0 then this is two minus if this is right - ju0 ha0 then this is two minus if this is right - ju0 ha0 then this is two minus plus so our 53525 so here we have right - 2 plus so our 53525 so here we have right - 2 plus so our 53525 so here we have right - 2 and if so here you if our friend of I Our friends, if we are getting less than what we are getting, then there is nothing to be done, the Maharaj is just whatever is ours and the robbers in whatever pimple mod they do, we will add our pure and plus in it and in whatever we do and here when So when we do the account ingredients, here we will add whatever our addition was to our tempo key. Okay, and Kepler width plus, so this is such a fortune project. Let's understand what we are doing in the code. It is simple, first of all, let me see here, first of all, we have done this fast that we have hit the size on one invariable side and are making their mind a vector of fear, what will happen in this, it will break our shoulder, which is what we thought. Na what happened, we will take a statement and also its injection will be 5050 so that when we are updating the account in the number spoon function then we will know which account of this five is the inactive we have to increment so we will use English. I put it together, okay, so this is made, then and now we are going to vanilla in it, making love and made the name profile crops' second paper and made the name profile crops' second paper and made the name profile crops' second paper international content which will be militant and called this mod of function, okay, the same in the mod. As we do, enter the chat window and in the minus that this weather function will run as long as it is flags and right and remove first the hotspot call up to the minute and then the lighter from Master Mithlesh and here's the whole story that in March Put left midnight and present and is the main champion, this is this line, this is not the one which is smart from a like flirting in the backstreet, which is the extra oil photo, had already made its temple run, wild life, if decided, if then let me here But that if the friend of the eye is that friend and like it is small, then just to have coffee, then plus C plus of the tempo's decision, so this is the judgment bell, but the phone is tempered glass, if the eye is big, which means we have to account in. We have to treat that eye element, cashew nut is intact, it will be found in the setting, then the second hand was active, I am in love and we will do plus right - G plus in love and we will do plus right - G plus in love and we will do plus right - G plus form and we will put this then in the temple and lastly this is because of thumb and If winter comes, if there are children or there is a limit, if there is any problem in the daily points, then put more, then put that and lastly, copy whatever time you have in your business, I have a forever approach, this is off. These people have taken the time complexity and Space is off in login no time, I have come from the hospital, so this is the belief, the previous is very simple, this line is means, if you understand the meaning of this line, then nutrition is very easy brother, it is okay and everyone is on the vine of this mathematics. All of us can do this question, if you have time to approach it, then let me know in the comments, I will make a video on it with my daughter and if you like the rest of the video, please like, subscribe and light the fire.
|
Count of Smaller Numbers After Self
|
count-of-smaller-numbers-after-self
|
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
327,406,493,1482,2280
|
162 |
today we'll be going over the cone number 162 would just find peak element so it's a peak element is an element that's great events neighbors given an input array num swear nuns at eyes Uncle Tom's and I plus one find a peak element and returns index the array may contain well so Peaks and in that case return the index to any one of the peaks is fine and we're assuming that the outer boundaries are equal to negative infinity so we have our array one two three one this is nums amount of peak elements we're going to find is one peak element which is the number three and the reason for this is because if we check three with this neighbors we see that 3 is greater than 2 and 3 is greater than 1 therefore 3 is a peak element for example graphing this we could see that go up to 2 then up to 3 then all the way down up to 1 so here we see that 3 would be a peak just like the peak of a mountain this is how we identify peak elements so for example in the array ABC where a B and C are integers in order for B to be a peak element B has to be greater than C and B has to be greater than a sounds move on up to how to solve this problem so let's say we have our integer 1 2 3 1 what we can actually do to solve this in just 8 lines of code is that we can just go through the array with a simple for loop and in the array we're going to check numbers at a position I and check numbers at position I plus 1 and then we're gonna check is if nums at i is greater then nums at i plus 1 and if so we're going to return I now the reason why this works is that because we are going to constantly be checking one element and the element after if you look at this example one two three it's all increasing up to the point of three but once we check the number after three we see it's decreasing so therefore in the number ABC if it keeps on increasing the number after it is always greater than the number before it but then once we reach a point B and then from there on C is decreasing we know that B must be greater than a and B must be greater than C therefore we would know that B is a peak element this is the simplest and most efficient way to find a peak element the actual code for this is very simple so here we are actually just gonna run a for loop that goes from I to the size minus one and this is because we are checking I and I plus one so once we get to the end of the array and we check it were you going to go to I and I plus one where in that case I plus one would be out of the bound and then over here we're doing what exactly what we discovered right we're gonna check if numbers that I is greater than numbers at I plus one and if so we're going to return I because again it's going to show that it is gonna steadily increase until we find a number where it starts to decrease and from there just going to return numbers that size minus one if we do not find I if we do find I we are going to immediately return the index which we find it at
|
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
|
219 |
hey folks welcome back to another video today we'll be looking at question 219 contains duplicates two the way we will be approaching this problem is by initializing a hash set and the hassle will keep a track of the k most recent elements that we have seen from the indexed um index element that we are examining right now so the way we will be doing that is let's uh start putting it up we have a headset and or the entirety of the area itself we will be checking if the element exists so if the set contains the current element that we're looking at the first thing we do is just rip the return row and it exists exist uh exits the entire method and if nothing has been reached by the end of the loop we just returned fourth so if the element doesn't exist already what you would do is you would add the particular element that will be into the set and if the size of the set is greater than k um size is greater than k what we will be doing is we will be removing the element that doesn't fall in i minus k range so that would be set dot remove f i minus k okay um so the reason why we're doing this is because we want to keep a track of the k most elements that we have seen recently and anytime the size is greater than k we know that we will be looking at elements that um that have surpassed k already within the k distance that's the reason why we're trying to remove everything that we've seen before um items the index so let's just run this to make sure everything is okay the first test case passes and it passes all of the other test cases as well so this time complexity of the solution is o of and the space complexity would be of okay because it will be storing a maximum of k elements so let me know if you have any questions about this uh problem um is there any questions that you want me to solve let me know in the comments below and don't forget to like share and subscribe i'll see you all in the next video peace
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
215 |
hi everyone before I solve the question today so thank you for watching my video so finally I got the 160 subscribers so I remember at the end of November I reached the 100 subscribers so since then just four months I got 60 new subscribers yeah um it was her actually I expected because uh for the first two months um I got zero subscribers so it was tough Journey but uh finally I got a 60 subscribers uh in a month so yeah I'm very happy and I will continue to upload the new video in the next year so please subscribe the channel and hit the like button or leave a comment so let's get started so today's questions is a case largest element in Array so you are given integer array numbers and then integer okay return the case largest element in the array so very simple question and then note that it is a case largest element in the salt order not case distinct element so you must solve it in all end time complexity so let's see the example so you are given three two one five six four and the K is 2 so output is 5 because uh we need to find the second largest number in input array so that should be five in this case so that's why output is five yeah very simple question but the point is we have to solve this question with a linear time complexity so I think simplest way is to sort them out and then uh choose the second largest number but I think that is like a quick sort of method uh that is like a order of analog end time complexity so yeah but we have to solve this question on linear time so let me explain how to solve this question okay so let me explain with this example three two one five six four in the k equal to so we need to find the second largest number in input array um so to solve this question uh we use a quick select which is very similar to um very famous sort algorithm click sort so if you don't know how quick sort Works actually I created a video a few months ago so I put the link in the description below so check it out for click select we use a left pointer and a light pointer so for left pointer is a most left index of the range so easily so zero and the light pointer is the most light index of the range in this case zero one two three four five and we use a pivot and index number and the pointer so pointer is updated with a left pointer so that's why I initialized to be zero and the pivot is initialized with a right pointer so that's why I give it is a lasting mix so basically we iterate through all numbers one by one so that is an index number current index number and every time we check current value versus pivot and if current num number is less than or equal to Pivot in that case um we will swap the number with current number versus uh this pointer number so let's begin so first of all pivot number is four buses current number is three so current number is uh less than pivot in that case uh we swap the number but uh P also pointing three so we don't change anything and then after that if we swap the number we move this speed pointer to next and also next current index number is one so next four versus two so current number is less than pivot number so in that case we swap the number but it's same so we don't do anything just update the p number to next and next so I so in this case uh again current number is less than four and swap the p number and the current index number but they are same so we don't do anything just update a PIN number to next and the next index is three so value is a five and a four so um current number is uh greater than or equal um greater than uh pivot number so in that case uh we don't swap anything and we don't move this P pointer to next so just a move index I here and then um check the current number versus pivot and the current number is greater than pivot so in the case we don't do anything and then uh so we need the um pivot so we stop uh iteration so now uh P pointer is pointing index um zero one two three and uh pivot number is 4. and at last we have to swap 5 P value and the pivot value so that means um this index value is full and the last value is 5. so the reason why we swap the number is so look at the um this area buses um this area oops so before uh P all numbers in the area is less than uh pivot p number and uh in the orange area so all numbers are greater than uh pivot number so now we can successfully uh separate like a smaller number and a bigger number okay so look at the K number k equal to and where the second largest number is located so actually we can calculate with scan number so that is length of input array minus k so that is length of input should be one two three four five six minus two is four so at least the second largest number uh is located at index 4 will above so y above because uh this input data is still not sorted actually and sort it input arrays so that's why we don't know where is the second largest number but at least second largest number is located at index 4 or above so that means um we can find the second largest number in Orange area because they are one two three four right so if um okay equals three so we need to if we need to find us the third largest number in input array in this case um length minus k equals three so in that case we have two larger number and then on the left side of P pointer so all numbers are small so that means this p number is a southern largest number in the case we can immediately return the like a p index right but okay now okay it's two so we know that at least a second largest number is located in Orange somewhere in Orange area so after that we call the quick select again but this time so we um so first of all we passed like a left pointer with zero and the right pointer equal five but uh we focus on only oriented at this time so left pointers should be four and the last index number should be five okay so next well we focus on the only um orange area so now left pointer is full and the light pointer is five so pivot number or still the last index five update with uh right pointer and this is a current index and uh this P Point uh is updated with left pointer which is 4. here then start looping so compare current number with pivot number so current number is greater than pivot number in the case we don't do anything but at last we swap the current P value and pivot number so now 5 is index 4 and 6 is the last value so same thing look at the okay um this area oops look at that um look at this area so um that so we have a two number and the six is greater than uh five so in that case uh six is a uh the biggest number in the array so that means um so this p number is now uh the second largest number in input array so um check p is length minus k so p is greater than length minus K which is four um we have to search on the left side and uh if p is less than this one in that case we have to search the target number on the right side and E actually if p is the same as this number or actually that's true in that case that is a target number so we should return 5 in this case okay so let's write the code first of all um calculate the actual Target index number so k equal ranks of input array minus k and the return on quick select passing the left pointer and the right pointer so numbers minus one and let's create a quick select function So Def quick good quick select and left and the right and P ivot and the P pointer so update it with numbers and the right and the left so start looping for I in length from left to right economics so current number is less than or equal pivot in that case and swap the p and I equal um so we solved this number so I and the B after that um move P to next so plus C for one and after we ditch the end of um input array so after that we swap the current p number and uh numbers um right so which means that this is a pivot number um equal and then this is our right so and a p uh so that we can separate like a small number and uh um larger numbers and uh um this k numbers so after that if p is greater than k in the case um so Target number are definitely uh on the left side so in that case the um quick select and there's same left pointer and the right pointer should be P minus one because uh we have to search on the right side left side and uh as if e is greater than less than K in the case um K is a definitely on the right side of B so little quick select and a small number should be so left pointers should be P plus 1 and the same right number and else so as I explained earlier um actually a current p is pointing the target number so just returned now p yeah actually that's it so let me submit it yeah looks good but it's not good at the end because um so quick select is average time complexity should be a linear time order of n but in some case so for example we um we continue to pick the largest number or smallest number as a pivot number in that case um so time complexity should be uh o n square or something so yeah in some case a very bad time complexity so next let me modify this program so that we can I think improve the runtime okay so to improve the runtime so we have a two Choice one is uh um so now we fix the pivot number as a like a last number right here so we change the like a random pivot so that we can improve the um diagram time so another thing is that um we should Shuffle on this input array before we start quick select so I take that algorithm so in that case before start click select so for I in length and so yeah we can do several ways but the simplest way is uh start from the last so length of each array minus one and -1 and the minus one and -1 and the minus one and -1 and the minus one and then um J equal random Dot landint start from 0 to index I so yeah that's why we start from the last so it's easy to decide the last value and after that numbers I and nums J so we swap the two numbers here so equal this number should be J this number should be I so I think like this is uh on solution so I think that's uh good and so let me submit it yeah so we can improve the runtime uh drastically um the previous one is like a 90 percent or something so now we get the 64 percent yeah so let me know if you can improve more so let me summarize step by step algorithm this is a step-by-step algorithm of case this is a step-by-step algorithm of case this is a step-by-step algorithm of case largest element in Array step one calculates the target index step two Shuffle input array to avoid the worst case step 3 start quick select step one set and pivot and P pointer step two if the number is less than or equal to Pivot then swap current key number and the correct number and move P pointer to next step 3 Swap the pin number and the pivot number so that we can separate numbers into smaller larger and pivot and step four if p is a greater than K so K is a target index in step one so Target and the target number is on the left side if p is less than k um in the case Target number is on the right side so step five if not the case the number pointed by P pointer is a target number yeah actually that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
1,186 |
hi everyone let's discuss about weekly contest 153 third question so maximum sapere with one deletion so we are given an array of integer and with being asked to return the maximum sum of the non empty sub-array with option to delete empty sub-array with option to delete empty sub-array with option to delete one element from it so let's take a look on the example so on the first example here we have an array and let's say we take the whole array as the sub array and then the sum of the sub array the maximum will be 4 because that whole sub array we can remove - steal from it so array we can remove - steal from it so array we can remove - steal from it so the sum will be 4 okay because we can optionally delete one element from debt sub array or any of the sub array and then on the second example if we take a look our maximum sucker is 3 here so we take this one element as the subarray and because the delay is optional so we don't perform the delete and then we get 3 as the maximum sum and another example so we cannot have a non-empty sub array so cannot have a non-empty sub array so cannot have a non-empty sub array so that means if all of our element is negative we still need to take one of the element and we cannot perform the lid on it because once we do a delete then that sequere will becomes empty so we written a minus 1 in that case okay so how we going to solve this question so this question is very similar to maximum sub array some without the deletion so the deletion comes when we have division we need to perform it from two direction of Katniss algorithm but without deletion we can perform it with only one x Karen s algorithm so let's take a look on how we going to do that in this example so this is our array input the case and then this is the way of finding the current maximum by the cattiness algorithm okay and then let's take a look on how we can produce that array of the current maximum so this is the formula so current array is either from the previous maximum plus current array or the current array itself the current index itself I mean so the first set the first time we will take the 11 here and put 11 and then next step 11 plus minus 10 or minus 10 so 11 plus minus 10 is 1 or minus 10 so 11 plus minus 10 is larger so we put 1 + 1 plus minus 10 is larger so we put 1 + 1 plus minus 10 is larger so we put 1 + 1 plus minus 11 is minus 10 okay or we take minus 11 so minus 11 and - 10 or we take minus 11 so minus 11 and - 10 or we take minus 11 so minus 11 and - 10 1 plus minus 11 and the larger the largest one is the minus 10 and minus 10 plus 8 or 8 so minus 10 plus 8 or a k-- plus 8 or 8 so minus 10 plus 8 or a k-- plus 8 or 8 so minus 10 plus 8 or a k-- right so the answer will be 8 so 8 plus 7 15 plus 6 plus minus 6 or minus 6 so the answer will be mine 15 plus minus 6 right 15 plus minus 6 will be 9 or minus 6 so which is 9 + 9 18 + 4 xx 2 and 6 so which is 9 + 9 18 + 4 xx 2 and 6 so which is 9 + 9 18 + 4 xx 2 and so on okay so we do it in one direction first okay so in this way we can know what is the current maximum okay from the left side and then we need to perform it one more time from the right side so it's called max right so we start from there 0 + 5 0 5 + 6 and then 11 plus 11 22 0 + 5 0 5 + 6 and then 11 plus 11 22 0 + 5 0 5 + 6 and then 11 plus 11 22 + 4 26 + 9 35 + -6 or minus 6 22 + 4 26 + 9 35 + -6 or minus 6 22 + 4 26 + 9 35 + -6 or minus 6 we will choose the 35 minus 6 29 plus 7 37 and then tap T 6 + 8 44 - 11 33 7 37 and then tap T 6 + 8 44 - 11 33 7 37 and then tap T 6 + 8 44 - 11 33 - 10 23 + 11 34 and then we get 33 - 10 23 + 11 34 and then we get 33 - 10 23 + 11 34 and then we get the maximum from life and maximum from wreck of the cattiness algorithm for the current max so how do these two array help us to find if we need to do one deletion or not right so let's say if we need to do one diligent let's say from this area of software as you can see everything is positive except minus 6 right so we want to know if we remove this minus 6 what will be the result so what we can do is we try to find what is the maximum sub-array we find what is the maximum sub-array we find what is the maximum sub-array we can get until this point like from the left so this minus 6 on the left side this maximum sorry will be 15 because this 15 we purely counted from the left until the point before the minus 6 that we want to remove so it's 15 is come from this 2 right actually we don't really know like where it's come from but we just know it's 15 from this entire left part of the sub array the maximum supper is 15 and then from the right part of it the maximum supper is 35 so if we're going to remove that -6 that -6 that -6 it means the maximum support from the right and maximum the maximum support from the right which is this part and maximum support of the right which is from this part will be merged together and this will be excluded so it means it's a 15 plus 35 which results in 50 okay so let's take a look on how the code doing this right so it's very similar with the explanation except we have one more condition here which is everything is minus so we need to take at least one of it so we take the smallest minus number so I find I try to find the smallest minus number and if the highest value is still a - at least we return the still a - at least we return the still a - at least we return the smallest minus number there and then after that we perform our formula which I explained from the extra C for the current max so as you can see here we initialize the forward array and then the current max equals zero and then there is a best max which we didn't really use it for now and then so we try to find the current max which is current max equals current max plus a or a okay so this part is not used let's move it out and then we try to find the current max which we simulate here like as I explained before so after that we will get the current max for each of the index and then we store it in our foreign index so which is the each of the value here for each of the index okay and then we do the same thing again for the backward array so we start from the last index until the first index and then yeah as you can see it's still the same we do the card max and then store it in the backward index for the value of the current Max and then what is best max so best max is only in case of we don't need to remove anything so if let's say this area will be the maximum number let's say this is a six okay for example this is a six so this entire area might be the maximum array let's say this is in fact the maximum rate like this is I replaced this with minus 11 so this entire area will be the maximum sub-array right so we take that entire sub-array right so we take that entire sub-array right so we take that entire area but we don't really remove anything from it so in that case this will be the best max okay so I start the best max as the initial output value and then from each of the index from one until array length minus two we try to merge the forward path and the backward part as I explained before like the here if it's minus six we expect we exclude this part and then worth the 15 and 35 and then we got the 50 okay and the best max is just in case everything is a positive then we don't really exclude anything but we already have the best max which come from we didn't remove anything so why it start from one until right that length minus two it's because if that value is actually on the corner we don't need to merge anything because if our maximum array is everything except the first index it means your maximum right is already getting the fail you here right or if it's the last index then your maximum life is already getting the fail you here so you don't need to merge the left and right in that case it will be a beautiful ooh that come from the forward or backward itself on the best max yeah and that's it for discussion thank you for watching see you on the next weekly contest
|
Maximum Subarray Sum with One Deletion
|
building-h2o
|
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104`
| null |
Concurrency
|
Medium
| null |
349 |
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now yeah so in this section of two arrays 3:49 given in this section of two arrays 3:49 given in this section of two arrays 3:49 given to a waist right up function to complete their in this section okay you tournament kit and we saw must feel unique to resell can be in any order okay so there's a couple of ways that you can think about this far the naive album would just be ants career and that you look at each element and service in the other way but you have to keep track of you have to make sure that basically you have to make sure that oh okay you chairman that we sell mister unique so yeah so we don't have to care about it that much which is did a couple ways to do it the way that I'm gonna do it now it's just by using a set and then put all the numbers in the first number first list in the set and then in a second no way yeah in fact I'm just gonna be a little bit lazy and then come up both of them to a set and then use a set intersection in Python so depending on your language this may or may not be easy but that is basically how I'm gonna do it that's let's get started so set one is equal to the set of numbers 1 set 2 is equal to set of numbers 2 and then now we just want to return a list so we return a list version of set 1 intersect set to that might not be pythons in texture okay so maybe it is okay alright because I don't remember the overloading functions but now let's put in a few cases so that looks good I feel confident that's submit the problem or a solution and fingers crossed okay so cool yeah accepted yeah so this is a very basic problem the way that I did is a little bit lazy it is o of N in time and space even though it is hidden away but because we're using libraries you can you could definitely improve the space usage right now it's off n plus M where n is the size of the number 1 and M is the size of number 2 you can actually make it the min of N or M and that'll be slightly faster but you cannot go you cannot do better than looking at every item at least once so you cannot be linear time for this problem so yeah so that's intersection of two arrays in terms of yeah for interview problems I think this one is pretty basic I don't think necessarily that this will be a problem by itself but this will be the basis of harder decode problems or interview problem so that they get familiar of it and in the same rain for competitive programming this is too basic to be considered so you have to just know it ok cool
|
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
|
1,047 |
okay so let's talk about removal adjacent duplicating the screen so you are giving a shooting s consists of lowercase english later so duplicate removal consists of choosing adjacent and equal later and remove them so basically it's likely so i'm going to draw diagram and then here's it so we already know this to be all the same right so we will remove but once we remove to be right these two a are adjacent with each other so i will have to remove these two a so this is super simple question just create the stream builder or the stack doesn't matter well whatever you choose right so this is a stream a b a c a right so i have a stream builder so stream builder is basically slightly like you have to check your last character in the stream builder with the index i in the string so if they are equal then you will remove the last character if not then just append to the stream builder right so here is it so last character in the stream builder so i'll open it and then b is not so append so then the next character b next therapy is actually equal to the last character in the string builder i will remove and the next character is a and now remove and then c no i append a no out of 10 right so the answer is c a at the end so this is how it is so uh let me just call it so stream builder i'm going to call sp equal to new stream builder and i will transverse the entire array entire character in the stream right start to char array and okay and i will also create a variable size for the streambuilder.length size for the streambuilder.length size for the streambuilder.length so if the size is actually related which means there's a character inside stream builder then i will have to check my character shot at size minus one the last character is actually able to see if that is true then i will have to remove so it's going to be hr right delete char at size minus one the last character and then if they are not equal then i would have to append my character c into a string builder and i will just return sp to string right so this is super uh super simple so you can use in stack but that is actually taking more memory and stuff to do right but stream builder is how it is how you locate uh how you do it in the hip so let's talk about timing space so this is time it's going to be all of n which means it's going to traverse every single character in the string and this is space the space is actually like how okay how many characters have inside stream builder so it's going to be the worst case going to be all of them that you append every single character into a stream builder and this will be a solution and i'll see you next time bye
|
Remove All Adjacent Duplicates In String
|
maximize-sum-of-array-after-k-negations
|
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Array,Greedy,Sorting
|
Easy
|
2204
|
1,684 |
hey there guys this is code tutorial for you back with another leode problem this one's called count the number of consistent strings it says you're given a string alloud consisting of distinct characters and an array of string words a string is consistent of all characters in The String appear in the string allowed return the number of consistent strings in their array words so let's go to example one we have AP for alloud and then we have the words a d b d a b a d a b so as you can see the output is two since strings a b and b a are consistent since they only contain characters A and B so example two uh all of them are consistent because every single one contains only the characters given a b c as you can see this one has a this b c a b c ABC C uh the last example we're given C A and here are the words and the output is four since the strings c a c d a c and d are consistent which again they are consistent if it only contains the words that are allowed the letters that are allowed so in this case it would be CAD so the way we're going to solve this is we're going to use a hashmap we're going to map out uh the string uh that we're given allowed so the key value will be uh Char the key would be chart and the value would be in and so we can see the frequency um and we're going to name it MP short form map and then we have to uh initialize a variable to contain how many consistent um strings there are so what we're going to do is name it results initialize it to zero and we're going to do a for Loop the for Loop is how we're going to uh map out our map named MP so we're going to do is Char P because we're going to U map it out as a uh charart that's the key value and this counts the frequency okay so now what we're going to do is we're going to have to do uh a 2d array uh no a two uh because it's a 2d array basically with a vector string of words we're going to have to do a this for Loop to be able to go through each individual character to see if it is a character that's not in the allowed uh string that was given then we are going to U not count that and we're just going to skip to the next uh string and Vector of string words because that uh string is not consistent so what we're going to do is going to do a for Loop and we're going to start it out and we're going to name a word and here we put the name of the vector string that was given words and so we're going to go since it's a string um that's where we put string just to make it a habit since we're not going to be changing anything we are going to do a constant since nothing is going to be changed so to check if um if the charact if the character that we come across uh is not allowed and we're going to notify we're going to be notified by making a uh variable bu the named is consistent and put initialize it to true so if we don't if that is not in the map if the character that we come across is not in the map that means it's not consistent so then we change the is consistent to tr to false so what we're going to do is we're going to do that uh other for Loop to access each individual character because this one is this uh for Loop uh the outer for Loop accesses each individual um string in the vector string so it'll access first this string a d then it will later access b d and then ab and so on and so forth the inner loop is going to access the each individual character inside of it so it will access the A and then it'll access the D for the first string and the second string it access the B and then the D so what we will do first is um let's finish this one we're going to take that and that's how you do AED for Loop to check each individual um element inside of that string and then so if we're going to but we're going to access our map if find we're use the function finding in our character C which is that uh that character that we're looking for at that particular moment if it finds the end we're using the name of a map the function end if it finds the end that means it is not in the map so is consistent is changed to false and once it is it's false that means uh we can just move on to the next uh string and Vector string words so what we're going to do is just break it off we're going to break that off we're going to get out of the inner loop inner for Loop and we're going to go on to the next word let's say it if it is consistent let's say it is true change this up right here let's say it is true if it's true if is consistent then we're just going to add one into our result so that means that word is consistent and at the end we'll see how many are consistent and we return our result so then we return our result after going through every single um string and Vector string words and in those particular strings that we go through every single character uh in those strings so then we going to run it and we had an error it's because I put MP right there change it to allow to be able to go through that string uh and there we go pass uh the test cases uh now let's go to this tab going show you uh just a little bit more information to get this problem down as you can see we're going to be working with the very first example uh so initialize named MP and then we initialized the uh results to zero and then we mapped out um with the for Loop we mapped out um the allow string of it in his characters and then um we go and then we go through all of uh what we did in the outer loop and the inner loop we're going through the vector of string and then checking each word is true or false if each character is true or false in those particular words so for the word ad it's false because D once we get to the character d false and it breaks and here for the word b d it's false because once we get to the character D it is not found in the map so it returns uh it change consistent to false then we break and the word aab it is true and so that we count it into result and baa is true so we count it into result and word b a d a b is false because once we get to the D it's going to not find it in the map it's and it's going to change consistent to false and then we're just going to break so if the word is consistent is true the result is incremented so we of course we got the result of two so the final result is the count of consistent strings which was two so there you have it if you want more coding Solutions don't forget to like And subscribe thank you
|
Count the Number of Consistent Strings
|
find-latest-group-of-size-m
|
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters.
|
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
|
Array,Binary Search,Simulation
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.