id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,639
um hello so um today we are going to do this problem from lead code daily challenge number of ways to form a Target string given a dictionary so basically we have a list of strings that have the same length um and those are in words array and we have a Target stitching and our task is to form this Target string using the words in this list but we have to follow some rules so the first one is that targets needs to be formed from left to right so it's not random and then if we take a ninth character if for the eye character from Target we take because it matches we take the case characters from one of the words then all the characters to the left of that one to the left of this case character in the same world we can't take them anymore that's actually the second one or this third rule um so if we take the K characters from our word then we can no longer take anything to its left um and this one basically just tells us that the target at that Index right needs to match the character we are taken from the word which makes sense um and it says here we can use multiple characters from the same string right so for example this one you could use three b's you could use a c from this one so you could use multiple characters from the same world um and what we want to do is to return the number of ways we can get Target which is this string out of the list of the words and of course we want to use a modular here um okay so that's that makes sense um now for example if we take a look at this first example what we can do is first the there are a couple of ways we can do it first is taking this a to match this a and then taking this B to match this B and then this a to match this a the other way of doing it is for this final a you could take also this a the other another way of doing it is for that final a you can take Instead This a again another way of doing it instead of taking this B if you take this b or this B right so you see there are multiple choices and if we compute all the number of ways we have six overall so that's the idea now in terms of limits we have all the characters are lower case English letters Target can be up to one thousand the words themselves can be up to 1000 as well and the number of Parts can be out to one thousand so it should be reasonable if we do something that tries all possibilities it should be able to fit so let's see how we can tackle it um okay so how do we tackle this well the first thing to note again with all of these problems is to think if there is some approach we can use to do this in a greedy way without trying all a possible all possibilities or any other approach we can do that doesn't require us to try all possible options basically to try all the combinations of characters of each world and see if we get Target and there is not really anything right we have to check the character to see if it matches the character in Target and so immediately we should try them to think about if we can do it with just trying all possible choices okay so thinking about all possible choices what can we do we have Target which is Aba right we of course need to go through the this target characters one by one two to find the match right and so in sort of these choices we need to think about what state are we choosing with right so here definitely one of the choices is the target index one of the things is the so basically if we find a match we will move Target let's say if we found the mesh for a so we found an a like here we'll move Target index to B if we find a match to be like here we'll move the target index to a so we definitely um can move with that and so we need the target index to tell us where we are at the Target string the other thing we would probably need is either we can either go through the words and in that case we need the index of the world but we also need to know where did we stop at each word because the problem says if you for example find a match for this C you no longer can use these two you can no longer use these two because they are before it so when you find the match you can no longer use anything to the left of it and so if we use word by word then we need to also maintain the index we stop it at let's call it J here so we need to tell the next word the next iteration that we can pick only from this position J plus one okay and that's actually a little bit tricky so must first think about if we can do it differently because that's tricky so the way we can think and also tricky and it would be expensive because we would have three values for this our state so let's see if we put the words like next to each other like this then we should be able to think about something so these are the indices of each word the words have the same length right so actually what we need is let's say we have an A here so for example here we have an A how many ways can we get an A from this first index well there is only this one and so there's only one way with the index is zero for this index there is only one way with this one for this index last one there are two ways to get an A and so for example if you want to match with this last one we know we can match it in two ways so that tells you that the frequency matters here we can use the frequency in some way so that's the first intuition the second intuition is that well let's just actually since we all since we only need to compare the in the foreign single index we can compare follow all the words we have and just check how many we can match right and so we just need to pass the actual column index for the words so let's just consider the words as rows and then let's just pass the index um let us call it I um as our state and now what are the choices we have and now our chases become at each point we have either we can find the match for Target index or no match okay so if there is no match well what's the next state then the next state is just going to the next column so if there is no match here I'll say if this was X there is no match we can just go to the next column which is I plus one and the target index stays the same I will call it t index just abbreviation here Target index stays the same and this called DX index Target index stays the same and we'll move to the next column now if there is a match what does that mean well it definitely means that the next state is going to be I we go to the next column because we already used the matches from the current column we can't use anything to the left anymore we can choose anything to the left anymore so we have to go to I Plus 1. but we also need to update our Target index because we just found the match it's good we move so we move our Target index to find the match for the next one okay so this is the states we do but by how much we should add the number of ways remember we are calculating the number of ways so this here the number of ways is just going to be there but here by how much should we add so here we just add the next state but here how much else we should add well let's say for example we find a match for this let's say we had another a here and we found two matches here and we are now looking for matches for B and let's say for BA we find three ways to get ba then and here we found two A's how many ways overall we can get total 2 multiplied by three six right because each of these three you can associate it with each of these two and that will give you six combinations and so here this actually if we sort of called our recursive function if we call it ways then this way is function here whatever we get from it we will multiply by how many matches we got so the matches for Target at Target index okay and then we add that to our results and then we add this also to our result because remember it's the number of ways so we need to add the number of ways for all the combinations for all the choices okay and so now it's we know what the choices we can do so we can just do a recursion there but now the question becomes what about what do we do to calculate this we can definitely calculate it each time but it's easier to just pre-calculate but it's easier to just pre-calculate but it's easier to just pre-calculate and we can use either a map or a table to just calculate for each character how many times it occurs in each Index right and that's a week since we have only uh lowercase English letters we have only 26 character so we can have some sort of occurrence array right that has the index as the row so the index here as the first um the first index will just tell us how many occurrences of each character in this column for this Index right and so and then the value here would be just for the character which we can just use art to get for a single character to get the representation in 26 range like this and that should be pretty much it um okay so let's run it actually on an example just to make sure um we understood this so if we copy this here go here quickly run it on an example so the first state we'll start with is with we have of course Target is still ABA so the first state is going to be Target is zero and the column zero okay and our column by the way ACA b c a and this is zero one two three okay so here we have two choices right we can either look for matches for this a or not look so first choice is not look well we'll just go to the next column and we still have we are still at index 0 for Target the second case is well there is one match for this a right so we know here we have one way definitely and then we the next state is going to be the next column which is one and then the next Target character which is one okay and now here why is it one to multiply by the whatever the number of ways we get from this because there is only one occurrence of a that matches here okay so now for this for example if we go down again we have two choices we can either go to the next column and still stay at one or we can go to the next column but move can we move by one here well depends if there is occurrences of B in this column well there is one here and so we can move and so two and by how much we multiply while we have just one occurrence of B so we'll multiply by just one there is one way just one way to get here um okay so we continue again two um so can we go can we take this a is there a match in column two there is no match so we only have one choice which is um no match choice and so no match Choice means we go to three column three and then which is index three and then two still two and so now at this point um at this point we um we'll look here is there a match for this a um there is there are actually two A's here and so here we go with um four so we are done so this is actually base case because we reached the end but we multiply by 2 because we found two occurrences which means we there are two ways okay and so if we bubble this up in this Branch we have only two ways because we multiply and multiply we have two ways and the parent can add up all the branches this brush also written something and this pattern will add it up and return it to its parent and so the base case you saw here is both can be we have two base cases one if we reach the end of Target then we are good that's we should count that as a way so if basically Target index is equal to the length of Target then we should count that as one number of way but if it's only let's say here maybe we reach 3 1 okay then this is we didn't find matches for all the target but here we've we reached the end of the world of the columns and so here I will return zero because it's not possible so those are the base cases but this is sort of the structure of branching that will happen um yeah and that's pretty much it this should give us the solution um we can just recurse using these two choices and then we can build this occurrences uh array and use that here and that will simplify the calculation for us right and each time we'll multiply by the number of ways we can get because of the number of characters we can the number of characters that match that we can get from each column um yeah so that's pretty much the idea let's cut it up and make sure it passes um okay so now let's implement this solution so the first thing we need is definitely our function which is ways and we said the two indexes we need is the index of the column and or the index in the words and the target index let's call it Target index and we said the base case is if we this reaches the end of Target then it's a good solution and so we need to count it but if we just reached the end of the words but we didn't find all them we didn't match all the characters of Target then we are not able to construct it and so we need to return zero in this case sorry this is the length of world zero because worlds have the same length and this is the number of characters in the world okay and now here we need to we have two choices one is skip right and the other is um you could call it consider or take or whatever you wanna yeah um or take if you can like take if you can that's sort of what we are doing here so for the Skip it's easy so we'd have our result we will this basically will start out as zero and we'll add each choice to it and so we'll return it at the end here so and so here for the skip well we want to add just skipping to the next column right so it's going to be I plus 1 but still same Target index because we didn't find any matches and then here we'll add a ways we'll skip to the next column again and then this is going to be um index plus one right because we need to find a match but we need to multiply it by the occurrence here so we'll create the array shortly so this is the occurrence of the what is the character well the character is just the character in Target so it's going to be Target at T index and then this is what we will use here to get the index in this array this is just will give us the index in the lowercase alphabet list okay and so if the character is not there we'll multiply this by zero and so this will not add anything which is what should happen because if we can if there is no match we shouldn't take it and so that's why this works let's actually um create this occurrence array so it's going to be 0 for each lowercase initially but we want to do it for each index for each column and so that's going to be range of the length of the words zero because words have the same length is this is the number of columns you could also call it just um columns like this and that way we can just reuse it here okay and now we to calculate it we'll just go through every word and then enumerate all the characters in every word because remember this is the column index and this is the character I'll just call it like that um in any rate of w of the word and then for the character so we put the column and then the character we of course need to do the same thing here to get its representation in an index so that would be something like this minus the odd for a and we'll count we will plus one because we it's in this column right and then we will start our recursive call well what's the start State well we start from the first column and from the first character of Target and then that's what we want to return but we also want to apply the math that the problem says we need to apply and so we can just take a mud like that this is going to be our mod 10 to the power of 9 plus 7 we apply the mod here and then we also need to apply the mod here and that should be it pretty much um except of course this has repetitive calls this multiple times in the recalculate so we'll need to memorize but first let's run it looks good last memo add memorization here so we just need a map and then we need to check if it's present so if these two in this state are already present we want to just return them so I in the Target index now if they are not there we just want to set them before returning and then we can just return okay so this should work let's submit and this passes our test cases um yeah so that's pretty much it just trying all the different ways um and then memory using memorization and the main trick is to think about it in terms of columns for the words and then using this table to record the occurrences so that you can easily calculate the number of ways that we obtain from each match um yeah so that's pretty much it thanks for watching and see you on the next one bye
Number of Ways to Form a Target String Given a Dictionary
friendly-movies-streamed-last-month
You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`. * Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. * Repeat the process until you form the string `target`. **Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba " **Output:** 6 **Explanation:** There are 6 ways to form target. "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ") **Example 2:** **Input:** words = \[ "abba ", "baab "\], target = "bab " **Output:** 4 **Explanation:** There are 4 ways to form target. "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ") "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ") "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ") "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ") **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * All strings in `words` have the same length. * `1 <= target.length <= 1000` * `words[i]` and `target` contain only lowercase English letters.
null
Database
Easy
null
122
hi guys welcome to algorithms made easy my name is khushboo and in this video we'll see the question best time to buy and sell stock part 2. you are given an array of prices where price at index i is the price of the given stock on ith t on each day you may decide to buy and or sell the stock you can hold at most one share of a stock at any given time however you can buy it and then immediately sell it on the same day find and return the maximum profit you can achieve here are a few examples that are given with the question and we'll see one of the examples while we see how we can solve this question so let's take this example wherein i have plotted the graph for this price so on day zero the price is seven on day one the price is one and so on over here we can see that we can attain a profit on this particular part and in this particular part why because we see that the price is increasing for this particular part of the array so what we need to find out in this array is the increasing sequence of the numbers and add all the differences from highest to lowest number that will give us the profit for these particular sections now let's focus on this particular part over here we have three transactions at point a b and c and the total profit that we can attain is c minus a which is the maximum profit that we can have now in order to find this we can either calculate c minus a or we can also calculate the profit at each transaction which is the transaction wherein i buy it a sell at b and buy it b and select c so this two transactions will also give me c minus a as this b gets cancelled out so what we get from this is that whenever we find a value that is higher than the current value we will calculate the profit at that point so if my previous value was lesser than this current value at which i am or my next value is greater than the current value whichever way you want to calculate it you can calculate the profit so this will be calculating the profit at each step and in this way you can go ahead and iterate over the array and find out the cumulative profit that you have earned throughout the number of days that you have been given so this was all about the theory behind solving the question i hope you have understood the logic that we need to apply so firstly i would recommend you to write down the code by yourself and if you get stuck somewhere you can follow the code which i'll be showing now so let's go ahead and code this particular approach that we talked about let's take a few variables the first one is n which is length of the prices array and we'll take profit that is going to be our result initially that will be 0 now what we are going to do is we are just going to iterate over the array so over here i will start with index 1 and compare price with previous one so let's take a for loop now if i'm getting a profit i'll add it in the profit variable and finally at the end i'll just return the profit let's run this code and it's giving a perfect result let's submit this and it got submitted so the time complexity for this particular approach is o of n for this for loop and the space complexity is o of 1 because we are not using any extra space other than this variables so that's it for this question guys i hope you liked the video do share your thoughts in the comments and also if you like the video please hit the like and subscribe button to get the updates on the new videos we post thank you for watching see you in the next one
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**. Find and return _the **maximum** profit you can achieve_. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 7 **Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. **Constraints:** * `1 <= prices.length <= 3 * 104` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming,Greedy
Medium
121,123,188,309,714
724
hello good evening friends good to see you again at code master quest today we've got another problem find pivot index and we are going to solve this question in Python so let's get started and find the question description in later here's the problem statement given an array of integer Norms we should calculate the pivot index of design and the period index is the index for the sum of all numbers strictly to the left of this index is equal to sum of all the numbers directly to the index is right and if the index is on the left edge of the array then the left sum is zero because there are no element on the left side and this also applies to the right edge of the eye right and at the end we should return to the leftmost pivot index and if no such index exists we should return -1 should return -1 should return -1 now let's look at the examples here uh for the first one if you got an input like this one we should return three because if you look at the index number three which is this one the sum of all the elements on the left side is equal to 11 and so on all the elements on the right side is also equal to 11 right so we should return 3 as output of this function now let's come back to the visual studio code and try to implement this problem in Python now and that's the first job let's define the function signature here so let's say solution and our function death pivot index itself nums which is going to be a list of integer and at the end we are returning an integer right so let's say return integer okay now I want to Define two variables to calculate the total sum of the values inside the input list and another one to keep track of the left sum editing at each index so let's say total sum is going to be sum for rounds and left sound is going to be zero okay now to fix this issue with the list let me imported at the top import actually from type in import list right okay now let me make the for Loop for I and value in enumerate now I'm and at each iteration I want to calculate the right sum and compare it to the left sum and if it's equal together we should return that Index right so let's say write sum it's going to be totalsa minus left sum before adding the value of the current index and minus value and if right sum is equal to left sum then we should return in this specific index which is going to be I otherwise we are going to add you know the value to the left sum so let's say less than plus equal to value and again if we went through this for Loop and we didn't find anything we should return -1 return anything we should return -1 return anything we should return -1 return minus now to test our implementation let me come back to the browser and copy the example from here let's come back to the visual studio code and paste it just right here okay now let me make an instance of the solution class so we go to solution then let's say print so pivot index for this input and we expect to have the 3 as a result open the terminal and run our function H3 right now as the last job let's try to submit our solution to later come back to the browser paste it here and then hit the submit button there we go here is the solution for this question thank you everyone
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
1,488
what's up everybody today we're gonna be talking about LICO problem 1488 avoid flood in the city so reading this problem was kind of confusing to be honest and I didn't understand it for like the first minute that I was reading it so if that's why you're here hopefully I can help explain it and you know you can solve it yourself or what have you but so let's sort of go over this problem we're given an array okay and in this array we're given two actually we're given actually two types of things even though they say they don't give us integers they give us one set of integers which are natural numbers 1 2 3 4 5 6 7 8 9 etc that tell you on that index day for example here index 1 it's gonna rain on the lake number 2 alternatively if there's a zero in the array we're given on day 2 0 1 2 it doesn't rain at all it doesn't rain on lake 0 it doesn't rain at all and what we have to do is on days where it doesn't rain choose a lake to dry such that a lake doesn't get rained on that already has water in it for example there's no solution to this problem it rains on lake 10 on the first day it rains on lake 20 and then it rains on lake 20 again there's no chance to dry the link ok alternatively for this problem there is a solution rains on lake 1 rains on lake 2 we dry lake 1 or 2 here it doesn't really matter and then it rains on like 1 &amp; 2 and then it rains on like 1 &amp; 2 and then it rains on like 1 &amp; 2 and then it's over doesn't matter no lake flooded because rain didn't rain on a lake those already there already had water ok so let's sort of move into the problem so let's just get right into the algorithm and sort of what the intuition is from that the intuition is basically we want to be drying lakes that are coming up soon okay if we had a lake that was rained on day zero and it wasn't gonna have rain again for you know a billion days or a billion years we wouldn't really care that much right so we want to be able to know what day is coming up next and this is typically when you want to know some ordering in the list you can accomplish that with a pre-processing step in linear time all pre-processing step in linear time all pre-processing step in linear time all right we can do one pass over the list and what we're gonna do is we're gonna create this set or this hash I guess that's it and in this we're gonna record where we see certain lakes so Lake number nine we see it index zero and seven Lake number two we see it index one three and six and this is gonna allow us to when we're moving through the list again for the second time when we're trying to figure out which lakes to dry on non rainy days we're gonna be able to look at this and sort of analyze it so the basic idea is we want to keep two data structures the first thing is gonna be a set it's gonna tell us which lakes are full and that's pretty intuitive right so on day one we'll see nine will put nine in this set okay that sounds useful and this is useful because if this were nine right we would be immediately able to tell that there's no solution and we just return the empty array right the second thing we need to keep is the next-best index to dry let's say we fell next-best index to dry let's say we fell next-best index to dry let's say we fell to a nine into the full lakes we get to this dry day you can probably see immediately well we need to dry to write because two is right after it so we need some data structure some ordering of two and nine such that we know two is coming up next so long story short we're gonna use a min heap in general whenever you hear something like we need the next thing in the list or we need the next best thing a heap is gonna be your go to write a heap is gonna be sort of what you're really most commonly gonna use to solve problems like this and we're gonna stuff indices into this heap we're gonna stuff the next index of that lake so when we start and we add nine in we're gonna put burn across out in zero we already saw an X zero and we're gonna add seven into our min-hee we're gonna add seven into our min-hee we're gonna add seven into our min-hee so if this were a rainy if the sort of dry to here we would pop off the min-heap and we would you know dry seven min-heap and we would you know dry seven min-heap and we would you know dry seven but we you know we get to day one we see to see the two we cross off the index we're at the add in the next index so three well that's coming up sooner and seven so we will put it in the min heap and it'll reorganize itself a heapify right and three will be on the top and once we get to day two we will pop off from our mini so we'll pop off three so go away I am and we'll say okay what's it index three right index three is coming up next right this is the next sort of lake that's full that's coming up next well we look in this array well too is it three so we put two in our solution array right in everyday that has a lake that it's raining on is like a negative one just by definition of the problem all right this is gonna get a little bit messy but we can imagine some separating line there and so you know we'll get to three and eventually you know this gets removed on day three or removed on day 2 and then it gets riad it on day 3 and we look up here and we go oh ok 6 is the next index so we add 6 into this min-heap and we get to add 6 into this min-heap and we get to add 6 into this min-heap and we get to day number 4 and we pop 6 off the mini but we put it here and then we get to day 5 and we pop 7 off the minivan we put it here and while we're doing this also we're removing stuff from the full Lakes as we're clearing it up sorry these aren't 6 &amp; 7 clearing it up sorry these aren't 6 &amp; 7 clearing it up sorry these aren't 6 &amp; 7 these are the value at that index so when we popped off here it was 6 well value 2 is it index 6 so we put a 2 here right and then value 9 is at index 7 so we would put a 9 here and you know that makes a little bit more sense now that I know wrote it correctly and this is sort of our solution and you can see that if you sort of just chose to fill in a nine here you would run into trouble because once you got to day 3 it would rain on lake number 2 I'm not going to show the code anymore in the videos the codes going to be below in the comments if you sort of liked the pace of this and prefer this instead that this is pretty much gonna be the sort of model moving forward gonna be sort of less sort of talking and more so it just jumped me right in so if you don't want to see more videos like subscribe but thanks I hope to see you the next one
Avoid Flood in The City
sort-integers-by-the-power-value
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake. Given an integer array `rains` where: * `rains[i] > 0` means there will be rains over the `rains[i]` lake. * `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**. Return _an array `ans`_ where: * `ans.length == rains.length` * `ans[i] == -1` if `rains[i] > 0`. * `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`. If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**. Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. **Example 1:** **Input:** rains = \[1,2,3,4\] **Output:** \[-1,-1,-1,-1\] **Explanation:** After the first day full lakes are \[1\] After the second day full lakes are \[1,2\] After the third day full lakes are \[1,2,3\] After the fourth day full lakes are \[1,2,3,4\] There's no day to dry any lake and there is no flood in any lake. **Example 2:** **Input:** rains = \[1,2,0,0,2,1\] **Output:** \[-1,-1,2,1,-1,-1\] **Explanation:** After the first day full lakes are \[1\] After the second day full lakes are \[1,2\] After the third day, we dry lake 2. Full lakes are \[1\] After the fourth day, we dry lake 1. There is no full lakes. After the fifth day, full lakes are \[2\]. After the sixth day, full lakes are \[1,2\]. It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario. **Example 3:** **Input:** rains = \[1,2,0,1,2\] **Output:** \[\] **Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day. After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood. **Constraints:** * `1 <= rains.length <= 105` * `0 <= rains[i] <= 109`
Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list.
Dynamic Programming,Memoization,Sorting
Medium
null
11
hello everyone and welcome to today's programming video in today's video we will solve the lead code problem called container with most water in this problem we have been given an integer array height of length n and each value or each number in that array represents the height of a line the vertical height or height of line so what we need to calculate here is the maximum amount of water a container can store and two lines uh together form a container so we need to find two such lines where the amount of water we can store is maximum and we need to return the maximum amount of water that we can store there and we have been also given that we can't slant the container so let's first understand how we can calculate the amount of water between two lines in general in this example we have been given the array height which contains the heights of lines here and between any two lines we can store certain amount of water and we need to find what is the maximum amount of water we can store IQ on these line Heights so let's look at the two red lines which we have here at index 1 and index 8. because we're filling water here we can only fill it up to the brim and that is the smaller of the two heights so the breadth if you want to calculate the area we need length and breadth so the length here would be the distance between the two red lines and that is eight minus one seven and the breadth would be 7 here because that is the smaller of the two line how light and therefore 7 times 7 equals 49 and that would be the amount of water we can store between line index 1 and line at index 8. now let's think of an approach we can use to solve this uh problem so let's uh take an example of lines and try and find uh you know what is the maximum amount we can store between there let's take a subset of lines and uh see how we can find the maximum amount of water we can store in between those lines so let's take uh the lines between say 3 and 6 here so ignore the lines outside of this green box for a moment so let's say we want to find the maximum amount of water between uh between these lines between three and six so it could be three and six or three and four and six we don't know yet so uh let's start off with three and six so between three and six how much water can we store so the distance between three and six is the length is 3 times how much is the maximum height of water we can have and that's actually just here that is 2 so 3 times 2 is 6 so that's same Out of Water we can store here now um let's see uh between um three and five so let's say three and five how much water can we store so the distance the length is two because five minus 3 is 2 and the minimum height is here is two again uh and that is 2 times 4 2 times 2 is 4. um okay so we check three and five um now let's check three and four so between three and four how much water can we store that is one times uh the smallest of the two and that is um the height too and that happens to be two so we can observe here that uh between 3 and 6 the lines three the line set in dice is three and six um the amount of water we can store um between three and six is more than what we can store between 3 and 4 and three and five and that is because 3 happens to be the smaller of the two so the line height at 3 is 2 and the line height at 6 is 8. so no matter what Heights the lines are in between it's always going to end up being like the bottleneck here three so if you know let's say the line at uh index 4 was say 1 then it would be even less so um there's no point in checking so because three because the high line of because the height of the line is 3 is less than the height of the line at six okay this is important the height of the line at 3 is less than the height of line is six we don't need to bother checking the amount of water between 3 and 5 and 3 and 4 because it's going to be less than the amount of water between 3 and 6. let me give you another example to clarify this point now ignore the lines outside of this purple color now let's calculate the amount of water we can store between 1 and 4. so 1 and 4 how much can we store so we can store uh length times breadth so that's four minus one three is the length and what is the breadth or yeah breadth of this rectangle which it will be smaller of the two because that is the max amount we can fill up to so that will be five and that's to multiply it we get 15. now let's look at um 4 and 2. so remember the point I'm trying to drive home is that given two lines okay the shorter line becomes like the uh you know the kind of bottleneck uh between the lines uh we have so for example now if you check two and four so I met bottleneck so actually it's kind of threshold uh so between two and four we have two times uh the max is actually uh five again so 10 and between three and four it's even less uh it's just this much water here so it will be one so four minus 3 is 1 times 2 so that's uh has two so we can see here that um given any two lines let's say these red lines at index one and eight and we can see that the smaller of the two lines is the is at index eight and that is the maximum amount of water we can fill we do not need to check the amounts of water between uh two and eight three and eight four and eight five and eight six and eight seven and eight because it is going to be less than one and eight because eight is the threshold between one and eight it's the smaller of the two so let's say we have uh two pointers uh I and J okay now we can calculate the area between these two now before we iterate through this array we can store Max as zero and that will be our result um so we calculate the area between I and J once we've calculated the area we can check if it's greater than max if it's greater than Max then you know we uh update Max only if it's you know greater than Max once we've done that we can check okay which one is got a smaller height in this case I where the line at index I has got a smaller height that means that we don't need to check the areas between uh 0 and 7 0 and 6 0 and 5 0 and 4 0 and 3 0 and 2 0 and 1. there's no need to check that so all we need to do here is increment I by one position and once you've done that we now recalculate the area uh and then if it's greater than Max area we update it um at this point we can see that the height of the line at I is 8 and the height at index 8 is 7 um so we have already calculated area between these two there is no point in calculating the area between 2 and 8 3 and 8 4 and 8 and so on and so forth so we simply move j one position to the left and that way we are kind of skipping over the in between uh you know lines and optimizing the calculation so we will recalculate the area and if it's greater than Max we will uh you know uh update Max so we'll continue this Loop till I is less than J and when the loop finishes we will have our result in the max variable let's look at the code and implement this logic initialize my uh two pointers I and J so I points to the first line and J points to the last line now I will iterate through this array and in every iteration we will update either I or J and in each iteration we will check you know which is the maximum area so let's Define a variable for the maximum area so let's now calculate the area between the line set index I and J as you've seen earlier it will be length into breadth the length is the distance between I and J breadth is the smaller of the two height once you've calculated the area let's see if it is larger than the maximum area that we have calculated so far and if it's uh greater than the max area we'll update Max area the max to be the new area that we just calculated now we saw that um there's no point in calculating the area between the smaller of the height and all the in between Heights so for example uh you know if you wanted to check 0 and 8 because the line it index 0 is smaller than the line at index 8 there is no need to calculate the area between 0 1 0 2 0 3 up till 0 7 it is enough to calculate just the area between 0 and 8 because all the other areas between 0 and 8 will be less than the area between 0 and 8. so I'm checking that if the height of the line at index I is less than the height of the line at index J then I don't need to calculate the in between uh areas I increment I by 1. um otherwise I decrement J by 1. and that way we will uh you know finish this Loop eventually and then finally we will return the maximum area that we have calculated or the maximum amount of water that a container can store okay um let's give it a run let's run some more test cases here we've got foreign thank you very much for watching and hope you like the video and find it useful please do remember to like And subscribe thank you bye
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
83
okay to solve one of the problem on lead code which is related to remove duplicates from the sorted list so you will be given a sorted list uh this is linked list not normally so you will give a sorted link list and you need to remove the duplicates from it so for example if uh 1 2 is given so the next value will always be great either greater or it will be equal so if i skip the next element and if i'll map it to the next to next then that this duplicate zero will be removed okay um so in case of this uh if we'll remove all the duplicates then output should be one two three so uh the problem uh is quite simple uh we just need to link if it is uh the duplicate value we need to link it to the next element so uh here our list node is given so i'll have a list node current equal to head i'll create it on the current value so while um current is not equal to null and current dot next is also not equal to null and why null i need to check so that it i'll not go up beyond this now the main condition is if current dot next dot val if it is greater than current.val it means it is a valid value current.val it means it is a valid value current.val it means it is a valid value so if one after when it is 2 then it is a valid value but if it is 1 equal to 1 then it is not valid it is duplicate so uh in this case to remove it i current dot next equal to current dot next so i'll jump from uh one uh to directly two and if it is greater than then what i'll do current or equal to current.next and at the end i'll return this head okay uh i think this will solve this uh problem if it is valid value we just need to go to the next if it is a duplicate value then we need to go from next to next okay let's see if now the problem on the solution is correct yep it is success means the solution is correct so here i hope you understood uh this was the given sorted link list where we just need to remove those duplicates so since it is sorted so that's why it was easy to undo this and we just need to point uh so in linked list if you need to remove uh node we need to point the next element to next element okay so like if this is duplicate then i will instead of pointing one to one i'll point one to directly to here okay so this problem statement is clear to you this solution is clear to you uh if you think the videos are helpful do like the video and subscribe to the channel thank you so much for watching
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
105
in this video we're going to take a look at a legal problem called construct binary tree from pre-order and in order binary tree from pre-order and in order binary tree from pre-order and in order traversal so given two integer array pre-order and so given two integer array pre-order and so given two integer array pre-order and post-order post-order post-order uh where pre-order is the pre or uh where pre-order is the pre or uh where pre-order is the pre or traversal of the binary tree and the in order is the in-order and the in order is the in-order and the in order is the in-order traversal of about of the same binary tree so construct the binary tree based on those two array that are given and return the binary tree's root note so here you can see we have a binary tree like this right so we have a pre-order traversal pre-order traversal pre-order traversal uh array and then the in-order traversal uh array and then the in-order traversal uh array and then the in-order traversal array so in the in pre-order traversal the so in the in pre-order traversal the so in the in pre-order traversal the order goes something like this where we traverse the current node then the left node and then the right node right the order always follow like this so is it going to be the current node the left node and the right node for the in order traversal is going to be the left node first and then the right node sorry the left node first and then the current node and then the right node right so this is in order traversal right so you can see that in the in order traversal nine uh is at the left right this so three is on is the root node and nine to the left of the subtree and 15 and 20 and seven is on the right subtree for the pre-order traversal pre-order traversal pre-order traversal you can see the root is that the first is going to be the first element in the array and then followed by the left subtree which is nine the right subtree 20 15 and seven right so based on those two the goal is that based on those two input arrays we want to construct a binary tree and we want to return the root note at the end so how can we do this so to solve this problem we know that the root node is going to be the first element in the pre-order pre-order pre-order array right and based on that we can just find that roon node which is node 3 in the in order array because we know that it says that the answer must exist right so it's guaranteed to be the pre-order traversal of the tree pre-order traversal of the tree pre-order traversal of the tree and the in order array is going to be guaranteed to be the in order uh traversal of the tree and the all values are unique so based on that we can just find that elements right we can just find that element um in the in order array so no three in the in-order race right so no three in the in-order race right so no three in the in-order race right here right so in this case what we can do is we know that everything on the left subtree is gonna be on the left side of this current node three and then everything on the right of the array is gonna be on the right subtree and using that information we can be able to instruct the binary tree and by simply starting from the current node right node three we build the node build a tree node and then we're just going to use this information we're going to build our left subtree right it's always going to be left and then the right so left side and then the right side first we build the left side and then we build the right side so the left side is only there's only one values in this case 9 so we add nine onto the um so in this case no root note down left is gonna be no nine and the right side is gonna be everything on here right and we know that 20 is going to be the root note of the right subtree right the root note of the right subtree so some right subtree is this right so the root knows 20. so in this case the node node3 dot right is going to be node20 then we have to do is we just going to go look for node 20 in the pre-order or i look for node 20 in the pre-order or i look for node 20 in the pre-order or i should say in order array once we find that element we're just going to um be able to determine which node is on the current nodes left and which node is on the current node's right so we know that 15 is on the left side of node 20 and the 7 is going to be on the right side of node 20. so we can just um we can just be able to add that node like build the subtree right we can build its subtree and then so on and so forth right so the goal is pretty much we're just going to iterate each and every single elements in the array and then build the tree so the time complexity in this case is going to be in so let's try to see how we can be able to do this in code so to solve this problem in code um let's try to make those arrays in a global variable so we're going to have a global variable called integer array camel case pre-order array and then camel case pre-order array and then camel case pre-order array and then we also have a in order array i'm going to say pre-order is equal to i'm going to say pre-order is equal to i'm going to say pre-order is equal to pre-order pre-order pre-order and in order is going to be equal to in order array and we also have the size which is going to be the length of the in-order ray that the length of the in-order ray that the length of the in-order ray that length so i mentioned earlier the time complexity is going to be big o of n where n is basically the number of elements that we have in the array right so it doesn't matter which array because they all have the same length and then what we're going to do is we're going to use a um use a hash table to solve this problem now we can also use a like a for loop to find that element's index in the in order array but we don't have to we can use a hash table to store the elements each and every single element as the key in the in order array and then the value of the table is going to be the index in the inorder ray so that we can be able to find that element in a constant time on average right so we're going to say for each and every single element so we're going to use a hash table so we're going to do is we're going to say hashmap.put say hashmap.put say hashmap.put i'm going to put the in order at i as the key and i is going to be the index right it's going to be the value of the in the table so that when we want to retrieve the index right uh in the in order array we can be able to just pass in the elements value instead of the you know instead of just using a for loop to find the element in a linear time complexity so in this case what we're going to do then is we're just going to use a dfs method to build our tree so we're going to say tree node right so tree node this will return the root node is equal to dfs and basically we're just going to pass in the range right we're going to pass in the range where it's start and where is end and we're going to uh basically do our debt for search to build our tree so in this case uh we're also going to have a index so this index value basically is going to be the index for the pre-order pre-order pre-order pre-order array right so we have the dfs pre-order array right so we have the dfs pre-order array right so we have the dfs and the starting range is going to be 0 and the n index is going to be n minus 1 which is basically the search range right um and then at the end we're just going to return the route okay so now let's try to build our dfs method so integer start right so s stand for start and e stand for end so basically what we're gonna do is we're going to start with this range right all we do care about is the range if the range is gone right there's no more range then we can just return right we can just start we can just return the uh null so it actually returns a tree node so what we're going to do is that if so we're going to define our base case so once we have our base case uh done we're just going to determine and build our tree right so build our build a tree node right build a tree node once we build a tree node we're going to uh find the index in the in order array for that element and then once we find that index just like i talked about before once we find that index we can be able to uh determine which uh which element like the range for the left subtree and the range for the right subtree right so in this case let's say this is the root node for the right and then we have the left we have the right so this is basically everything on the left subtree and this is basically on the right subtree so we can have like a range we can just pass down the range and if that range is gone we can just uh um search on the search uh like traverse the other path right so in this case what we're gonna do is we're just going to traverse the left side because in the pre-order traversal is going to be pre-order traversal is going to be pre-order traversal is going to be current node left the right so once we build our tree node we're going to um like build our traverse the left side right traverse the left side to build our left subtree or i should say just build left subtree and then we're going to build our right subtree right so once we have our left and the right subtract is done we can just return the tree node that we created uh here right so let's try to define our base case so our base case is that if s is bigger than e we can just return null right now then what we're going to do is we're going to build our tree node so current tree node is equal to tree node and we're going to pass in a value so in this case we have the index right so this case in this case what we're going to do is we're going to say pre-order at index which is going to be pre-order at index which is going to be pre-order at index which is going to be the first the which is going to be the first element in the array which is no three so in this case we have current val is equal to pre-order array at index pre-order array at index pre-order array at index right this will give us a value and we want to make sure that we increase increment the index by 1 for the next well before we traverse the left subtree right so we pass in the current value for the current tree node so once we have the root node right we what we're gonna do is we're gonna build our left subtree so current the left subtree is going to be dfs right we're going to pass in the starting point which is going to be the start and the end point in the endpoint is actually going to be the uh the index right the index for the um for the in order array for the current roon node so uh in this case we have a midpoint which is equal to um so it's kind of like binary search right we have like a midpoint search on the left side search on the right side kind of thing so the midpoint is going to be um uh the hashmap dot get right uh current.value or just current.value or just current.value or just current value is fine they're all the same so we get the index once we get index we can determine our range it's going to be mid minus one and the right subtree is going to be the current dot right is equal to dfs mid plus one to the end right so we have a range there and at the end after we build our left our right which is going to return our current node right so basically we're just going to return the current node after we build our current subtree right so we have our left subtree build the right substrate build and then our job is done so let's try to run the code okay so let's try to submit and here you can see we have our success so this is how we solve the construct binary tree from pre-order and construct binary tree from pre-order and construct binary tree from pre-order and from pre-order and in-order traversal from pre-order and in-order traversal from pre-order and in-order traversal let go problem
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
380
hey everybody this is Larry this is day 12 of to June the code daily challenge hit the like button hit the subscribe button let me know what you think how did you do in this farm did you do okay was it interesting and all that stuff okay cool insert the lead get random or one design a data structure that supports all following operations and amortized averaged or one time insert wire which inserts value we move value which removes awhile you get random which returns a random element from the current set of elements each element must have the same probability of getting being returned okay yeah the first thing I think of to get old one is to put insert and remove over in like what I said it's very it's hard to get it without that maybe other than some counting sort or something like that but that also allows you to handle tubes and stuff like that and of course there are the caveat order the thing to always mention is that with the hash table or map now job one is a little bit not as tight but that's okay I think that's usually on interviews that's why would you look at one and look at random you need a way to get a random element from a set which is a little bit tricky I'm thinking of just like figure out a way to map order in so good why you into a set and we I think the way that I want to think about it is yeah and because I think that the other the way that I will implement it without the remove over exam is when we insert we just put it in an away and when we have an array we just get a random element from their way now how do we do the removal well when we remove an element the problem with what the good thing is that the order doesn't matter in the way so in a normal way let's just say in a normal way you know you have 1 2 3 4 5 6 7 8 9 10 or something like that and let's say you want to remove sex right you remove sex usually what you want the answer is to be this 1 2 3 4 5 7 8 9 10 but what we actually in this case we actually don't matter what don't this case we actually don't care because it's a set so you actually can and because you never see it anyway it's no in some random value you can actually just change it or not changed but that was delete sex keeping a placeholder and then move the last element ICS to that element so just moves to ten there and then we move the last element and the reason why we do this is well because that's what the problem asked for you needed to keep an old one otherwise we're moving an element from the list is going to always be on n on average because if you remove the first element it shifts everything from the right to the left right so okay so now that I think that I have a technique or an album and we could show that insert in this case would just be old one and we will go over again once we write the code because inserting to a set and appending to a list is ov1 removers we thought that should be all one and get random should just be also or one yeah okay so again the first thing I would also say is that in different languages you might do the randomness point differently yeah experiment a bit play a bit do whatever makes you that makes you feel comfortable but yeah I just want okay let's do it let's start coding it so soft.i and if you say this is equal to soft.i and if you say this is equal to soft.i and if you say this is equal to just a random this so that table is equal to a hash table so insert let's say if value is in self that table that means that what I guess technically this is a key but it's no computing but if the wire is already in table that means we don't have to do anything so we just return otherwise we want to append why you and then the index of this would be the length of salt on this may be minus one yeah because if that's so elements then it should be su and then now it's one so yeah something like that so that's easy to remove let's do the get random first and then the get random it should also be straightforward we just look at the list and get a random ID element give me a second actually I'm just going the pipeline random library I don't actually remember that much so I could just random so I could use random range random and I think there's also a choice in a sequence that's use choice today I think I did it on shrimp the other day with random and but you can do it in either case but yeah we'll just choose that choice so return random that choice salt on this and of course on an interview just ask what they prefer because this is just of course this is just like soft on this well like random dog random and or something like that from 0 to length of Southdown list - 1 maybe something like that right list - 1 maybe something like that right list - 1 maybe something like that right so did a couple of ways to do it they're all equivalent kipper tick and I buy one but just now communicator interviewer to make sure that you know it's okay to do what you're doing and also even if you do it the other way you do it this way be like ow I know that there's a standard library in Python that does this so I would have done it that way but of course you know in an interview things are a little artificial right obviously anyway we move oh okay we did what we said so okay let you say if Wow is in it's not in so if this is this value is not in the table that we don't have to care about it I think we don't have to return any penguin yeah okay well I'm glad to return okay I didn't notice - glad to return okay I didn't notice - glad to return okay I didn't notice - you didn't say but you have to return triggers insert correct later okay so we have to mix um so this is for us return true so now we move remove one from the set okay and then return true so obviously moved ten it's true okay so this is for Stan and then at the end return true and then how do we remove well the index is equal to self that table well and then now what do we say we want to get the last element and then move it here right so dot this or index yes you go to subtitle this of last element so that's just negative 1 in Python but you could do like n minus negative 1 or something like that and then the sub down list that pop I think pop love should return to it should remove the element that's to the right and that's my syntax all for that general idea should be okay and then now we remove it from the table and we remove the last one and then we want to update the element that we just updated to the new index okay I think that should make sense unless I have like an op I'm on a typo it is true didn't you tell you it's correct or not okay that's just for funsies we put a few more looks okay let me just submit it then ooh one time ever remove insert I know we move insert huh okay I mean like I said off by once always a little tricky but which so it's having issues equipment move which we move isn't having issues with oh I see because hmm I didn't miss in that case but the thing is basically if you're removing the last element on a list and this is not true so okay so that's this here first and I think that should be okay I was just to be frank I'm stupid careless with the ordering of things and the reason why we want this line here instead of where we had before I just forgot to do it and then I forgot to think about it cuz I was a little bit confident so not in a good way Allegan maybe but um oh yeah but basically I thought about this vows quite typing it but then I just forgot to follow up but which is that when index is the last element then this pops this removes the element and this we must anomaly from the table so when you go to here it already doesn't exist so that's why I failed but once we change the order back up you know this is basically no art because it sets what it used to be to itself and then it pops it and this is also no well even though I mean I don't know why but it's a spin up yeah okay so now that submit again oops cool yeah so this is all one because in this initialization solve one insert is all one because we a pen is all one putting some in hash tables or one we move those also or one cuz pop removing the last element or one deleting an element from the tables or one and these are just all you know hash table lookups and get random is all one because it just takes a random number from the list this is true I hope that's true because actually I don't know the performance profile random that choice so maybe I lied here that's maybe I lied to be honest so maybe I actually would we'll do it the other thing where you take a random int from 0 to n because I'm not sure about implementation and if I had intimate time I would look at the source code to kind of make sure because there a couple of ways you can implement from this and especially if you take it from a sequence you can assume that it was a sequence then it may go for one by one versus taking a random element from index so actually I might have lied to you here so make sure you know your library and the performance special for an interview you're about to show off and like what I did it's probably still fast enough but because some would a lot of these things that he's in pipeline is implemented and see but that said make sure you know your implementation otherwise some ego I interview it would be like are you sure just like either now I'll be like huh you all right so yes what this may be oh and now that I think about it again but there is a one way of writing it which is why you know we did it this way right random so this should be one for sure well we're here not so sure now dad think about it again that's my bad cool yeah this is a very data structure problem so you probably won't get this on a competitive programming not like this and in competitive programming it doesn't really matter that much between oh one and O of log n so but in an interview that's led to either question and it prize a reasonable question to ask though I don't know because I think doing the key observation for this one for an interview or just prom in general is the thing about removing an element in or one time and noticing that it does not matter that don't water shifting doesn't matter so you could do something like this which is a little bit of a weird trivia slash trick it doesn't really come up that much in real life I don't think what is I haven't really been ever come up something off my top of my head so do it as you will better but still was an interesting trivia interesting farm interesting problem solving and yeah yet do I have with this problem let me know what you're playing hit the like button to subscribe but now see how tomorrow bye
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
875
hello everyone welcome to day twentieth of january code challenge and the question that we have in today is coco eating bananas here in this question we are given the piles of bananas in the form of an array also there is a person named coco who decides to eat bananas but are at the eating speed of k each hour she chooses some piles of the bananas and eat k bananas from that pile if the bile has less than k banana she eats all of them instead and will not eat any more bananas during that hour what do we need to do in this question we need to identify the minimum integer k such that she is able to eat all the bananas within the given hr's so we are given the edge count up till which she is allowed to eat these bananas and the rules of eating those bananas across these piles we need to tell that value of k the minimum one using which she is able to finish all the piles within the specified timestamp so i'll talk about it more in the presentation the pro that we are going to use to solve this question will be binary search so let's quickly move on to the ppt where i'll tell you how to go about the algo coco eating bananas lead code is 875 and let's get started with the first example that was specified in the question here the piles are specified as 3 8 7 11 and the total number of rs that are specified as eight so let's hypothetically assume that the value of k happens to be 6 in this case and if i ask you whether the value of k that is 6 will fit in this complete piles let's try and calculate how much time will it take will it be less than or equal to eight so let's check that we have the pi k value as six so let's start with the iteration we see three other three divided by six gives us zero that means it will contribute to one r let's proceed ahead 6 divided by 6 again gives us 1 it will contribute to 1 r we have 7 by 6 as of 1 7 divided by 6 is 1 however there is a remainder left which is one so that will contribute to another r so the value would be two next we have eleven by six is it's again one also we have a remainder left which is five so it will again contribute to two so in totality how many hours would it take one two four six it's gonna take six hours so this is within the limits of h that means the value of six can one of the probable solution for this input array now we know given a value of k how can we calculate the number of hours it takes to eat the entire pile and we can compare it with the value h we can use this to finally arrive at the minimum value of k that will support within the range of h how can we do that we'll apply something similar to range based binary search approach that we did few days back as well here in this case we'll take the low value as one because that's the first positive value and the higher value can be taken as the maximum value across these set of piles that is 11. so let's get started let's take low as one high as 11 and let's calculate the middle pointer the middle turns out to be 6 1 plus 11 by 2 gives me 6 and let's calculate the number of hours it takes given the fact that k happens to be 6 it again takes 6 hours and 6 happens to be less than h so what we can what we should do in such case we should decrement the high pointer so that we want we arrive at the lower value of k so h gets decremented to mid so now h points to 6 and let's repeat the process let me just change the color of pen and we have low as 1 high as 6 what is the middle value turns out to be 3 let's calculate the number of r's it takes corresponding to k as 3 so 3 by 3 gives me 1 6 by 3 gives me 2 7 by 3 gives me 3 11 by 3 gives me 4 what are the total sum of these 1 plus 2 is 3 plus 3 is 6 x plus 4 is 10 it takes 10 hours if the value of k happens to be 3 so it is it has violated the condition the upper limit of h which is eight what do we do in such case we increment the low pointer to mid plus one uh so low gets updated to four now we have low pointing to 4 and high pointing to 6 let's proceed ahead and let me just change the color of pen we have low pointing to 4 and high pointing to 6 let's calculate the middle pointer the middle turns out to be five and let's proceed with the same calculation of ours to eat the entire piles five by three by five gives me one plus six by five gives me two plus 7 by 5 gives me 2 plus 11 by 5 gives me 3 so what is the total sum turns out to be 2 plus 3 is 5 plus 2 is 7 plus 1 is 8 so it is within the range h is equal it is equal to the value of h that we have what do we do in such case we again update the high pointer so as to reconfirm whether it's the least possible value or not so h gets updated to mid now h is pointing to 5 and low is pointing to 4. let's do the next iteration and now we have low at 4 and high at 5. let's recalculate the middle pointer the middle turns out to be 4 and corresponding to 4 let's calculate the number of hours it takes so 3 by 4 corresponds to 1 plus 6 by 4 corresponds to 2 plus 7 by 4 corresponds to 2 plus eleven by four corresponds to three again it turns out to be eight and what do we do in such case we decrement the high pointer to mid high gets updated to four low is also pointing to four how is high is also pointing to four the loop aborts and we say that four is a minimum possible value let's quickly talk about the coding section where i'll exactly do the same steps as i have just talked so let's move on to the coding part and here i have created a helper method it's possible to eat bananas where i'm i pass in the pile set i pass in the rs value that i have in the input passed and i assume that this is a probable value of k so this is a pretty simple and straightforward method you calculate the total hours it takes to eat the entire piles and you compare it with the value of r that we have the main character of the problem lies in writing the binary search approach appropriately so we have a low value set to 1 the high value set to the maximum value across the pile set and we go with the standard way of writing the binary search approach on the range based values where low is less than high you calculate the middle one if it's possible to eat all bananas what do you update low to mid plus one otherwise you update mid to high in the end you simply return the value of low pretty simple and straightforward nothing rocket science we have been doing this in the past and we have sold plenty of questions on these links i'm not sure why did it take five uh 78 milliseconds probably i'm connected to vpn but let's just ignore that this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to channel thanks for being here have a great day and stay tuned for more updates from coding recorded i'll see you tomorrow with another fresh question but till then good bye
Koko Eating Bananas
longest-mountain-in-array
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. **Example 1:** **Input:** piles = \[3,6,7,11\], h = 8 **Output:** 4 **Example 2:** **Input:** piles = \[30,11,23,4,20\], h = 5 **Output:** 30 **Example 3:** **Input:** piles = \[30,11,23,4,20\], h = 6 **Output:** 23 **Constraints:** * `1 <= piles.length <= 104` * `piles.length <= h <= 109` * `1 <= piles[i] <= 109`
null
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
1766,2205
1,743
hey there everyone welcome back to lead coding so it is 8 am in the morning and i am solving the contest number 226 it is the second problem of the contest i'm gonna upload this soon after the contest ends so do hit the subscribe button to get more such content in future as well and press the bell icon because i am frequently uploading videos all right so now let us start solving the question so there's an integer array nums that consist of n unique elements but you have forgotten it however you do remember every pair of adjacent element in nums you are given a 2d integer array adjacent pair of size n minus 1 where adjacent i it denotes a pair which is adjacent to each other in the original array it is guaranteed that every adjacent pair of nums i and nums i plus 1 will exist in the array which is given to us all right so let us say if the original array that we have to find out is one two three four so how many adjacent pairs are there so one pair is one comma two or two comma one so it is present here then another pair at the same pair is two comma three so two comma three or three comma two they both are adjacent so that is also present and the last three comma four three comma 4 is also present similarly for this example it is the same and for the last example also so we are given every adjacent pair now we have to uh we have to recompute or remake the original array using this all right so while i was solving this question the first thing that striked in my mind is like if we find out the adjacent elements of this and it is forming a chain like structure right so like if we have the adjacent elements and if we make a plot if we make a graph of it we will get a chain like structure for example let me just take this 2 1 3 4 3 2 1 3 4 and 3 2. if we have these adjacent pairs and if we make a graph using these so 2 and 1 are connected in the graph 3 and 4 are connected in the graph and last is 3 and 2. so 3 and 2 are connected in the graph now if we look into this if we start from 1 then 1 is connected to 2 is connected to 3 is connected to 4. it is forming a chain like structure we just have to find this chain and that is why we just have to create a graph using this one using the edges which are given so let us consider them as edges and make a graph using these edges so we will get a structure like this now in this structure what next we can do is to generate the output what next we can do is we can run a dfs starting from one or we can run our dfs starting from four why only one and four and why not two and three the reason is if we start a dfs let's say from two if we start a dfs from two then maybe it will go to 3 then the dfs will go to 4 and then it will go to 1 and that will give us the wrong answer it is going to give us 3 2 3 4 and at last it will give us 1. i think this one wait a second two and three and four and yeah this is not correct i think all right so we have to start from either terminal so the terminal is one or four how we can know the terminal so when we create the graph we will be creating the graph with the help of maps or unordered maps so corresponding so map of two corresponding to two what i'm gonna store i will be storing one and so two is adjacent to one and three corresponding to three i'm going to store two and four inside the map this is how we create the graphs right then adjacent map of one is only two and map of four is only three so there are two elements inside the map which are adjacent to only one elements and there are other rest of the elements are adjacent to two elements so these two are the terminals let me just uh try to explain this better with the help of the code so let us go to the code here so the first step is to create the map or the graph i'm going to use a map you can also use unordered map that will give you better complexity so this is my map i am going to each of the pair one by one let me denote the adjacent pair by a and corresponding to a of 0 i am going to push back a of 1 and corresponding to a of 1 i am going to push back a of 0 so this is how we create graph now our graph is done now we got that chain like structure now in that chain like structure i will have to find the terminals so i will be going to each of the element inside the map if a dot second a or second gives us the vector it is going to give us the vector that means how many elements are adjacent to a dot second dot size if it is equal to one then it is one of the terminals so we can take head we can take a variable head outside head and we can make the head as a dot first okay so now we have the terminal and now we have the graph that we need now in this graph i am going to do a dfs void dfs inside the dfs i am going to pass a map of end comma vector of int this is the graph then a set because we don't want the elements to be repeated otherwise our dfs like it might go in infinite time so this is this step involved in the dfs only we create a visited array or maybe a visited set you can also use another set here that will give you better complexity so i'm taking this visited now this is the element on which we are currently on and then last thing that i'm going to take is a vector that we need to return as the answer i'm going to generate this answer now i'm on the element a so if v dot find a is not equal to v dot and that means we have already computed this element we have already come to this element so we are just going to return from here otherwise we are visiting this element for the first time and hence we will be pushing it back in the answer and at the same time i will insert it into the visited array and then i will go to other elements from here for auto x belong to these are the elements adjacent to a map of a and i'm going to do the dfs on this dfs i will have to pass m then v then x and then answer so we are done with the dfs i think yeah now let me create the set of hint visited a vector of int answer and now i will be calling this function dfs from here pass m pass the visited array and then the head and the answer head is the element from which we are starting so after this let me try to run this to see if there are any compilation errors four three two one i think we are getting correct answer let me just submit it now and it got accepted all right so you can do slight modifications here you can use another set instead of sets and you can solve this problem in a better way but this is the first thing that came into my mind like forming a chain like structure so from the edges which were from the uh like elements which are given to us i considered them as edges and using those edges i was able to draw this graph now in this graph i can simply run a dfs the dfs could be started from either terminals so that it only goes into one direction there's the main motive behind starting it from the terminals basically if we start from one then it will only go into single direction that is from one it will go to two from two it will go to three from three it will go to four if we start from four it will go to three then one sorry three then two then one if we start from three then it will go let's say it goes to two first so it will go to two then it will go to one and then it will start again from four and that will give us the wrong answer that is why we will have to start from either terminal now you can tell me the time complexity and the space complexity of the solution into the entire comment section and i will verify it once the contest is over or if you want me to do it now you can easily understand the complexity here is because we are only having two edges at max so the complexity is only the total number of elements which are there that will be the space complexity now talking about the time complexity it is equal to the dfs that we are doing here so as there's a restriction on the number of edges it is uh equal to the total number of elements which are there in the uh in the output array we go off and we can see all right so this is it for the solution if you like the video make sure to hit that like button and do subscribe to the channel for more such content in future thank you
Restore the Array From Adjacent Pairs
count-substrings-that-differ-by-one-character
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Hash Table,String,Dynamic Programming
Medium
2256
222
hello guys welcome back to take tours and in this video we will see the count complete three notes problem which is from lead code day 23 of the June challenge so before seeing the problem statement let us now see the definition of complete binary tree so in a complete binary tree all the levels till the second last level are completely filled okay and the last level may or may not be completely filled so if not completely filled then the node should be filled from left to right and if it is completely filled then that type of complete binary tree is also known as a perfect binary tree okay so let us look at some examples in this case you can see that this first tree is having three levels and all the levels are completely filled with nodes so this is a complete binary tree and this is also known as a perfect binary tree okay in the second tree you can see that it is having three levels all the levels till the second-last level are completely filled second-last level are completely filled second-last level are completely filled and in the last level the nodes are filled from left to right okay so this is a complete binary tree but this is not a perfect monitor tree because these three is having just a single child it should have two children okay in the third tree you can see that there are three levels and the first two levels are completely filled but in the third level it is not completely filled and the nodes are not filled from left to right okay because this five is the child of three but it should be the right child of two otherwise it will not be a complete binary tree so this is not a complete binary tree in the similar way this is also not a complete binary tree because still the second-last level tree because still the second-last level tree because still the second-last level all the levels are completely filled but in the last level the node should be filled from left to right order so this five should have been the right shade of two and not the right child of three okay so I hope you've got the idea about the complete binary tree so let us now look at the problem statement in this problem we are given a complete binary tree and we are required to count the number of nodes in that tree so in this case let us assume that this is our complete binary tree and so if we count the number of nodes then it will come out to be five so I will be showing you two methods in order to solve this problem so let us look at the first method is a very simple one which is by using inorder preorder or post reversal and in this method we will basically be traversing each and every node of the tree therefore the time complexity will be order of n I will be providing the code for this method as well okay so is it possible to decrease the time complexity by using the special property of a complete binary tree so let us now look at the second method in this second method we are given a complete binary tree having four levels okay so you can see that all the levels till the second last level are completely filled and the last level are filled from left to right okay so if it would have been a perfect binary tree then the number of nodes would have been two to the power levels minus one so let us consider this tree only till level three so if you see this tree only till level three only this part then the number of nodes will be nothing but 2 to the power level minus 1 which will be nothing but 2 to the power 3 minus 1 it will come out to be 7 but a complete binary tree is not always a perfect binary tree so how do we count the number of nodes efficiently can we make use of the property of a complete binary tree in order to improve our algorithm so let us look at the two cases which are possible with this problem so in the first case or the complete binary tree will be nothing but a perfect ventilatory that is all the levels will be completely filled so if all the levels are completely filled then the number of nodes will be nothing but 2 to the power number of levels minus 1 which will be 15 in this case so how do we find whether a given complete binary tree is a perfect binary tree or not so what we will do is we will be starting from the root node and then we will traverse till we reach the left extreme node so the left or extreme node is 8 okay and we will also keep counting the depth so depth in this case will be equals to 4 that is you can also say 3 but I will say 4 okay so the right depth will be equals to 4 as well I will be starting with 1 I will consider that this is depth 1 that is level 1 then this will be level 4 okay so you can see that the left extreme level is 4 and the right extreme level is also 4 and they are equal so whenever left extreme level and right extreme level are equal then it will be a perfect mandatory so we will simply apply the formula while traversing we will also find the number of levels this is for in this case so it will be 2 to the power 4 minus 1 which will be 15 okay so this is case 1 and this is a simple case now the second case will be if our complete binary tree is not equals to the perfect binary tree then how will we solve this problem so in this case as well we will be starting with this first node and then what we will do we will find the left extreme depth and the right extreme depth so the left depth will be equals to L equals 2/5 and the right depth R will be equals 2/5 and the right depth R will be equals 2/5 and the right depth R will be equals to 4 so you can see that l and r are not equal so whenever they are not equal then we are sure that if we consider this current node as our root then it will not form a perfect binary tree so what will we do we will make two calls one to the left and other to the right so let us assume that we will first process the right call then what will happen now our current node is 3 okay and we will repeat the same process we will make the call till the left extreme node we will make the call till the right extreme node so in this case left will be coming out to be 3 levels and right will be coming out to be 3 levels so left and right are same this means that if we consider 3 as our root then this entire subtree rooted at 3 will also be a perfect mandatory and since we know that this is rooted at 3 and it is a perfect binary tree so we can find the number of nodes in this subtree by just using the formula 2 to the power number of levels minus 1 which will be equals to 7 ok so as soon as we find 7 we will simply return the value so it will be returning to 1 value equals to 7 now let us say we will process the left call so when we reach to this node 2 we will make the same call so what will we do we will make the left extreme call and the right extreme call so the left extreme will be giving us the value equals to L will be 4 and the right value will be equals to 3 since it has only 3 levels so what does this indicate it indicates that this is not a perfect binary tree if you - as a root so what will we do we will - as a root so what will we do we will - as a root so what will we do we will again make the left call and make the right call so we will assume that we are first processing the right call so if you assume this five as a root and make the left extreme call make the right extreme call then in this case L will be two and R will be equals to two so they both are equal therefore if you consider five as a root then this entire subtree will be a perfect mandatory so the number of nodes will be 2 to the power 2 minus 1 which will be equals to 3 so this node 5 will be returning value equals to 3 to this node 2 okay now we will process this node 4 so we will again measure the left extreme depth and the right extreme depth in this case left will be coming out to be 3 right will be coming out to be 3 so they both are equal therefore the number of nodes will be equals to 2 to the power 3 minus 1 which will be 7 since it is a perfect binary tree rooted at 4 now this node 4 will be returning a value 7 to this node 2 now since this node 2 received both the left and the right calls so it will add 1 because this node needs to be included this root needs to be included as well and it will return 7 plus 3 plus 1 which will be 11 now this node 1 received 11 from the left called 7 from the right call it will add its current node which is 1 so it will be 11 plus 7 18 plus 1 19 so the number of nodes will be coming out to be 19 ok so this is the entire method of solving this problem so for solving this problem we will basically be requiring 2 calls which is the left extreme call and the right extreme call okay and we will just be finding the number of levels while we are making these calls so I hope you understood this method this diagram looks messy so I will show you a fresh diagram so what will be the time complexity in this case well if we assume a perfect binary tree then this will be having maximum number of leaf nodes so let us assume that our binary tree is having total nodes as 2 n plus 1 and internal nodes equals n and the leaf nodes equals n plus 1 this is true for a perfect binary tree okay so the number of levels will be equals to of total number of nodes which is 2 n plus 1 base 2 ok so this is the number of levels in this case it is equals to 4 now what will be the number of nodes at the last level that is equals to n plus 1 which is nothing but the leaf nodes ok so what was our process what were we doing actually we were making call from this root node so when we were at this root node then we were making two calls one call was to the left extreme depth and another call was to the right extreme depth and then we were checking if the left value is equals to the right depth value so what was the time complexity for that actually for checking both the depths the time complexity will be 2 into log of 2n plus 1 base 2 ok so this will be the time complexity for checking the depth once now when we are comparing it and if they are not equal then what were we doing we were making two calls one to the left-hand side and another one to the left-hand side and another one to the left-hand side and another one to the right-hand side now again we were right-hand side now again we were right-hand side now again we were repeating the same process so again what were we doing we were making the left extreme call we were making the right extreme call and for this as well left extreme call and right extreme call so how many times these calls will be made actually you can see that if you see this root 3 then this is a perfect binary tree so as soon as you find that left is equals to right then you will simply calculate the number of nodes and you will return from here without checking further child nodes okay so this will be very efficient in terms of time so the first thing to keep in mind is there are log n number of levels and at the last level you are having n plus 1 number of nodes ok so what we were doing we are actually dividing the number of nodes into two parts and then we are searching in both these parts ok but you might argue that this will get repeated again and again but the property of this complete binary tree of filling the nodes from left to right will not let this subproblems to get divided again and again ok so one of these two parts will get returned soon therefore what we are doing is actually we are dividing a problem into two parts and then we are searching in both these parts but one part will be returned soon either this right one or this left one so let us assume that this right one is returned then we will again be dividing this problem into two subproblems okay which is exactly in between and then we will be searching in both these parts and one of them will soon be returned again so you can see that this is very similar to the divide-and-conquer method similar to the divide-and-conquer method similar to the divide-and-conquer method which we are using in binary search so the time complexity will approximately be the same as binary search and since we have n plus 1 number of nodes there for log n plus 1 base 2 will be the number of times we will be making this calls that we will be making these divisions now how many times do we make this binary search we will be making it number of levels number of times ok so what will be the total time complexity it will be number of levels multiplied by how many times we do this binary search so the total time complexity will be order of log 2 n plus 1 base 2 into log n plus 1 and this can be approximated to time complexity of log n into log n ok so this is the entire problem let us now look at the code so this is the code for the algorithm which I explained here we will be past the root and then as soon as we are at the root we will find the left extreme depth and we will find the right extreme depth and then we will compare if the left depth is equals to right depth if they both are same then the current root node is forming a perfect binary tree therefore in that case we will return 2 to the power left levels minus 1 otherwise if this is not true then we will search in both the calls that is a left child call and the right child call and then whatever value is returned from the left call let's say it's X whatever value is returned from the right call let's say it's Y we will add X plus y plus the current node which will be 1 because the current node will also be contributing to count equals to 1 and we will be returning this value to its parent node so this is the entire process so this is basically a recursive call here you can see that count nodes is again being called on the left child count node is again being called on the right child so this is the algorithm which I had explained and this is order of log and time and I have also written the code for the first method this is just a one-liner okay so I hope you are able to one-liner okay so I hope you are able to one-liner okay so I hope you are able to understand it if you have any other approach or solution in different languages then please share below so that everyone can take benefit from it like and share our video and subscribe to our channel in order to watch more of this programming videos you know not sure - thank you
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
416
hello friends to the rest of the partition eco subset-sum problem let's partition eco subset-sum problem let's partition eco subset-sum problem let's first see a statement given a non empty array contain only positive integers find if the array can be partitioned into two subsets such that the sum of elements in for subsets is eco let's see the example if we are given one five eleven five we can partition this array into one five and eleven so we will turn to so from this example we know that these two subsets not necessarily P sub array we can use the index 0 1 &amp; 3 sub array we can use the index 0 1 &amp; 3 sub array we can use the index 0 1 &amp; 3 so that's a hint and the let's see the example 2 we are given 1 2 3 5 we cannot partition this array into choose you call some subsets how can we quickly know the fact because if we sum up these four elements we can get 11 divides you not equal to 0 sorry 11 module 2 not equal to 0 because other elements should be positive integers we can simply return false so this question becomes to that we are given array we needed to find some elements in this array let's sum up II go to the total sum of these arrays divided you like if this sum equal to all the elements in the numbers array their problem becomes we needed to find whether we can pick some elements in these numbers to get some divide you right how can we find her this fact basically you can sync outer to use backtracking because we can start from every index of these numbers and try to sum up other elements and there to see whether we can get to their sum over to this is the one solution our solution is dynamic program because this question is similar to zero-one knapsack problem zero-one zero-one knapsack problem zero-one zero-one knapsack problem zero-one knapsack problem because for every because we needed to find a subset right so for every element in the numbers we can pick it or not pick it so simply deep he I means whether we can sum up her I from their numbers array so this is our two solutions and now I will first her solve this problem using backtracking so first and I said before when you choose sum up this other elements in the numbers so for every number in their numbers we will sum up it and do a quick check if this sum module true not equal to zero we return fourth and then we just symbol let this is sum divided you because this is our new target we need to find whether some elements can sum up to this target and because of the backtracking usually we will call another function I just name it help function unless employment is help function we will return a boolean and then we need definitely needed to pass these numbers and we need to pass index because we can start from each in there to find the weather some elements can sum up to their target yes we also need our target so the best kiss should be because we do not necessary to sum up with gesture - that from this target so the best kill - that from this target so the best kill - that from this target so the best kill should be if the target equal to zero will return true but we also needed to find some false cases when their index reached the end equal to the numbers tolerance or the target a less than 0 because we - it right so when it's less because we - it right so when it's less because we - it right so when it's less than zero we cannot find the correct answer Rouge returned the force but as this we only need to find a one valid partition so if the helper if helper numbers index plus one and they're the targets - numbers index if we have find targets - numbers index if we have find targets - numbers index if we have find the wrong solution we return true we do not need every one to be true if one is true we just return - but if not one is true we just return - but if not one is true we just return - but if not true we need to change their star index right but the problem that we may meet - right but the problem that we may meet - right but the problem that we may meet - the time limited its autonomy to exceed their problem like I see this example if is well the oh the one endo wondered because when we try the first one we cannot find that a very valid answer we were usual we will try the next one but basically if the first one we cannot fight there find us the answer we cannot find either so we need a to skip the Sam skip with their same elements that's the reason we do this part the next star index should be index plus one right but if this J we should always make sure this J is valid so J less than the numbers length and their numbers index ego two numbers J if they are eco we should skip it so we just let it J plus and then we just return the helper and numbers and there will be J and there this should also be targeted because we just a change or start index not element so it's also be the target let's fill this part little should be the numbers and the starting a zero and the target should be their son okay so it's very fast and you can see so now let's solve it by the dynamic programming okay this part is the same right okay and then we will use a boolean array that means whether we can sum up to I from the numbers are read so the size should be there some plus one because we can pick none of these elements in this array so DP 0 should be true therefore every number in their numbers array we will try to pick it or not pick it so we should start from there some right know je ho to some IJ greater than 0 J minus - once this Jake resident than 0 J minus - once this Jake resident than 0 J minus - once this Jake resident you should do pay attention to that we should add this eco if u equal the number and the d pj will equal to j which means we did are we done we don't repeat this number and the d pj minus number which means we take this number the reason that we should contends this eco because owning tv0 is true at first so when they are eco we can get the j-hook can get the j-hook can get the j-hook choo-choo like you and first owning dvds choo-choo like you and first owning dvds choo-choo like you and first owning dvds zero is true and then when we go to this one and the when there are eco we know DP 1 is true so on so forth and finally just a returned deep here some which means whether we can some map to this some ok thank you for watching see you next time
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
268
hello guys welcome to another video and the thing is according today we are going to do a very simple problem which is called missing number simple but interesting let's see the problem you are given an array numbers containing n distinct numbers in the range 0 to n you have to return the only number in the range that is missing from the array just try to take an example to understand suppose this is the array that is given to us right what is the size of this there are four elements so the size is four so what do we expect in this we expect zero one two three four out of these numbers which is missing we want to find one okay this is the actual array that is given to us right we wanted all these elements to be present but 0 to n has the size of n plus 1 so here n is four right so there are five elements that should have been present but the size is only four so only four elements will be present one of them is bound to be absent so you have to find the element that is absent now in this you can see that zero is present one is present 2 is present 4 is present 3 is missing 3 is the number that is missing so the first approach or the simplest approach to do this problem will be just take a sum of all the elements that are expected to be present so sum of elements that are expected to be present and then subtract it from the actual array so you will get the missing element right so if you take the sum of all these elements subtract and subtract the actual elements that are present three will be the lone element that is remaining and that will be your answer so you can do that let us try to uh code using the brute force approach first and let us see so we will have to take the sum of the um expected values so what is the sum of expected values it will just be n into n plus 1 by 2 we can use the simple formula so let me just write into 0.5 formula so let me just write into 0.5 formula so let me just write into 0.5 so this will be the sum of expected values and what is the sum of the current array so we can just use the accumulate inbuilt function which will give the sum of the current array so we can start from the beginning and we can take the sum till the end num start begin it should be dot here till nums dot and the initial sum is 0 so you can just return this as your answer this is the simple brute force approach let us do one thing let us run the code and see if it is working okay yeah it's not working because we have not declared n so let us quickly declare an n will be your num start size okay so now let us run the code and see if it is working so it's fine and let us also submit this code and then let's move forward to the next approach okay this is accepted this is fine but this there's a better approach than this which will be actually faster also because we are going to use bits for that and uh it will also be faster because in this you will have to sum over a lot of value so you may actually in this you will actually uh try you can actually run into overflow errors because you are summing large values in this case our answer would exp uh accept it but uh that could have been situations where int would not have been appropriate because you are overall summing this and subtracting this so that is a problem so you can rather do one thing rather than summing up these values expected value and subtracting from the actual values you can do one thing why don't we take a zor of these uh values so what do i mean by that let's try to take a zone so the element that we have is 0 if we take a 0 of 0 with 0 we will get 0 right so what is or so zoro is if you take same any two elements that are same if you take this or of two elements that are same you will get zero if you takes or of two elements that are different you will get one so what do i mean by that for example if you take 0 of 0 with the 1 in that case you will get 1 if it takes 0 of 0 with 0 you will get 0 you take 0 of 1 with 1 you will get 0 so it's like that if you take sort of two numbers that are different you will get 1 okay otherwise you will get 0 so in this case 0 and 0 are same so if you take the 0 you will get 0 similarly take 0 of 1 with 1 it will give you 0 it will cancel out if you take 0 of 2 by 2 it will give you 0. if it takes order of 4 with 4 it will give you 0 the element that will be left will be 3 right so that will be your answer so you can use this approach also to actually get the answer and you will not run into any sort of overflow errors we can do that so let us take this particular approach i is equal to zero i less than nums dot size i plus and we have to basically takes also the symbol for the order will be this and let us start taking is also initially and declare answer initially let me make it zero and i will take 0 so i have to take 0 of each element so this is the sort that i am taking initially of all these values and then i have to take the 0 of all these values also so that they cancel with these values so what can i do i can do one thing i can take this or with i here it says okay so this will uh give me the proper answer but i will also have to take the zor finally with the with n so let's say uh n is equal to nums dot size i also have to take the zor with n because for example in this case we also have to take this or with four right so uh you have to take this all with the last number also which is a four so that and then you can finally return your answer so let's try this code out if it is working so it's fine let's just submit this and see if it's an accepted solution so it's fine thank you for being patient and listening
Missing Number
missing-number
Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._ **Example 1:** **Input:** nums = \[3,0,1\] **Output:** 2 **Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums. **Example 2:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums. **Example 3:** **Input:** nums = \[9,6,4,2,3,5,7,0,1\] **Output:** 8 **Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums. **Constraints:** * `n == nums.length` * `1 <= n <= 104` * `0 <= nums[i] <= n` * All the numbers of `nums` are **unique**. **Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?
null
Array,Hash Table,Math,Bit Manipulation,Sorting
Easy
41,136,287,770,2107
1,802
hey what's up guys uh this is sean here again so uh this time on one 1802 maximum value at a given index in a bounded array okay so you're given like three positive integers and index and the max sum and you want to construct an array nums right that satisfy the following conditions so the length has to be n and each number is a positive integer and the absolute difference between two adjacent numbers is either equal or smaller than one okay and the sum of all the elements does not exist exceed maximum and at index at this index the num the number is maximized and we you just need to return the maximum numbers on this index okay so for example we have this kind of uh is equal to four index two max sum six right so the maximum we can get is two in this case i think this is because you know we have one two and so okay so the index two i think it's zero oh yeah it's uh it's a zero index so that's why we have yeah that's why they have like two possible solutions maybe one two one right one two one so that's why this one is two so similarly for this one you know so we have total we have six you know basically we have six numbers right for second one we have six numbers and we're trying to maximize index one which is this one right and the total is ten that's so the answer for this one is three and why is that actually you know so one of the solutions is like this so basically for three and then we have two on this one right and we have two one right that's how we get this 10 because i think the total for this one is what it's like i think we have this is eight yeah this is ten right so basically this one equals to 10. cool so to solve this problem you know the uh actually you know so for this one you know since we're trying to maximize the this number right uh we should just try then try to max maximize this number and then still we satisfy this kind of uh distinct this conditions you know i think one of the observation we can make is that you know we should make here so no we should make is here you know as long as we fix like this kind of numbers here you know since we want this uh sum as smaller as possible basically you know as long as we fix a values at this index here we will always try to decrease on both left side and right side for example if we fix this one to three here right you know of course we can make this one three and we can also make this one four right so basically two three or four they're all they're two three or four they're all satisfied uh this condition right but we want to choose the smaller one the smallest one which is two because we want to minimize the total sum right of this kind of array that's why you know we always choose the smaller one right so similarly on the right side that's why what i'm saying that you know as we fix the number here you know we always try to decrease the number on both left side and right side and then this leads to us like a binary search solution right where you know we try to we binary search this value directly right and every time we have a fixed num index here we try to use a greedy approach to calculate the uh the smallest sum right who satisfy all the others of conditions and if that's the sum is within the this uh maximum range then we know okay so that one is satisfied we can just move our cursor basically to the right side right otherwise we go to the left side okay cool so and then that's lead us to this kind of binary search solutions so which means that you know for the left we have one because all the numbers they will they need to be positive integers and then the right side i'll just use the max sum to be the upper bound and then to search the biggest numbers we have a template right so while l is smaller than r then we have middle equals to l plus r minus l then divided by two right if helper right so i'm going to call the hyper functions if the middle one is true right it means that you know we should go to the right side you know since we're getting since we are uh calculating the maximum values right it means that we are if this one is true we're gonna move this middle one assigns me the one to the left otherwise we sign the middle one minus one to right okay and then in the end i return left right so this one means that you know since the l could be the answer basically we're trying to move the left the lower bound to the right as much as possible right oh and since we are doing like this kind of l the lower bound equals to middle we have to do a r minus l plus one i think i have already talked with this one a few times basically so every time when you have like a left equals to middle you need to do l minus uh l minus l plus one this is to make sure you know when we have like l equals to three and r equals to four if we don't do this uh l minus uh l plus one you know if we don't do the plus one basically we'll end up uh to an infinite loop basically the l will always be three and we'll never exit this while loop okay cool so that's gonna this is a template to calculate the uh the maximum values by using the binary search right and then the left the rest is just like to implement helper functions right and so to calculate helper functions a little bit complicated you know like i said you know if we have like this kind of integers here right let's say we have a middle values here right we have a middle value here actually this is three right so if we have a three and then we have two one right so if the left side if the length of the left side is smaller than the middle values right actually we're not getting everything right basically uh it will stop at some place and if the length on the side is greater than the value itself like i said you know basically the value will be decreased uh to one and then it will remain as one right so at least that's how i uh the way i did it was the you know since we know the total values from the middle to one right which is the n times n plus one uh divided by two right that's going to be the total values if we uh decrease this middle to one and then by comparing the length on the left side and on the right side i can either subtract the missing part or i the missing part what is one in this case right by subtracting the missing part or by s by increasing or by adding the remaining ones part right if the basically it means that you know if the length is smaller than this one we need to subtract the missing part and if the length is greater than the three we need to adding the remaining ones okay so that's why you know uh for the total right so the total we have uh this uh n times n plus 1 divided by 2 right so i think i'm just that's why i have like another hyper functions how it's called accumulate right with n this one i simply return the n times n plus 1 divided by 2 right so and the total is the accumulate middle right and then for the left length right so i call the left length equals the index plus one right since the index is zero based you know right so this index is one but the left length including the middle itself is 2 that's why i do this one right and then the right length equals to n minus index this one we don't need to subtract 1 because n is 1 based actually right and then uh i have a left offset right i cut left offset equals the right offset equals to zero because the offset could be an active or it could be positive right okay so if the left length is smaller the middle it means that we need to subtract the missing part right which means that you know the left offset equals to minus accumulate right middle miners left length this is the missing part and we also need to do with the accumulate parts right because let's say we have five and a four right basically you know actually we're missing one two three right so this is the part we're missing that's why you know to get the four and five you know at least that's how i do it right so we have a total here you know we need to subtract the one two three which is the middle uh minor subtract the left leg okay else right also left offside means that you know the left length subtract middle okay so this one means that how many ones right how many uh remaining ones we need to add to the total value right that's going to be the left lens minus subtract middle and similar same thing for the right part i will just copy and paste here so we have a right length and we have a right offset right okay and then so the answer is that uh the total right times two right uh for both the left and on the right side and then a total plus left offset right and then plus total plus the right offset right and then subtract middle right because you know this is the middle right so this is the left side and this is the right side and we count this middle one twice that's why we need to subtract this middle and then we simply return if the answer is either equal or smaller than the max sum right if it's smaller by using this kind of greedy approach it means that it's true otherwise it's false right yeah i think that's it right i mean if i run the code here accept it if i submit uh let me see seems like something is wrong here so we have this one oh i see i think it's because the uh the upper case right i think there's a uppercase s yeah cool yeah and yeah so at the time complexity right so we have a log yeah so here we have log n right where n is the 10 to the power of nine and uh and inside the helper functions here i think it's uh this is o of one actually yeah so this is all of one the helper function so i mean the total time complies time complexity is the slogan basically yeah i think that's it right i mean it's just like very classic binary search solutions where we fix the uh the index values right and then we try will greedily greatly calculate this uh the total sum right of the uh of the entire array by using some of the math formula and then a little bit trick of the at least i use the offset right by comparing the length of the left side and right side i mean i'm pretty sure there could be other uh solutions but anyway this is how i did it okay cool and i think i would stop here and thank you for watching this video guys stay tuned see you guys soon bye
Maximum Value at a Given Index in a Bounded Array
number-of-students-unable-to-eat-lunch
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of all the elements of `nums` does not exceed `maxSum`. * `nums[index]` is **maximized**. Return `nums[index]` _of the constructed array_. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** n = 4, index = 2, maxSum = 6 **Output:** 2 **Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\]. **Example 2:** **Input:** n = 6, index = 1, maxSum = 10 **Output:** 3 **Constraints:** * `1 <= n <= maxSum <= 109` * `0 <= index < n`
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Array,Stack,Queue,Simulation
Easy
2195
1,861
hey everyone how are you guys doing hope you guys are doing well long time no see today let's go through another legal problem 1861 rotating the box let's take a look at the problem you're given an m by n matrix of characters box representing a side view of a box each cell of the box is one of the following it could be a stone which is a pound or it could be a stationary obstacle or a star or just an empty space which is represented by a dot the box is rotated 90 degrees clockwise causing some of the stones to fall due to gravity each stone falls down until it lands on an obstacle another stone on the bottom of the box gravity does not affect the obstacles positions and the inertia from the box's rotation does not affect the stones horizontal positions okay let's take a look at the illustration of the picture so that we can better understand what's going on or what's being asked it's guaranteed that each stone in box rests on an obstacle another stone or the bottom of the box retain an n by m matrix we are given m by n and we are asked to return n by m matrix representing the box after the rotation described above so the let's take a look at example one things will be a lot more clear we're given this 1 by 3 rectangle or box and it's rotated 90 degrees so that it's one it was laying down now it's standing up right so it looks like this why did the stone change because of gravity right the one used to be on the top it has to fall down to the middle because the middle one is empty and the one on the right side in the beginning it doesn't change because it will stay in the bottom because of gravity all right so this is a stone empty and stone and now the output becomes empty stone and stone all right easy to understand let's take a look at the second example all of these what are these this is star means obstacle right a stationary obstacle okay that means if we flip this one we if we stand this one box up all of these they will just fall to this level if it has a stone here both of these will just stay stationary as well right because of this obstacle here and they could not fall until to the bottom or the bottom two spaces are empty right okay let's take a look at one more example this is the final example okay final example we can see here let's take a look at a row by row so this is the first row which will become the first column right first column because there are obstacles here so these two stones they couldn't free fall into the bottom right so they stay here and so is this column this row when we stand it up it becomes like this the middle column and all of the three stones will just stay there they couldn't free fall because there's an obstacle here but for the very last row or the very first column in the output all of these four stones they do free fall because there are no obstacles here and they are empty spaces here so this one dropped it down to here all of these three will move will drop as an as a result of this move right so um the idea is pretty clear and what we are asking to do we're given this m by n box and we're asked to return an n by m matrix so what we'll do is just uh we'll try to find will go through this box row by row which is mutate the row in place we can mutate the real impacts in place although it's not a good idea to modify input this is a lethal problem it's totally fine in the enemy you might want to clarify with your inner viewer whether it's a good idea to modify the input or not but for here simplicity reasons we're just modifying the input directly would try to move the stones to the right as right side as possible if there is no obstacles blocking the way and then we'll do this row by row and in the end we'll just create a new matrix n by m matrix and assign each single row to each single column and then return the output that's it okay straightforward and easy let's put the idea into the actual code all right so first we'll use two variable one is m i call it box length one is in uh which is basically one is the number of rows the other is the number of columns so because we have this constraints here m and n is at least one so which means the box will not be now or empty in the beginning and then we'll just go through every single row m i plus and how do we go through every single row we'll start from the last column right we check whether the last column is an empty space or stone or an obstacle right so we'll start from j from n minus 1 j is greater than or equal to 0 j minus so we'll check if box i and inj if this one is a box that means it's possibly could be shifted towards the right of in the output box it's free fall right if this is a box we'll check whether we can shift it towards the right so basically we want to find the one right to the right uh right adjacent on the right side of this freeze of this stone is a free space it's an empty space we'll just call this one empty j plus one so while empty smaller than n and box i the same row and empty is the column equals to an empty space which is to keep incrementing empty we want to find the last obstacle of the one that is not an empty space right so if when this one breaks out we'll check if empty so we'll check if empty is smaller than n that means the empty is still within the columns constraint within the columns boundary and box i empty equals and empty space in this case we can swap this right which means the stone is going to fall freely onto this empty space box i and empty is going to be a stone it's going to be a stone and then the where the stone originally fell from this one we're going to make it empty right because it fell into the new position the other case is that it could be that empty falls out of the range oops it could be that empty the last one smaller than within the columns range like this box i m c minus 1 equals to the empty space or just to move the stone into this position this one becomes a stone and then box i box j this one becomes an empty space we'll keep moving all of the box out of the stones as long as the next one right on the right side adjacent to the stones will just keep moving towards the right all right this will do the job this is inside this first process so after this first process all of the stones are possibly just we can think of the gravity not as gravity that pulls things directly vertically to the bottom of the floor but to everything on the right side so after we've drawn all of the stones free fall if there are no obstacles to the right side we can now we can stand up the box so we'll just um which is to virtually stand up in the box by that what i mean is that we can create the result new chart this case is n by m and it was originally the number of columns now is going to be the number of rows m was originally the number of rows now it's going to be the number of columns and now we can think about how we can traverse this given input after we have done the processing so it's basically this one is zero now it becomes what it becomes here it becomes zero three right so we're going to traverse through this matrix so first i start from zero i smaller than we're still going to start i smaller than so smaller than m right i plus m is here 0 1 2 this is the m number of rows and then we need j start from 0 j smaller than n j plus uh you can see these uh these two massive for loops all of the indices and the boundaries are exactly the same as this one so what this means is that we will traverse through the original input after our processing it's still going to be column by column and row by row right but we'll have to put this one onto here this one here so that means okay the result we need to pay special attention to the result index let's put this one here so the row index of the result is going to be the column index right j is here so where is j is this one this is the j right this is the first column we use j to represent the original column but this column is becoming this row right so that's why this row we use j and we go from the very right side so very right side to the middle to the left side right so we need another variable i'll just call it i j and k starts from what k starts from n minus 1 m is what m is the number of rows which is 0 1 2. okay m is 3 in this case 3 minus 1 is 2 which is 0 1 2 right so we have m here and what does m how does m change m going to increment and m is going to decrement every single time no not this not m is going to be k right so this is how we can transpose this we can stand up this box vertically right and then we'll just return result now let's hit run code and see um wrong answer new char what's going on oh a re-index new char what's going on oh a re-index new char what's going on oh a re-index uh should not m it should be k what was i doing so this is the case that's why i initialized the base k let me run code one more time yeah accept it all right accept it now let me hit submit all right accept it 100 and 50 let me just hit it one more time and see okay now it's 100 15 milliseconds last time it was 50 and this time is 100 i guess it's just that it doesn't have enough submissions to distribute the result one more time last time 100 50 is always the memory usage is 75 megabytes i'm basically the only actual memory it's not really actual memory for the processing it's just the result we're just transposing the matrix last time 100 50 all right here is the entire idea of my idea of solving this problem of course there are many ideas i don't claim this one is to be the most arrogant or efficient could be something to be optimized so please comment down below and let me know how you guys approach this problem or how this um algorithm could be optimized i appreciate that if you guys like this video and you find this video helpful or interesting please do me a favor and hit the like button that's going to help a lot with the youtube algorithm and i really appreciate it and don't forget to check out my other videos on my channel as i have accumulated quite a lot of different other videos about data structures lead code dfs bfs q priority queue whatever to help people better prepare for the uh for the coding interviews um so hopefully i'll just see you guys in just a few short seconds in my other videos thank you very much for watching
Rotating the Box
building-boxes
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity **does not** affect the obstacles' positions, and the inertia from the box's rotation **does not** affect the stones' horizontal positions. It is **guaranteed** that each stone in `box` rests on an obstacle, another stone, or the bottom of the box. Return _an_ `n x m` _matrix representing the box after the rotation described above_. **Example 1:** **Input:** box = \[\[ "# ", ". ", "# "\]\] **Output:** \[\[ ". "\], \[ "# "\], \[ "# "\]\] **Example 2:** **Input:** box = \[\[ "# ", ". ", "\* ", ". "\], \[ "# ", "# ", "\* ", ". "\]\] **Output:** \[\[ "# ", ". "\], \[ "# ", "# "\], \[ "\* ", "\* "\], \[ ". ", ". "\]\] **Example 3:** **Input:** box = \[\[ "# ", "# ", "\* ", ". ", "\* ", ". "\], \[ "# ", "# ", "# ", "\* ", ". ", ". "\], \[ "# ", "# ", "# ", ". ", "# ", ". "\]\] **Output:** \[\[ ". ", "# ", "# "\], \[ ". ", "# ", "# "\], \[ "# ", "# ", "\* "\], \[ "# ", "\* ", ". "\], \[ "# ", ". ", "\* "\], \[ "# ", ". ", ". "\]\] **Constraints:** * `m == box.length` * `n == box[i].length` * `1 <= m, n <= 500` * `box[i][j]` is either `'#'`, `'*'`, or `'.'`.
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
Math,Binary Search,Greedy
Hard
null
1,808
Hello Hi Everyone Welcome Back Click Wedding Sudhir Fourth Roshan Office Contest 234 Question Is Your Appointed On Prime Factors Which You Can Start Appointed And Satisfied Fall In The Condition Sir The Number Of Prime Factors Of Can Not Necessarily A Distant Is At Most Prime Factors To Towards Nice View of NH Maximize Noida West is a sorry number Vijay divisible by all the prime factors to add to three different factors in the number of cases Wealth creation for not ok no return Ka number of narrative itself and brought up in written and Verbal Ability in the Number of Times in This Number Will Shetty Comedy Show and 800 Barricade Example When the Give the Prime Factors 555 Prime Factors No Ambiguity of Five Prime Factors Early of the Prime Factors but Attacking Lately Too Two to Five Notices The Number Dresses The Prime Factors And Theirs More Than 600 Six Pieces Needs Of The Real King Up Who Arms Yes Or No 102 Still Have Freedom Fighters XXX Why Scientist Robert Pattinson Factors In These But In This Case Of Record Chunari D Advisory Issued At Least Have This Point Flex Into A Superior Than All Leaders Will Be Divisible By Them All The Prime Factors Section Wise Video And Right Is So How Many Players In The Basis Of Which Have So Far Been Accessed By 20X * Have So Far Been Accessed By 20X * Have So Far Been Accessed By 20X * X into a deep neck * * * * Aremedy yo behaving a till then we that S into being total number of nice as few may zoom located carefully you find what you have enough batsman in odi series notes for consideration in witch they are living dead in 2009 subscribe 602 play list number apna ise 0.2 havells play list number apna ise 0.2 havells play list number apna ise 0.2 havells treatment plant by four number office number of members and s they have time number bahubali-2 this is the number have time number bahubali-2 this is the number have time number bahubali-2 this is the number of de villiers and jp duminy question is reduced to avoid a question is reduced to find out now half effective in three factors which were lost near at most and prime Factors Wild 100 Titanic Alert and Prime Factors Can We Should Points Configuration of Secretaries Configuration of ABCD on Which State is Equal to 9 Subscribed and Productive Maximum Products Given Total Number of Cases That Such a Summation of All Things Beautiful 2m It's Done Princess Were Given Injections Possible give in that stopping 518 159 five also points 223 and a big broken down into your suggestion and dynasty products six product 14 and deserves better okay equipped minutes i india kiran is it 9483 find 2515 100 to * * install to * * install to * * install that those times were Giver Sixteen And Vitamin Two Are And Basically 3D 3123 For 6 And To Do 810 Metro's Unique 1994 * 1431 16th Key 810 Metro's Unique 1994 * 1431 16th Key 810 Metro's Unique 1994 * 1431 16th Key Tarzan The Parts Of Three I A Firm Meaning Two 220 Mathematical Proof Vishu Parade Ground Should He Be Kept The Breaking Down Into End Parts Internet Sports Sir Absolutely Two Disha Express To The Power And Wealth By A That World Ray Driver Two Parts Reports And Write But Again With Help Of Certain Examples PDF Break Down Into Three Parts Of Birth To Get Maximum Muscular Tomorrow 24th And Sewerage Putting Two Parts Of Badluck Only Breaking Down With Three Little Time I Can And Will Determine the letter will not be ready for it will break down and parts of 3 that nine degree course in front of you is number is vansh one was with numbers in python dancer is also hands free * basically a the answer is 123 hands free * basically a the answer is 123 hands free * basically a the answer is 123 arrest to the power Of and every student response to give me the power of free softwares which it calculate deposit craft 3D supreme power and wildlife in this park is calculated method plants stayed one day that this tricks one-rupee idlis one should be that this tricks one-rupee idlis one should be that this tricks one-rupee idlis one should be indicated s when will have 10th A demon decrees one morning breakdown 1093 for before rough and dry difficult-2 1093 for before rough and dry difficult-2 1093 for before rough and dry difficult-2 then a supreme power 1083 minus one mandal wife and okay for centuries versus the students were waiting for into power of that Aditya Trishul power of and divided by free - 151 - Two in this case by free - 151 - Two in this case by free - 151 - Two in this case Superintendent of Police moment 1000 three so entry problem this is like an Indian co 9 inches plus two eleventh fennel 12323 okay so basically this supreme power and divided by three multiply 222 tables that 321 very nice day function like this inches a hint Debashish Boys Dress Power Bet Get Your Husband Flight 2020 That And Power Of Sacrifice Will Tree Ru Best To Power And Wealth With Friends A Free State Power And Every Native And This Again A Couple Of Years Yes Or No We 20 All This Meeting Record Invite is acceptable or aromatic plants solution tenth type of problem difficult dad if subscribe number for which divided into two parts of the body part adb scratch medical you can just started using this formula in just two width number to the number subscribe to me and let Sudhir Pandey solution price is lugai ka video mate you like share and subscribe channel for more such content thank you
Maximize Number of Nice Divisors
stone-game-vii
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is **nice** if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not. Return _the number of nice divisors of_ `n`. Since that number can be too large, return it **modulo** `109 + 7`. Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`. **Example 1:** **Input:** primeFactors = 5 **Output:** 6 **Explanation:** 200 is a valid value of n. It has 5 prime factors: \[2,2,2,5,5\], and it has 6 nice divisors: \[10,20,40,50,100,200\]. There is not other value of n that has at most 5 prime factors and more nice divisors. **Example 2:** **Input:** primeFactors = 8 **Output:** 18 **Constraints:** * `1 <= primeFactors <= 109`
The constraints are small enough for an N^2 solution. Try using dynamic programming.
Array,Math,Dynamic Programming,Game Theory
Medium
909,1240,1522,1617,1685,1788,1896,2002,2156
1,743
Hello, meeting you all after a long time and also our budget has also increased, this time it is fine, so let's see what is today's problem, so brother, let's do a little flexing, otherwise before that it has been said to restore the are from the Adjacent pairs okay so there is an injury are names that consist of a unique elements but you have forgotten it how ever you do remember every pair of adjunct elements so like their output is tooth their actual position was This is actually tha but ya have forgotten but they remember that T was next to them, as if there was one next to T, they remember that there was four next to T and it is not that if I have said Aaju Baju, then that means next to T. It can be like this only, not like this because this is also adjacent, right, so now let's do the next one, then we are given entry in the addend per y, the size is a human shape, addends per yv indicate element, and we are the addend term, okay. And this line which I had told is the same and it is said that every aid per will assist in advent per, it is okay, every aid will be there in it is okay and now we have to write the original, as told that if it has happened, then it has already happened, okay. Even if it is yes, it will be clear after seeing the apple, it should be right next to the four. Satisfied is satisfied. There should be F next to it. This is also satisfied. It is perfect and the same. This is also the lid answer, so now comes the matter. That brother, how will we think, how will we do this, is it correct, since he has asked for a vector as the answer, so I thought it would be okay to make a vector in the beginning and whoever is saying it, will put it directly and then change it accordingly. Said that friend, this means a little, the answer is coming from above, then he said, this will not be possible for me, or I am not able to think this way, a little more, means one more time, if you have seen something, clue, then you have seen, yes, it is also given. I thought, okay, it comes on its own, maybe a graph, then I thought, oh, it is visible, let's try to make a graph like form, okay, like four is going, what is going on is minus, sur and minu are also going. Okay, then one is going to four, so this is also going to me, meaning their and then minus 3 is going to me, so one is going to all minus, so this is also going to be ours, right now and if this If we try to make a graph like this then how will it be made like it is fur and was going, in Mansu there is a plus one, it is going near this and minus 3 and is going near this, okay yes, then now a graph like this will be made. So, it is okay to look carefully at these two answers, and what I saw was that brother, Y which is -3 and nut, these are the nodes that brother, Y which is -3 and nut, these are the nodes that brother, Y which is -3 and nut, these are the nodes on which no other meaning is coming, is it okay or not, they have only one edge. It is kind of free that they can stay in this position because they do not have any tension. There should be someone on this side of me. This same concept is also used in Tojal Sat P, which is Khan Algam. Okay, so if you feel that, let me tell you. Just comment and I will tell you, it is good, it is fine, same degree person, then it came to my mind that brother, 3-2 and it is coming here, that brother, 3-2 and it is coming here, that brother, 3-2 and it is coming here, then I thought, ok, this can be a starting point, so we can get a starting point. If we make any proposal -2 then we will come in -2, if any proposal -2 then we will come in -2, if any proposal -2 then we will come in -2, if he has only one element, then there is only one brother, so four, then we will go to four and say, now who do you have, then he will say -2, say, now who do you have, then he will say -2, say, now who do you have, then he will say -2, then -2, not brother. It should be because the one then -2, not brother. It should be because the one then -2, not brother. It should be because the one behind me is the one behind me i.e. from where I have behind me is the one behind me i.e. from where I have behind me is the one behind me i.e. from where I have come, then it's okay, let's go to the forest, okay then we come near the forest, Boga said four, no brother, four is already ready, so he said -3 and even Our n is so he said -3 and even Our n is so he said -3 and even Our n is already made up to 1 so straight away brother return tuck was simple nothing was there and same if we run with -3 then let's see how it will work -3 will go run with -3 then let's see how it will work -3 will go run with -3 then let's see how it will work -3 will go after -3 it will say yes give one brother after -3 it will say yes give one brother after -3 it will say yes give one brother after one it will say Four will say yes, it will work, then -3 will not work, then -3 will not work, then -3 will not work, then go to four, he will say -2 will work and let's see go to four, he will say -2 will work and let's see go to four, he will say -2 will work and let's see what the answer is. Oh, it is absolutely right, so it was simple. If you are visiting a time complex, then it is okay to turn it on only once. Not like this, let's do the code now, it is simple and yes, to do this, we will use what is our ADJ, I will take that map in which I will take these nodes and these, we will take the vector, okay, that's it, let's go. Now let's start coding so let's go to the code so like I said to create an unordered vector of the best then let's take the auto edge copy and that will be a zero and ave okay so now What will we do, eddy g of y dot push back similarly and ls, so our undirected graph is now perfect, they also need a vector, free for the answer, no worries right now, ok perfect now, as if our main, as if, we have. Starting point is required, which was the one which will have only one or else just find the starting point and start node then initialize it and for auto it is for iteration and we will traverse in ADJ so if it is the size of the second because If there is a vector then there is one like its parent, we have got it, then start is equal to sorry ITR which is the first yes and l break and what is to be found, we have found it and we will break it, we have started it, we have found it. So if you don't do two things from here, then run it directly in the loop and put it, then what will we need for that, okay if the loop one is doing it, then do the second one and say, take the start point and edge and take the green ridge, put it and keep it. And then write bco general purpose ok brother or nothing return at the start place and what do we need one cha map pass ok and pass it by ref so that it is not copied and also the result is same and yes I will tell. So what did I say that from where the meaning of that which came from behind is like 'T' then yes, if we like 'T' then yes, if we like 'T' then yes, if we get this one from the forest then we have to leave the forest, then we would have taken more or we would have kept the one that came. OK parent or question, whatever you want to keep then result will be pushed back and then what will we do for now we will see brother who is there and then we will ask if brother is not that fine then we will call you. It will happen, it will be the end result, so good, let's try to submit and what has happened, so now what will I give the minus, but it can be a result, okay, it will not be a minus, it will not be an element, so what will I give the minimum. What is going on, let's submit it and see if it is perfect or good, it was fine brother, the problem was good and I told earlier that yes and topology shut also means digi wala, we will see it. If you want, please comment and even if you don't comment, please comment on mine. If you feel like it then you can make it, okay let's meet again with a new problem, let's go bye.
Restore the Array From Adjacent Pairs
count-substrings-that-differ-by-one-character
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Hash Table,String,Dynamic Programming
Medium
2256
744
okay let's talk about the find smallest letter greater than the target so you are given the character letters which is already sorted in non-decreasing order and character non-decreasing order and character non-decreasing order and character target so return the smallest keratin array is larger than the topic so here's a example so and also okay if a letter wrapped around so if top equal to z and there's no character inside the letter array which is greater than z you have to return the first one so this represent a wrap around right there's rubber rum so um you can actually just use well you can actually just use linear search but in this case it's going to be all of them right so i would just basically find the first one which is greater than the target and then you'll return so i'm going to show you if the array a resolution so it's going to be one for char c letters and i will say ifc is actually going to probably i'm going to just return right and then everything else uh which is going to be in this case if probably equal to z and there's no character inside the uh current entire later array and it's greater than sorry i'm going to return the first one so this is going to be if i raise it's already sorted and i think i spell it wrong all right let me do it again and this is how it is all right and here we go so if array storage do like this right what happened very not sorry right so i'm going to say troll rns able to do empty so i'm still from diversity and letters and then if c go to target i'm just complaining i'm not going to assign this into a chair uh to the character which is for two equal to w right and if the answer if i didn't assign the character to the instrument right if anything equal to right and also in auto the current character which is what greater than the problem you have to assign integral to c but why if you want to reassign right we assign if the answer is greater than c which is imagine like uh imagine c f j right and then probably equal to what probably equal to h initiative b and c e c d f probably cdf is better no c e f c and probably taurus d and if origin is not solid it's going to be c f e okay so if a ray is not started after i will sign i will assign f right away because if the answer was empty and then character is greater than target i will assign f for sure but i need to resign reassign for my answer to e right so i would say if i current character if our answer f is greater than the current character i will reassign my answer to e to c and because c is actually greater than here right so this is pretty much it right so uh in this game i'm going to check if my answer equal to mp if this is going to be true i'm just going to assign um my first character inside the array data array i will just return answer and this is going to be a linear search as well but this is going to be arrays now sorry and here we go so uh there are problem counts for the solution but think about it and this is going to be all of them time when the arrays are sorted this is already sorted and spaces will become for both and just making sure you know that you have to return the letters for the first character when the target is actually greater than any character inside the layers and this is pretty much the solution for linear search and i will talk about the binary research later and i'll see you next time bye
Find Smallest Letter Greater Than Target
network-delay-time
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`. **Example 1:** **Input:** letters = \[ "c ", "f ", "j "\], target = "a " **Output:** "c " **Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'. **Example 2:** **Input:** letters = \[ "c ", "f ", "j "\], target = "c " **Output:** "f " **Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'. **Example 3:** **Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z " **Output:** "x " **Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\]. **Constraints:** * `2 <= letters.length <= 104` * `letters[i]` is a lowercase English letter. * `letters` is sorted in **non-decreasing** order. * `letters` contains at least two different characters. * `target` is a lowercase English letter.
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
Medium
2151,2171
1,482
hello friends so today we're gonna discuss yet another problem from the latest binary search series i'm working on the problem name is minimum number of days to make m bookings now this is also a medium problem so let's discuss this problem this is also an interesting problem for you doing you are given an integer array bloom day an integer m and integer k so you are given three values in the input a bloom day integer array uh integer m and integer k we need to make m bookies to make a bouquet you need to use k edison flowers from the garden so you have to make m bouquets and whenever you want to make a bouquet you can you like you will always choose key addison flowers okay so now the garden consists of n flowers the ith flower will bloom on the bloom day eye okay so like and you can only use one flower exactly for one book you cannot like use single flower for multiple times return the minimum number of days you'll need to wait to able to make m bouquets from the garden if it is not impossible you will return on minus one like or if it's not impossible to make m case you'll return a minus so as you can see here we will make i will make you understand for this example if the given constraint is m equal to 3 which means that you have to make three bouquets and you have to like find out and you have to make a bouquet such that you have to choose one flower for each book so as you can see the answer is 3 which means that i will take this after 3 days this flower will bloom because let's assume that the time will start at 3 equal to 0 after t equal to 1 this flower will bloom which means that this will flower out you can plug this out then after time two this will pluck out the time three this will pluck out then at four five six seven eight nine both of this cloud will not bloom but as you can see i only want three bouquets and k equal to one which means i want 3 flowers so i can only take these flowers at time equal to 3 and the answer is fine so this will also tell us that we should not always just take out the maximum value from this area what i mean by this is you can also say that okay i will take out the maximum value from this array and that's the time when every flower will bloom if all the flowers bloom at that time i can take out all the flowers but that's the thing you will understand that this is a monotony function now what is the monetary function i've already told you in the last couple of videos a motive function is the one in which the values stay constant till a particular value in which the value will give a negative answer or like the answer we don't want till a particular value and after one value it will start giving the correct answer okay so maybe this is also going to answer this also answer but this is the first point after which it is giving the correct answer so you have to find out this point also so that's the whole question so now as you can also see if i take out or if i take out flowers at time equal to like let's zoom 20 at 20 all the flowers in bloom so i will make i can make bokeh but i have to find out the minimum time at which i can pluck out the flower such that i can make bouquets in which i will choose key consecutive flowers to make m bookish now that's the question so now can you tell me what is the case for minus one directly without like looking at the given constraints like you will find out whether there is some case minus one after doing some calculations but can you tell me like directly there is one case in which like you can tell that there will be the answer is minus one as you can see uh if m if i want to make let's assume that i want to make three bouquets and every bouquet has one flower so i will require three flowers but let's assume my garden will has only one flower if my garden has only one flower then how can i get three flowers so that's the trick you have to like they have to find out these small things in which it will give the boundary cases so if my total length of this bloom day the total number of flowers is less than m into k then the answer is already minus one okay else we have to do some calculations so ah so what we'll do that is simple trick you will take you will find out the boundary for this now the boundary for this is actually c you will not take so the maximum time will you will take to pluck out is you can either take out the maximum bloomberg value which is 10 to the nine you can like you can take it by nine also but as you can see if you can also take the maximum among all of these elements that's the right limit also because you will not take more than 10 hours okay like you will take 11 hours also fine but 10 is the maximum r because at that time every flower will move so you can also take the right pointer to be the maximum among all of these values or you can also take right value to be 10 to a 9 whatever you want so what you'll do you will do the same right or left is equal to 1 right equal to the like something like x then you take the middle value if you will do an okay function for this middle value well you will take that whether taking this middle value as a time so mid will tell us the minimum time at which i will pluck out k consecutive flowers and form if i take out k consecutive flowers how many bouquet i can form let's assume that i can form small m okay and if this smaller bouquet is greater than or equal to capital m okay which is the number of bouquet i want then this falling condition is fine this part particular mid is fine then i will take my right pointer equal to mid if this value this wind value is not fine then i will take my left pointer equal to mid plus 1 this is the standard binary search function i've been using in the couple of videos so you can also check that video out so that's the whole trick for this question find out left equal to one right is the maximum among all the numbers okay this is the condition we will which i have told you in the starting of this video if m into k is greater than the total size of this bloomberg then later or not minus one directly else i will do this function in which l is less than r i'm using long because these values are very large and if i multiply m and k directly then it can it will give out like for large values it can get overflow so that's why i converted it mid is the mid of left right divided by 2 then this is the okay function in which i will send the mid bloom day mk if this is fine i will make the right equal to mid else make the left equal to mid plus one and turn on play and then how this okay function is working this will take the input of mid which is the minimum time i'm assuming such that i will pluck out k conjugative flash and make m case in this mid time and this is the bloom day uh eric so this is the sub area sub arrays means uh like how many bookkeepers i can make this is actually booking and total and n iterate over from left to right okay so what will i do if a of i is less than equal to mid what i'm actually checking if the current bloom day value is less than the mid value then i can take this in total is telling me that whether i can take this flower in my book so i'm actually moving i'll tell you how this okay function is working let's assume that my uh this map is this okay and uh maybe i can tell that my like let's see that my mid value is equal to or i can make my bloomberg uh let's do this now uh what will i do i will make my let's do that i will make my this value mid value equal to five okay or my mid value is five then what will i do i will go from left to right i will keep on taking these flowers by plucking out these flowers and make a bouquet whenever i found out that this flower is greater than the time of blooming i cannot take this see i have either two conditions i can either like my bouquet size is equal to one so i will take one flower then i'll take that whether i can for a bouquet with this yes so i will take a bouquet out of this but now let's see my bouquet size is equal to two so i will take out this one flower and still i want this is not sufficient to make a bouquet i will add another flower but i will only add this flower if this flower bloom day is less than or equal to the mid which is the bloom day or time i have actually calculated for which i'm calculating this mid value this is the mid value i'm sending in the okay function so what will i do i'll move from left to right tell that okay mid actually define the time this is the minimum time for which i will take out or make the bookies so this is five which means that i'm assuming that at time equal to five i can make i'm actually like searching at time equal to five how many books i can make so at time equal to five i'm moving from left to right and then i will check that okay i can pluck out this cloud because this flower is actually all like already bloomed so then i will move from this to this line is also less than equal to five so i can also take this flat this flower is also fine i can take this plot this cloud is not fine so i cannot take this plot this cloud is fine but also while moving from left right i will check that whether my book is complete my bookish size is two so i'm moving for left right this flower is fine but at this point my book is complete so i will take this as a bouquet and if my this map okay i will make my total equal to zero now again i will take this my bouquet consisting of one flower then i will go to this point but now i cannot take this flower so now this cannot be a complete bouquet because even though there is one valid bloom flower i cannot take it because i have to take consecutive flowers i have taken this as a one bouquet i cannot take this because this is not bloomed and also i cannot take this so as you can see in this particular configuration my answer is one i can only make one okay so that's i hope you get my point how i'm making the quiz so that's how this function is working i'm moving from left to right i'm checking that whether a of is less than equal to mid then only i will increment my total else if this is greater than or equal to my mid then which means that i have encountered a flower which has the bloom day greater than my mid then i have two conditions one condition is my total is greater than equal to k if my total is greater than equal to t i will make my sub array which is actually making the number of bouquets i have i will increase plus which means that i have encountered i'm actually moving from left to right i've encountered a flower which has a bloom day greater than the mid value of talking about so what i will do i will check that number of flowers i have counted till now if the number of flowers counted till now is greater than the bookie size then i will increase my bookish size and i will make my total equal zero total means how many flowers i have taken till now because i have to start afresh because after this point i cannot make a streak i have to make a new stick from this and thus i will make my total will actually be exploring the total number of streak also if at any point my total the total number of flowers i have taken till now becomes greater than equal to k and i will also do the same i will make my sub array or actually number of bookish plus and will again make my total equal zero so i will again make my stick equals zero because i have already make a streak and that's how i'm making or calculating how many strikes i can form if my mid is equal to this and my a is equal to this and the given m and k these are this after calculating out all the values i will also check it for the last condition because the last if i'm iterating from left to right okay uh let's assume that all the flowers are completed okay i will always like i can only check this condition if uh like whenever i feel or whenever i found a flower which is not blue then only i will get into this condition but if all the flowers are bloomed i will move from left to right and i will take all the flowers and like i will not go to in any condition so this condition should also be taken care after completing all the volume will also chill like check that the total after all these should be greater than equal to k so i will also increase the total sub array by 1 again and in the end i will just return out or check that if the total number of sub arrays or total number of bookish i can make with this particular configuration is greater than or equal to m and means how many bookish i want then this is a valid answer so i will return on true else this is a invalid answer i will turn out false and after doing this okay function for all the possible mid values i will get out or get actually the possible minimum possible mid values at the left point so i hope you get the gist this is the same code i've been using for all the like binary search problems i have been posted on this binary sort series so if you haven't check out the latest or the previous videos you can also open my channel and search for the binary search cd so you can check those videos out so i hope you get or like these explanations if you like this explanation please hit the like button subscribe to my channel i'll see you next month keep coding bye
Minimum Number of Days to Make m Bouquets
how-many-numbers-are-smaller-than-the-current-number
You are given an integer array `bloomDay`, an integer `m` and an integer `k`. You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden. The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet. Return _the minimum number of days you need to wait to be able to make_ `m` _bouquets from the garden_. If it is impossible to make m bouquets return `-1`. **Example 1:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 1 **Output:** 3 **Explanation:** Let us see what happened in the first three days. x means flower bloomed and \_ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: \[x, \_, \_, \_, \_\] // we can only make one bouquet. After day 2: \[x, \_, \_, \_, x\] // we can only make two bouquets. After day 3: \[x, \_, x, \_, x\] // we can make 3 bouquets. The answer is 3. **Example 2:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 2 **Output:** -1 **Explanation:** We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. **Example 3:** **Input:** bloomDay = \[7,7,7,7,12,7,7\], m = 2, k = 3 **Output:** 12 **Explanation:** We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: \[x, x, x, x, \_, x, x\] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: \[x, x, x, x, x, x, x\] It is obvious that we can make two bouquets in different ways. **Constraints:** * `bloomDay.length == n` * `1 <= n <= 105` * `1 <= bloomDay[i] <= 109` * `1 <= m <= 106` * `1 <= k <= n`
Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.
Array,Hash Table,Sorting,Counting
Easy
315
927
hi guys welcome to algorithms made easy my name is khushboo and in this video we are going to see the question three equal parts you are given an array which consists of only zeros and ones divide the array into three non-empty divide the array into three non-empty divide the array into three non-empty paths such that all these parts represent the same binary value if possible return any i j such that array with index 0 to i is the first part i plus 1 till j minus 1 is the second part and j till array.length is the third part and till array.length is the third part and till array.length is the third part and all three parts have equal binary values if it is not possible return minus 1 comma minus 1. note that the entire part is used when considering the binary value it represent for example 1 0 represents 6 in decimal and not 3 also leading 0s are allowed so 0 1 and 1 represent the same value now we are given this examples over here wherein let's see the first one if you break down into three equal parts it will be this one then you will have the zero one and then you can have this zero one so the indexes that we need to give is the ending index of the first part which is 0 and the starting index of the third part which is 3 so that is how the output comes now let's see this example number 2. over here we have four ones which can never be divided into three equal parts and so the output is going to be minus one comma minus one and similarly we can apply the logic for example three and get this output now let's go ahead and take one of the examples and see how we can solve this question let's take this example and see how we can get the output so we need to divide this array into three different paths that can have the same number so it becomes these three parts which depict the number five now the output will be the last index of the first partition and the first index of the last partition so over here the output will be 2 comma 8. now that we know how to give the output let's see how we can partition this array so for that let's see the basic intuitions or deductions that we can make from the question itself as the question says we need to partition it into three equal parts which means all the three parts must have equal number of ones and thus the number of ones must be divisible by 3. so the count of 1 is equal to 3 into k where k is the number of ones in each partition if the number is not divisible by 3 we can simply return minus 1 comma minus 1 as it is not possible to divide the array the second deduction is that if all the numbers in the array are 0 then we can return any 3 partition we do not need to calculate any further and the third one is we need to see that the equivalent decimal number and all the partition is same so let's see how we can partition the number here is the first step that we are going to need that is the number of ones that are present in the array for this particular example we have six ones and each my partition should contain two ones so i have taken the value of k as two now the second part find the partition with equal number of ones for this we'll take dedicated variables to define the partitions which are i1 j1 i2 j2 and i3 j3 initially we have it as -1 and now we'll initially we have it as -1 and now we'll initially we have it as -1 and now we'll start partitioning now what are the conditions that we are going to use for partitioning while partitioning we are going to consider a partition wherein the start index has the number one and the end index should also have the number one so whenever the count of the one in the current partition becomes equal to k we say that this is one defined partition for us now you will say that what happens to the zeros and what if there was a zero after this we'll take a look at it in the later part for now let's take this condition and partition the array we'll start with the first index but before that let's see the conditions that will update our variables if the current count of 1 is equal to k 2k or 3k that means we have reached the end and so we assign the index as j1 j2 and j3 on the other hand if the current count of 1 is 1 or k plus 1 or 2 k plus 1 that means it is the starting of that particular partition and so we will assign that to i1 i2 and i3 so our partitions are going to be divided in following way that my count of 1 is starting from 1 to k from k plus 1 to 2 k and from 2 k plus 1 to 3 k make sense okay let's move ahead with this first index the current count of 1 becomes 1 and so we will update it in i1 so the index for i1 becomes 0 depicting this first one that we have encountered for the next zero we do nothing so we'll move to the next one that we have and with that the current one count becomes 2 which is equivalent to k and so we update our j1 because we have got this k similarly for now 0 we do nothing and we move on to the next one that we have and over here the count of 1 becomes k plus 1 which means we need to update i2 and so we update i2 with the index similarly we do for g2 i3 and j3 so now we have the partition ready with us wherein we are only considering the numbers starting from one and ending with one so over here these becomes our partition as we have these partitions with us what we need to do next is compare the numbers that we have in this if the numbers are not equal then there is no chance of bifurcating it into three parts and so we can simply return minus 1 comma minus 1 but in this case as we see the numbers are same now comes the next question what about the zeros so for that let's take one more zero at the end and see what happens as we have this 0 at the end the number that we need to consider for this last partition is not 1 0 1 but 1 0 because this is a trailing 0 and so what we need to do is we need to count the trailing zeros that are present for a partition so that becomes this for the partition number one that is the first partition we have two trailing zeros for second one we have no and for the third one we have one trailing zero so if we have a trailing zero for the end number that is for the number in the third partition then we need to consider that and we need to have minimum those number of zeros in all the partition at the end so over here as we have one zero in the last partition we need to have at least one zero in first and second but as this violates the condition that second has no trailing zeros the output again will be minus one comma minus one for now let's take a zero in the second partition also now what happens the last partition has the number one zero second partition has one zero but the first partition has one zero one double zero so what do we do with this zero is actually going to be a part of the second partition as a leading zero and not the trailing zero for the first partition because leading zeros do not have any effect on the number that it is forming and so our partitions become like this what is the output will be the j1 that we have found that is this part 2 plus the trailing 0 that we need to have that is 1 0 so this becomes our first partition then the second partition comes and the third partition will start from the j2 that ended plus the trailing 0 that we had plus 1 for going to the next window so that gives us j2 plus trailing 0 plus 1 so that will give you the output so now we know the basic just of the question when we need to return minus 1 comma minus 1 how do we need to partition how we need to consider the trailing zeros and how we find the output from the indexes that we have found out plus the trailing zeros that we need in our partitions so the theory part over here is over let's go ahead and code this out so firstly let's take n which will give array.length secondly we'll take one array.length secondly we'll take one array.length secondly we'll take one count that will give us the count of once and we'll take a loop and count the number of ones in the array so this is counting number of ones now we'll take the base exit condition which is if the number is not divisible by 3 we return minus 1 comma minus 1. if one count is equal to 0 return any partition so let's write that condition so over here you can return 0 comma n minus 1 and now what we are going to do is find k which is 1 count by 3 and now create partition so for creating the partition we need six variables and will take an integer variable to hold current count of one which is initially going to be zero and now we take a follow in this follow we are going to check if my array of i is equal to 1 because in that case only we are going to update our variables we need to first do current count plus 1 and then we need to see if current count is equal to 1 then we need to update i1 equal to i otherwise if current count is k plus 1 which means i 2 is going to be equal to i if current count is 2 k plus 1 then i 3 is going to be updated with the current index now let's write the conditions for j if current count is equal to k j 1 equal to i similarly for j 2 and j 3 so this will give me inj values for all the three partitions now comes the part wherein we compare the three partitions so for that there are two methods the first is by using extra space let's use that first so this is the first part and similarly we'll have part two and part 3 and this will just change to i2 i3 and j2 j3 we are taking this plus 1 because this index is not inclusive now that we have these with us we just need to compare it so if part 1 and part 2 are not equal or part 1 and part 3 are not equal that means we have an unequal part and we cannot divide the array and so we can just return minus 1 comma minus 1 now if this also passes we need to take care of the trailing zeros and for that we need to first count the number of trailing zeros in first second and third part so the trailing zeros in first partition is equivalent to starting of second partition which is i2 minus ending of first partition minus one similarly for second we'll do starting of third partition minus ending of second partition minus one and for third we'll do the end of the array minus ending of the third partition minus 1. so now we have the zeros with us again there is an exit condition that is if the number of trailing zeros in third partition is still greater than the minimum number of zeros present in first and second then we have no chance of partitioning it into three equal parts and so we can return minus one comma minus one once we are done with this part also and the code comes below this we can return our indices and these indices are last index of the first partition which is going to be j1 plus the number of trailing zeros that we are going to have and that is given by third and the first index of the last partition which is j2 plus third plus 1 so this will give me last index of the second partition and this plus one will go to the start of the next partition let's run this code and we are getting a perfect result let's submit this and this got submitted now the time complexity for this is of n as we are going to iterate over the array the space complexity is also going to be o of n for this part which we can reduce too often now let's do that so we'll just remove this part and we'll write a while loop so let's take a few variables so we'll take start mid and end which are going to be i 1 i 2 and i 3 so these are the starting indexes of my three partitions and we already have our k with us so let's start a while loop so while k minus is still greater than 0 and array of start is equal to array of mid and array of mid is equal to array of end which means the numbers are equal so i can just do start plus mid plus n plus so this will continue till i am finding equal values now if everything was equal my k will become -1 my k will become -1 my k will become -1 so i need to take that into mind if my k is still greater than equal to 0 then i can return mu into minus 1 comma minus 1 as we found an inequality and this loop broke before it should have broken so that's the o of one space method let's run this also and let's submit this and it got submitted with this solution our time complexity still stays of n but the space complexity becomes of one that's it for this video guys i hope you liked it and i'll see you in another one so till then keep learning keep coding you
Three Equal Parts
sum-of-subsequence-widths
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
Array,Math,Sorting
Hard
null
1,461
hello everyone welcome to day 12th of march lead code challenge and today's question is check if a string contains all binary codes or size k so in this question you are given a binary string an initial k you need to check whether for every binary code of length k is the substring of the given input string s if all the binary codes are part of this string s then we need to return true otherwise we need to return false so let's understand it with an example we are given a string s as this and k equals to 2. you need to generate all the binary codes of length k that would be 0 1 and for each of this binary code we need to check whether it is part of the input string or not if it is part of the input string we continue the process till with the time we don't exhaust this list otherwise if it is not we abort the process and return false from there and then itself so let's quickly understand the algorithm that i have created for this i'm taking a pen here and this is a naive algorithm that states to generate all the binary codes of length k and check if the generated code is present in s it's part of s or not if s dot contains all the generated codes then we return true from a solution otherwise if we find at any step that this is not part of the generated code is not part of string s we abort the process and return falls from there and then itself what are the issues with this approach the primary issue with this approach is to is that we are generating all the binary codes that means we have to generate two desktop k binary codes if k is the given integer and that would be expensive and again we need we will be checking for each of this a generated code whether it's part of the string or not that would again be expensive we need to do the traversals every time we are checking the generated code so s dot contains is the time complexity for s dot contains method is order of n where n is the length of s so the total time complexity would become n into 2 raised to par k which is quite high can we do something better than this yes how can we reduce the time complexity and the space complexity for the solution so let's think in the opposite direction what about creating all the substrings or size k from this input string s so let's assume the length of the string is n and we k is given to us as 2 so we will generate all the possible substrings of size k using this string s so what those would be let's start from the first index 0 let's move to the next index we have 0 1 then we have 1 0 then we have 0 1 then we have 1 0 so this is the complete list of sub strings of size k if we want to remove duplicacy from these substrings how can we achieve it we can put them in a hash set instead of a list so the solution says create a hash set instead of a list for where you are adding all the generated strings of size k into your hash set so therefore the hash set will look something like this it will have 0 1 and 1 0 so how this will help us whether we have covered all the cases or not there is a mathematical formula which we can use the total number of binary codes of length k would be 2 raised to par k and we can compare the size of this hash set with this value if there is a discrepancy or a mismatch between the size and expected size and the size of the hash set we'll return false otherwise if there is an exact match then we'll return true so pretty simple way of thinking where we are generating all the possible substrings of length k putting them in a hash map then comparing the expected size what would have been if there would have been an exact match what that would be tourist per k what is the current size of the hash set would be given by set dot size if it matches then we return true from a solution otherwise return false i hope this solution is clear to you and let's talk about the complexities here are we able to reduce the complexities the answer is yes how we are traversing the string s only once so the time complexity would be order of n minus k and uh what we are also generating uh substrings of length k so we will have to multiply it with k so the complexity would be order of n minus k into order of k and what would the space complexity the worst case space complexity what this solution would be order of two estimate because we are generating there could be a case where there is an exact match and we have to we will have to store all of these in our hash set so space is slightly compromised but the time complexity is has reduced drastically so let's quickly move on to the coding part first of all we can have a safety check if it happens that the length of the input string is less than k is greater than the length of the input string that means we'll have to return false up front because there will be no way you can achieve it otherwise let's move on with the processing we'll have a hash set of site of type string new hash set and let's start generating the substrings of size k i equals to zero i is less than equal to s dot length minus k i plus and let's add the generated string into our hash set s dot substring i comma i plus k and once we have all of them added in the set let's compare the size the expected size and the current size so this is the current size what is expected size that would be math dot pow 2 comma k and i think we are good here let's just try and run the code return to and let me just submit it accept it the time complexity would be order of n minus k into k because you are generating all the substrings and then the space complexity is order of 2 raised to 1 k you can improvise this complexity further by instead of using the substring method uh you can use the two pointer approach to build those strings each time you remove one character from the start add one character to the end and this complexity can again be reduced to order of n minus k thanks for watching the video hope you enjoyed it and please don't forget to like share and subscribe to the channel
Check If a String Contains All Binary Codes of Size K
count-all-valid-pickup-and-delivery-options
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively. **Example 2:** **Input:** s = "0110 ", k = 1 **Output:** true **Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring. **Example 3:** **Input:** s = "0110 ", k = 2 **Output:** false **Explanation:** The binary code "00 " is of length 2 and does not exist in the array. **Constraints:** * `1 <= s.length <= 5 * 105` * `s[i]` is either `'0'` or `'1'`. * `1 <= k <= 20`
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Math,Dynamic Programming,Combinatorics
Hard
null
249
how's it going everyone michael here so today we're going to go over the algorithm problem group shifted strings this is a very popular facebook problem and you kind of have to think outside of the box to solve it's definitely not your typical problem at least not from my experience but i'm gonna walk through it step by step for this problem we are given a list of strings like this and we have to group these strings together based on their shifting sequence so you know what is a shifting sequence so let's look at these two strings abd and bce so to get from character a to character b that only takes one step since b is right after a and then to get from b to d that takes two steps so essentially our shifting sequence for the string abd is one two now for string bce to get from b to c that takes one step and to get from c to e that takes two steps so once again our shifting sequence is one two for this string both of these strings have the same exact shifting sequence because one they are the same size in length and two their patterns are the same both strings had the same shifting sequence of one and then a two after we determine the shifting sequence for every string in our list our output should be the following abd tied with bce ac tied with y a and h tied with p so let's jump into the algorithm in order to group these strings efficiently by their shifting sequence we are going to need a hashmap the key in our hashmap is going to be the shifting sequence and the value is going to be a list of strings that match that shifting sequence so we're going to need to loop over all of the strings in our array so starting at index zero we have the string abd now to get from a to b that takes one step and then to get from b to d that takes two steps so our sequence is one two one thing to keep in mind is for each shift that we do we need a delimiter between them so we can just use a comma for example you could use any character as long as it's not a digit the reason this delimiter is needed is because we need to be able to differentiate a shifting sequence from another as an example let's say i represented this one comma two shifting sequence without the comma so let's just say i represent it as one two but this would not be able to tell the difference between a shifting sequence of 12 like the number 12. 1 2 and 12 those are obviously different shifting sequences so that's why you need a delimiter so moving on we have a sequence of one comma two and we're gonna check if that string is inside of our hash map and since it's not we're gonna create a new entry with a list containing the string abd next we're gonna look at string bce from b to c that's one step from c to e that's two steps so our shifting sequence is one comma two and we do have that shifting sequence in our map so we're just gonna add bce to our list next we have the string ac to get from a to c it takes two steps so our shifting sequence is just two and we're going to create a new list for that shifting sequence and add the string ac next we have the string y a and so for this string it's a little bit interesting because to get from y to a we have to essentially circle back around still this would only take two steps one to go from y to z and one to go from z to a and so our shifting sequence is 2 and we're going to add y a to that list next write the string h and this shifting sequence is just an empty string there's no sequence since it's a character on its own so we're gonna create a new list with the string h and then finally we have another string of size one the shifting sequence is empty string so we're going to add p to that list so by the end of iterating over all of the strings in our list we will be left with this final output all right let's go over the code for this solution we are given an array of strings and then we need to return a list of lists of strings from our function essentially grouping all of the strings by their shifting sequence the first thing we want to do is initialize our hashmap next we need to loop over our list of strings so we're going to say 4 string str in strings and essentially what we need to do for every string is compute that shifting sequence so what we can do here let's initialize a string builder and we can call it pattern and now we need to start computing the difference essentially how far away each character is away from its neighbor so in order to do that we need to start a loop starting at index one so we're gonna say for int i equal to one and then i is less than string dot length i plus and so what we're going to do is compare the character at i and i minus 1. so what we can do is say char prev is equal to string dot char at i minus one and then cur our current character is string dot char at i and now we need to compute the difference between these characters so in my opinion i think having a separate function for this makes sense so we'll say int and we'll call it maybe distance and we're going to say compute distance and we're going to pass in the previous character and the current character so for now let's just assume we have this function written just so we can continue on in the logic so what we want to do now is we're going to say pattern dot append we're going to append this distance to our pattern and then we're also going to append a comma and so like i mentioned you can use whatever delimiter you want you could use a comma maybe you want a pipe it doesn't matter as long as it's not a digit next what we need to do is when we come out of this for loop we need to create a new list if the shifting sequence does not exist and then we just need to say list dot add the string and then we need to update our map so we're gonna say map dot put and we're gonna put the pattern with the list inside of it and then when we come out of this for loop we're returning a list of lists of strings we really only need the values inside of our hash map we don't need to know the actual shifting sequence values we only we just need to group them together so what we can do here is we could just say return new arraylist and we're going to say map.values and we're going to say map.values and we're going to say map.values and so the last thing we need to do is create this compute distance function so remember we have characters but we want to know the distance between them so in order to do that we could say in val is equal to prev minus the character a plus one and then val2 is equal to her minus character a plus one so why did we do this the reason we do minus character a is because any character that's a letter minus the character a will give us the actual integer value so for example if we had character a minus character a that would be the value zero and then we don't want it to be index based so that's why i offset it by one so if we had the character a minus the character a this would equal zero but then we're offsetting it so now this is one all of the possible values that we can have in this compute distance function are just 1 to 26 so now that we understand that we can come down here we're going to say return if val is less than val2 this is the simplest case all we have to do is val2 minus val but there's still an extra edge case remember we went over an example previously say we were comparing character y with character a we have to essentially wrap around so in order to do that we need to compute the distance from y to z but then compute the distance from a to wherever value 2 is so in order to do that we know there's 26 characters in alphabet so all we have to do is say 26 minus val plus val2 and so that is it for this algorithm let's submit just to make sure it works our time complexity is going to be big o of m times n where m is the number of strings we have and n is the max string length because for every string we need to iterate over all of its characters in order to determine its shifting sequence line four is the big o of m portion line six is the big o of n portion and since the loop is nested we multiply these notations together our space complexity is going to be big o of n where n is the number of entries we have in our map i have some other string problems on this channel if you want to learn more problems like this also check out my public discord channel it's still fairly new and the group has grown a lot so if you're looking to maybe get some study partners or just you know talk about computer science related topics this is a great place to do it so that's all i have for you guys and i will see you all next time
Group Shifted Strings
group-shifted-strings
We can shift a string by shifting each of its letters to its successive letter. * For example, `"abc "` can be shifted to be `"bcd "`. We can keep shifting the string to form a sequence. * For example, we can keep shifting `"abc "` to form the sequence: `"abc " -> "bcd " -> ... -> "xyz "`. Given an array of strings `strings`, group all `strings[i]` that belong to the same shifting sequence. You may return the answer in **any order**. **Example 1:** **Input:** strings = \["abc","bcd","acef","xyz","az","ba","a","z"\] **Output:** \[\["acef"\],\["a","z"\],\["abc","bcd","xyz"\],\["az","ba"\]\] **Example 2:** **Input:** strings = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strings.length <= 200` * `1 <= strings[i].length <= 50` * `strings[i]` consists of lowercase English letters.
null
Array,Hash Table,String
Medium
49
1,823
hello everyone today I'm going to solve code problem find the winner of the circular game there are n fres that are playing a game the fres are sitting in a circle and are numbered from one to n in a clockwise order more formally moving clockwise from the ice FR brings you to the I plus one's FR for one is L than oral to I is less than n and moving clockwise from the end frame brings you to the frame first frame the rules of the game are as follows start at the first friend count the next ke friend is in clockwise Direction including the friend you started out the counting wraps around a circle and may count some friends more than once the last friend you count leave the circle and loses a game if there is still more than one friend in a circle go back to step to starting from the friend immediately cles from the friend who just lost and repat also the last friend in a circle wins the game given a number of friends and an integer K return the winner of the game let's take an example the first example which is n is five and K is2 so uh I'm going to arrange the friends in a clockwise Direction in a circle and they say we have three four and five right so the we start from the first frame and we will count two frames and the one we just stop counting is lows the game right so one two is going to L the game and it's going to remove from Circle and we start from immediately to the right of the one which loses the game so we start from three and we're going to be at four and we're going to remove this three from the game and we start from five and we will be at one so one is going to remove the game or move from the game and we start from three because to lose the game we start from three right so three is going to three and we were going to remove five because five is the one we last counting right so we start and we start from three and there is no one right so three is the one which win the game because three is only one in the game right so we are going to solve this problem this way but if you know already about rf's problem it's going to be easy for you um so it what we are going to do is I'm going to represent the this fres as nor like I'm going to represent them like this one like let's say we have five friends a BC right so we have ABCDE e right we have five friends and the indic are just the one two and three and four right so in this Arrangement n is five right we have um five and we have K is to right so this is um our parameters right so we have this Arrangement so the one which loses the game is B right so B removed from the game and our representation is going to be we start from C D E and A is going to be the last right so and our indices will be like one uh two and three right so we will have four friends and um we have only 2 Cas is not going to change right so now the loser of the this game is d right d is going to lose the game and remove from the game so um our Arrangement is going to be e uh is the first one and C is the last right so and we will have uh this indices right you can see the indices then now we have three frers and two right and last and when we remove when we are here this Arrangement the loser is a right so we're going to start from c and e will be the last right so now we will have this indices right so uh n is going to be two and our K is not going to change as always so in the last the loser is uh the winner is C right C is only the only one which left is in the game right so it's in will be a zero right so a zero and um and N is equal to one right so n k is two right so um as you think about this as recursive um recursive uh way of solving the problem the sub problem so this uh we will return the indic right so whenever we are we have one friend so it's going to return where it's position right position is zero right it's going to return the its position is going to be zero right it's going to return zero to the one which calls it right so zero is return to this one so the one we want is the position of the winner so as you can see the position of the winner in this game is C right so in the last uh sub problem the position of the winner was zero and in the second in this one the position of the winner is the C is zero right so it's going to be zero also here and the position of the winner in this one is two right the position of the C is two right it's going to be two and the position of uh the position of C in this one is three right uh zero right and the position of C in the first call is going to be two right it's going to be two so as you can see there is some kind of pattern right so what we are going to do is once we are adding two k to the one that's returned from uh return it from uh one the one we call and we mod by two right let's say for example for this one for the last code whenever we remain with one frame its position is zero right we return zero and we plus 0 Plus it's going to be like 0 plus two right 0 plus two is two mode by two because the number of friends at where at this position is two right two by more by two is zero so the we the position of the winner is zero right so it's going to be zero here and 0 + 2 is also two here zero here and 0 + 2 is also two here zero here and 0 + 2 is also two here right as you can see and the number of friends is three at this position and two M by three is going to be two right so the position of the winner is two here and we add uh we add two to when we add 2 + two is four right it's going to add 2 + two is four right it's going to add 2 + two is four right it's going to be four more by4 is zero right the position of the winner is here zero and when we are at this position the position of the winner is two right since 0 + 2 is two and two more by five since 0 + 2 is two and two more by five since 0 + 2 is two and two more by five is two the position of the winner is two so our recursive solution is going to be like this one so we are going to solve this problem using this methodology so um time complexity is just where um so it's going to be like um time is just the it's going to be uh see K log kilog in um since um I think it's not it's going to be off in instead of K again because we are decrementing each time by um as you can see we repeat this thing we have done this thing and five times right it's going to be n and um space complexity is also the Cod St is going to be in right so I'm going to solve this problem uh in of and of in space in time so I'm going to implement this way so uh I hope you get the point so going to write the code so our base case is going to be if um this function for example we say let's define our function to see us so let say to see us takes two parameters like any NK if n is going to be one I mean it's one we going to return zero right since is going to be zero so otherwise we are going to return um k um plus um that we going to call Josephus and say Josephus of n minus one comma k um we M um it by n right we are going to mode the whole thing by one by n and then we are going to return um to seeus to see of uh n comma K uh I think uh k n plus one because why we make plus one is because we have made um the IND is zero right we start from zero instead we have to restart start from because the fres are numbered from one to n right so I have to make it plus one right so let's run the code and see what's going to happen um so as you can see it passed so it's submitted and see if works for all the test cases so it passed um okay I think see it pass so it bits this much of the pyth users and space this much of the Python users so thank you very much
Find the Winner of the Circular Game
determine-if-string-halves-are-alike
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
String,Counting
Easy
null
1,399
Hi everyone, I am Nishant and you have joined with the entry. In this video series, we will prepare for the interview by doing a lot of questions of lead code, so which question are we going to do today, let's see let's dive in. Hi everyone, I am Nishant. Today we are going to do question number 1399 on lead code i.e. Count Largest Group. Let me i.e. Count Largest Group. Let me i.e. Count Largest Group. Let me read the problem once and then let's see how we can find the solution. The problem says that you are given an integer n. An integer n will be given to you. n can be anywhere from one to 10 to the power of 4. Each number from 1 to n is grouped according to the sum of its digits. So every number from one to n is grouped according to the sum of its digits. Like see here one and 10 have been grouped because their even digit is one, 2 and 11 have been grouped because their even digit is two, okay 3 and 12 If the digit of these people is even three, then they have been grouped in this manner. Return the number of groups that have the largest size. So, how many number of groups are there in the group that has the largest size. Ok, listen carefully. Largest. If we have to return how many number of groups with that size, then what we will do first is that we will find out the largest size, okay, from the groups formed according to the sum, we will select the group which has the largest size. Let's do one thing, first take a hash map and keep a variable named largest size, make it zero, now what we will do is first find the digit sum of every number from one to n, okay once the digit sum is found. Then we will go to the number of members of that sum, okay, whose digit is the sum, and we will increase it by one. Okay, starting from zero, we will keep increasing it by one, then this will store the entire number corresponding to that sum in our map. Another thing we have to do is to keep updating the largest size inside the loop. As soon as we find a larger size group of that particular sum, we have to keep updating it. After the end of this loop, we will get that largest size here. We will know who can belong to any group. In this case, once that is done, then we will take a variable named result, initialize it with zero and iterate this map and see all such values, okay, all the values ​​which are see all such values, okay, all the values ​​which are see all such values, okay, all the values ​​which are largest. If it is equal to the size, then this will tell us the total number of groups which is of the largest size. Okay, and we will return the same once we submit it. Okay, so here I have submitted. After submitting, look at this submit. If it is done, I hope you have understood this problem, ok, it is an easy problem, I will meet you in the next video, till then by and
Count Largest Group
page-recommendations
You are given an integer `n`. Each number from `1` to `n` is grouped according to the sum of its digits. Return _the number of groups that have the largest size_. **Example 1:** **Input:** n = 13 **Output:** 4 **Explanation:** There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: \[1,10\], \[2,11\], \[3,12\], \[4,13\], \[5\], \[6\], \[7\], \[8\], \[9\]. There are 4 groups with largest size. **Example 2:** **Input:** n = 2 **Output:** 2 **Explanation:** There are 2 groups \[1\], \[2\] of size 1. **Constraints:** * `1 <= n <= 104`
null
Database
Medium
2046,2097
494
so today we're looking at lead code number 494 it's a question called target sum and so we are continuing on using our backtracking recursive template our depth first search recursive helper and we are solving this using that method and it's the same method that we're using to solve all the other questions in this playlist that deal with permutations combinations or subsets so one of the reasons why i chose this is just to show you how powerful this template is because you can solve many problems that deal with any of those issues like permutations subsets or combinations quite easily by just implementing this template and just filling in the blanks so to speak but i think it's also really important to know what it's doing under the hood so we're going to conceptually go over the recursive tree and then we'll go ahead and implement the code and we'll use the template and we'll see how effective this is okay so here we're given an integer array nums and an integer target and we want to build an expression out of nums by adding one of the symbols plus and minus before each integer num and then concatenate all the integers for example if nums 2 1 you can add plus before 2 and a minus before 1 and concatenate them build the expression plus 2 minus 1. we want to return the number of different expressions that we can build which evaluates to the target so here we have an array of five ones and our target is three so output is five because there's five different ways or five different combinations of these numbers in array where if you put a positive or a negative in front of them that will sum up to the target three here example two there's only one way we can get one and that is by the number that's in the array and we have some constraints here that the length of the nums array is going to be less than or equal to 20. um and then here okay that's gonna be zero to one thousand okay so let's go ahead and build out the recursive tree to kind of show what's going on underneath the template that we're using and then we'll go ahead and implement the code okay so the idea here is we want to do exclude include okay and we don't want to you know build a string and then convert this to numbers and concatenate it and figure out if this equals three we don't need to do that we can just keep a slate variable that's going to just keep a running sum as we build out this tree and then when we get to the leaf node we can check does that running sum equal our target if it does then we can just go ahead and increment a result counter so that's the most efficient way to kind of go about this instead of building out a string and doing all that'll just take up a lot of space and time as well okay so here we're going to have we're going to start with our ith variable whoops let me go ahead and fix this here i'm just gonna grab this pull this over here and erase this one here so i can move this around okay so here we're gonna grab our ith variable here our ith value and what we're going to say is at this point we're going to add or subtract whatever this is to our slate which is going to start at 0. so what i'm going to do here is i'm going to write positive and negative okay so whatever the value is on the left we're going to make it positive on the right we're going to make it negative so here it's one so we're going to add one to the slate and we are going to subtract one from the slate okay so now on the first level our uh our running sum is going to be either one or uh minus one our base case will be if i is in the range of nums okay so i then increments we go down the tree we increment i pass it in the recursive helper and now we do the same thing for each one of these nodes okay whatever the slate is this is one we're gonna add one so this will be two and we will subtract one which is going to go back to zero same thing here we are going to add one which will this will go to zero or we will subtract one and this will go to minus two okay so now we're going to go ahead and increment i again okay and we are going to pass in we're going to go ahead and recursively call all the values on this level of the tree so here uh we're gonna add one so our running sum will be three we're gonna subtract one so our running sum will be one here we're going to add one so our running sum will be one and we'll subtract one so this would be minus one same thing here this would be 1 this will be minus 1 and this will be minus 3. okay all we're doing at each level is we're just adding or subtracting the value that's in i okay and then we're recursively going down the tree so now we're going to go ahead and increment i go to the next level here i is still in the range of nums so we're not at our base case and we're gonna do the same thing we're gonna go ahead and add one and subtract one okay add subtract add let's see here this is going to be one two this will be zero this would be 0 minus 2. um we're going to add 1 here so that'll be 0 and we'll subtract 1. this will be minus 2 and this will be minus three okay and now we go ahead and increment i on this level and we go down the tree okay now we're building this out breadth first search but in the actual code it's actually doing this depth first search and i'll explain a little bit of that um once we build out this tree okay so we're still not at our base case now we're gonna get to our final base case okay so we're gonna add one here this would be five this will be three now we hit our leaf level here okay so we hit three and when we hit that leaf level that base case we want to check what is in this so far what is in our running sum does it equal our target here if it does we want to just go ahead and increment our result okay we have a global result and we're just going to go ahead and increment that by one okay same thing here we're going to add one so this is going to be three this will be one and again we hit this base case here and we check does this equal the tar our target is three not five so that's my mistake let me just go ahead and change this is not a five this is a three okay so it does hit that base case and what we're going to do here at three is we're going to go ahead and increment our global result okay and now we here at two we subtract one this is going to be uh one here we add one so this is going to be three again this goes ahead we're going to go ahead and increment our global result to 3 and then we're going to backtrack and move on okay so now here this is going to go to 1 this is going to go to -1 so on and so forth so you can see -1 so on and so forth so you can see -1 so on and so forth so you can see that any time we're hitting a two we're going to get a three when we on the add one so here and i believe that's it okay so we have one two three this is also going to go down to three and this is gonna go down to three okay and so we have one two three four five so our global result will increment to five and that's what we'll return and that is indeed the correct answer so you can see how this is forming a tree and how this is working now we built this tree out level by level but in the code it's going depth first search it's going to go and build out this part of the tree first then it's going to backtrack pop it off the slate come back this way come back that way and it's doing this all depth first search and it's doing it in pre-order in pre-order in pre-order okay so we're building this recursive tree that's kind of going this way okay so let's think about time and space complexity here okay so if we think about time complexity well here we have one right let me use i'll use blue uh for this so here we're gonna have one operation here now we're gonna have for each node at the root level we're gonna have two choices okay so we'll multiply that by two now each one of these nodes here we're going to have two choices so we'll multiply that by two which will equal four now we're going to have two choices on that which is going to equal eight this will equal 16 and this will equal 32 right and so if you notice here how many times are we doing this we're doing this n times one two three four and five right so we have n numbers and we are doing two to the n operations okay so our time complexity here is going to be 2 to the n because at every level of the tree we're doing two operations on each node so it's just going to be it's going to be worst case 2 to the n now what about space well because we're keeping everything in a counter we're not going and concatenating a string and then doing a linear operation we're just keeping a running sum and keeping a counter we're hitting constant space on all of that but we have to remember that we have because we're doing recursion we do have a call stack so our recursive call stack how deep does it go what is the height of our tree worst case at any point during this code right at this point what is the worst case for the height of the tree is log n so it's going to be n numbers okay so you can see here this is going to be the height of our tree worst case at any point from the root to the leaf level and that's n so worst case on space is that we're at a leaf level and it's going to be o of n okay and so the height of the tree is log n relative to the respective to the size of the tree okay uh and so here this the size of the tree is two to the n and so our height is going to be n okay and worst case at any point that's going to be the height of our tree so that is time and space complexity and let's go ahead and jump into the code here and code this out and again we're just using this template so what we're going to do is we're going to create a global result okay and so i'll set this to result i'll set it to a counter zero then we'll have our depth first search helper okay and this will be i nums target and a slate i'll call it running some okay make sure i got that okay and so now what do we want to have our base case okay so what is our base case um if i is going to equal nums.length that means we're at the leaf nums.length that means we're at the leaf nums.length that means we're at the leaf level what do we want to check if running sum equals target okay and if it does all we want to do is increment our result and then we return out of there okay and now we're going to have our depth first search recursive helper and so we want a positive include positive and then we want to include negative okay so how do we do this we're going to add on to our running sum we can do a plus equals nums at i and then we pass this into our uh our depth first search for increment i pass in our nums pass in our target and pass in our running sum okay and then we can we just want to remove that from the running sum as we go back up the tree okay and then we want to just pretty much do the same thing for include negative however what we want to do here is let me just zoom out here so you can see the whole thing uh what we want to do here for negative is just go ahead and switch the signs here all right and now we're going to run our depth first search i will be 0 nums target and our running sum will start at zero and then we return result okay and so that's it's not too bad and you can see that the code here this code right here like the base case that first search recursive helper include exclude or include two different things um that is just it's taken straight from this depth first search backtracking template that i'm using to solve every other problem in this playlist so if you're still confused about this definitely recommend checking out these other videos it's a very powerful thing to really have a handle on because you can solve a lot of problems that are dealing with any permutations subsets combinations really quickly and easily all right let's just go ahead and run this make sure everything works okay and we're good okay and so that is leap code number 494 target sum uh it's a great question it's really fun and it's not too bad to solve it's just make sure you understand conceptually what's happening with these so you just don't want to rote memorize this because it's just not going to work that way you really want to understand what's happening under the hood but once you do get that once that connection is made it's quite magical you know because you can solve a lot of other problems really quickly okay that's 494 target some hope you enjoyed it and i will see everyone on the next one
Target Sum
target-sum
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`. Return the number of different **expressions** that you can build, which evaluates to `target`. **Example 1:** **Input:** nums = \[1,1,1,1,1\], target = 3 **Output:** 5 **Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 **Example 2:** **Input:** nums = \[1\], target = 1 **Output:** 1 **Constraints:** * `1 <= nums.length <= 20` * `0 <= nums[i] <= 1000` * `0 <= sum(nums[i]) <= 1000` * `-1000 <= target <= 1000`
null
Array,Dynamic Programming,Backtracking
Medium
282
1,221
hello everyone welcome to question coder so in this video we will see the question 1221 that is split a string in balanced strings so this is a lead good question and it can be asked in an interview because it is an easy level question or it can be asked as a level one question for competitive programming if you would have tried code forces or code shape so let's see the problem statement then i will explain you how we can solve this question efficiently and i will also give you provide you the code in the description along with explaining the code so let's see so given the balance strings ballastings are those who have equal quantity of l and r characters so that means it is clear that a string which is of consisting of only l and r is given and ballasting is that which has equal number of else in us the number or count of l and r are equal so given a balancing s split eight into maximum amount of balanced strings so we are given a string s which is totally a balanced ring that is if we take a whole string and we have to break it into maximum amount of balance swings so return the maximum amount of the splitted balance string so let's see the example so you can see in this example we are given a string you can see this also well i will explain with this so you can see this example if we are given a total string s so in this all the number of uh left and uh r and l symbols or characters are equal you can see our occurs you can see five times and also occur four times so we have to return the maximum number of the sub strings which we can get from this string total string which is also all the substrings should also be the balance ring so you can see in this example so this is the string if you can see we break it like r and l you can see r and l so left and r and l are equal so you can see count of r and l are equal so this is a balancing and if you can see we can take this three else and three r so you can see this string so this is also a balancing because the number of l's and others are equal and you can see then lasting will be l and r so we can at most we can make three uh three sub strings which are the balance strings from this given string so we have to return that number you can see three so we for similar for this example you can see l and r so you can see there are equal number of lnr's but you cannot break a string because you will not get equal number of elena if you can see if you try to take this something or you can try to take any substring you won't be able to find equal number of l and rs in any substring because you can see this is of different structure so here the answer will be one only because the total string is balanced or we can see balancing so that is why we will simply return one so in this example also you can see this thing that we are given here we can uh we can break it into you can see r and l then we can only break into r and this l and r l so therefore the answer for this thing will be two so you can see the constraint so a string size will be between one to one thousand so that is not a big size and so we can handle it easily so this condition we know that the single loading consists of capital l and capital r so let's see the example uh again i will explain with example more detail in with detail then i will explain the approach then the algorithm so let's see so this is an example that we didn't see so you can see this string that we are given so it only consists of r and l uh characters so let's see how many we can how many strings substrings we can get which are balancing from this total balance string so let's see so here you can see till this thing you can see l and r and l are equal the number of r and l are equal 1 so that means we can again what one substring this and then we can try to take this but this will be not having equal number of lnr and because it does not have any l only so this one this will be also not equal balancing so this one this is the one that we can get so the number will increase to 2 so now you can see this will be again this can be taken as a substring which is balancing r and l then this can be also taken so that means the total number of balanced substrings that we can get from this total balance string is actually 4 for this example and let's check out the answer so you can see the answer is 4 for this so for this example you can see this is this example is same so you can see that here we can break this r and l so their equal number of r and l then we can try to break this with here the l is not there so that means we cannot take this also so therefore the you can see we cannot take any of the substrings so this uh substring actually you can see there will be no equal number of l and r's so that is why we will have to take whole substring so it will be you can see three l's and three r's uh you can see this four else and four hours so that is why the answer for this will be two actually so let's see this example actually you can see ll so this is example you can see output is two you can see we can take only these two substrings from this total balancing so therefore the answer will be two so now let's see how we can approach this question actually so this is actually i will give you a hint this is actually an observation based question because if you see we don't have to make any substring or we actually have to split the string so what we can do is you can see we every l is dependent or every balance ring is dependent on the number of r's and number of else and if it if we traverse from the from this thing you can see we will trus from the left right to this string and we will check at what point the number of r and l's are equal if you see all the substrings that we are making from this total string is actually when the number of r's and else are equals we don't care about where the r and l exist we care about the point at which point the r and l are equal so you can see at this point we know that number of r and l so what we can do is we can make two pointers we can make two counters actually c one and c two so l and r you can make so at every point we if it is r so we will simply increment the first pointer if your counter if it is l we will simply increment the second counter and at every point we'll keep checking if these two counters are equal that means we have found a balance string so we can simply increment our result okay you can see so at this point our r and l will become equal so these counters will become equal so we will simply get this so what we can do is when we get them equal so we will have to reinitialize them we will set them to zero because the next window will start with the fresh counters so we simply set them to zero so they will again be set to zero now again we will traverse over the string and we will find that so that is why we i will tell you that when you get this question you should always try to observe some things so here as i told you we don't have to make anything so this is actually a simple basic question easy level question so you can simply solve it using two counters as a total so let's see the algorithm then i will explain you that uh with the trident so this is the pseudo that i've written so as i told you will have to make two counters actually left and right or you can do it with one counter also but i will make two counters for easy understanding and this result variable that we have to return it will consist of the maximum number of balanced substrings that we can make so what we will do is we will traverse from this thing from left to right we will traverse from left to right and at every point so we have initialized r and these are our variables or counters okay so at every point we will traverse so this at this point you can see this is r so we have written you can see these conditions if and else so if the character is our this character is the traversing that we are doing so if characters are will simply increment over r pointer or r counter sorry so at every point we will check if our left and r become equal so now you can see left is zero because it is initialized to zero so these are not equal so we know that it uh at this point we have only started the array traversing the array so the balance thing cannot be there so we'll simply go to the next traverse so we will come here next iteration actually so we'll come here now it will be l so we will check if character is equal to go to r so it is not r so that means it is l so we will simply increment our l so it will become one and at this point we know that this is a balanced string you can see this is a balancing number of r's and l are equal they are both one so we will check that this condition if l is equal to r so you can see l is one and r is also one that means we have found a one uh substring or one substring actually which is a balancing so we'll simply increment a result that we have to return so the result is incremented so it will become one so now we come to this point r so here at every point as i told you when we get this we will what we do is we simply reinitialize our l and r to zero actually because for every window we should have the fresh counters so we'll simply increase them and make them zero you can see make them zero so now at this point r will be incremented so it will become one at this point again r will become one because l is zero and r is one so that is not equal so that we will iterate next time so it will i will come here or this point will come here and r will be incremented it will become two so now l is zero and r is two so that means we have not found any substring which is a balancing so again we will increment about this pointer and it will point to this so now the character is l so else part will be run so this left will be incremented it will become one so now again for the next iteration it will come here and l will become two so now when we reach here we will check this condition if l is equal to r so you can see l is two and r is two so that means we have found more substring which is a balanced substitution string you can see r and l two number two and two are else that means this is uh incremented so we will increment sorry we will increment our result so it will become two so now we will re-initialize our left so now we will re-initialize our left so now we will re-initialize our left and right pointer so they will become zero let me discuss so i hope you are understanding how i am doing this so i will uh directly write it you can see if they are in re-initialized then again at this point re-initialized then again at this point re-initialized then again at this point when we come here r and l will be incremented so they will become equal so we will simply increment our result so it will become three so and they will be initialized they will become zero again now again at this point when we traverse these two characters actually r and l will be same and then again our result will be incremented and we have found our results result is four so we can simply return our result so this is totally observation based question this is nothing this has nothing to do with strings or like anything so you can simply use two counters as i told you and a result variable that you have to turn or you can simply write one counter and you can increment when you get r and you can decrement when you get by one when you get l so when it will become zero that means when the number of r and number of left get cancelled so the result will be zero so you can simply increment over the uh this result variable at that time and the time xd for this will be simply o of n or the length of this thing because you're not only interested in this thing one time and the space complexity will be open because you we are just using the variables to keep the count of the result and the number of right and left so let's see the code i will also provide the code in the description you can check the code from there so let's see so you can see i've simply initialized right and left to zero like these are the counters and this is our result that we have to return and this is uh the interfacing the secret space actually so you can see this is a simple auto loop or you can see in the modern follow in the c plus 14 plus so you can see character for every character in the stream we will check if the particular character is equal to r then we will increment over this right pointer or right counter then otherwise if it is not ah that means it will be l so we can simply write else to uh else condition then we will simply increment l plus at every point we will keep checking if the number of right and l uh l r and l are equal then we will increment our result you can see a result zero and i will i can also you can see here i up i reinitialize r and l so you can do that without really any re-initializing so if you don't want any re-initializing so if you don't want any re-initializing so if you don't want to initialize them then you can skip them so you can see i have not set them to r and l to zero so you don't have to do that compulsively so you can see then we will simply done the result after we have traversed whole loop and we have found the number of substrings which have which are actually the balance ring so let's see submit the solution actually so let's see this so i will also write the code in the description as i told you so actually you can see it got submitted and it took uh it took less time than 100 percent observation so it was actually faster than 100 percent of solution or the submissions in the lead code and it took less memory than seventy four point nine one percent of the solutions so thank you for watching guys i hope you like this video and do subscribe this channel and like this video and share this video with your friends for more and for more such videos do subscribe channel thank you for watching guys
Split a String in Balanced Strings
element-appearing-more-than-25-in-sorted-array
**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. Given a **balanced** string `s`, split it into some number of substrings such that: * Each substring is balanced. Return _the **maximum** number of balanced strings you can obtain._ **Example 1:** **Input:** s = "RLRRLLRLRL " **Output:** 4 **Explanation:** s can be split into "RL ", "RRLL ", "RL ", "RL ", each substring contains same number of 'L' and 'R'. **Example 2:** **Input:** s = "RLRRRLLRLL " **Output:** 2 **Explanation:** s can be split into "RL ", "RRRLLRLL ", each substring contains same number of 'L' and 'R'. Note that s cannot be split into "RL ", "RR ", "RL ", "LR ", "LL ", because the 2nd and 5th substrings are not balanced. **Example 3:** **Input:** s = "LLLLRRRR " **Output:** 1 **Explanation:** s can be split into "LLLLRRRR ". **Constraints:** * `2 <= s.length <= 1000` * `s[i]` is either `'L'` or `'R'`. * `s` is a **balanced** string.
Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.
Array
Easy
null
1,604
hey what's up guys this is john here so uh someone suggests me to increase the font a little bit more so i zoom in this page a little bit more to 150 percent so let me know what you guys think about this found i think this should be big enough right for you guys to see it okay cool let me know okay so let's take a look at uh like one of this week's bi-weekly like one of this week's bi-weekly like one of this week's bi-weekly contest problem which is the 100 sorry 1604 uh alerts using same key card three or more times in a one hour period all right so i'm not sure why a lot of people downvoted this problem i mean i think it's a it's okay problem right i mean okay so lead code company workers use key cards to unlock office doors each time a worker uses their key card the security system saves the worker's name and the time when it was used so the system emits an alert if any workers use the same the use the same card key three or more times in the one hour period okay basically you know you're given like a two list basically the first one is that is the name of the person and second one is that the time right the time that this person used this key card and it just asks you to find the person who has used this key card more than three times in an hour okay you know so for this problem you know i so it's always right we need to group those punch times right by the group by the persons and then we just need to sort them we just need to sort those times uh and then after that we just need to use a sliding window right so the sliding window is going to be an hour our uh side sliding windows and we just check if there's any at any moment if there's any more than three times inside the sliding window if there is we simply add it to the final result okay and of course in the end they also ask you to return the uh sort name in ascending order alphabetically this is just it's just like a sort in the end okay and i think one of the things we uh we might need to be careful and not be careful we just we need to be uh aware is that i mean uh the time is given in the format of a string here like a hour and minute so when we use the uh use the sliding windows we need to find a range of those times but those are strings and to add one hour on top of the current of the on the current one basically for example if you're sticking you will stick with the strings format let's say if the 12 0 if you want to look back for one hour it's going to be 11 zero okay otherwise it's going to be a what uh some other formats let's say if there's like uh ten zero and we're going to be nine zero basically you know the stream manipulation in terms of in times will be a kind of annoying so oh wait there's a simple way we think we just need to convert like this string format to an integer time basically we just get the hours right so we have a hours times 60 plus the minute basically we just convert everything into integer of a minute so that will be easier for us to compare cool i think that's it uh let me try to code these things here so basically you know uh first we need the end here we have a length of the key name we can use either of the uh the list here and then i we just need to like a times right uh for the with that originally like dictionary basically to store the uh the times for each persons and then for like i in range n here okay we have a name right the key name on i don't know if we have a time because the key time okay and that's that and now we just need to convert uh this time into each integer number how do we do it we simply do we split these things in by the uh by the colon right and then we have a hour in t equals to the height t0 okay and then we have a minute hint t1 okay right we have now we have in the integer type of the hours and the minutes so now we can store those things here store the at the time for this person basically this uh times this person okay name right we append by the uh the what the h times 60 right plus the minute okay so now we have this we have groups all the times for the rich persons now we just need to uh loop through the persons each person inside the times dictionary okay and then we have a time list right let's say we have time list here so it's going to be a times dot name and then like i said since we're going to sort it so i'll just do a sorted here like based on that based on the times here okay and then for the sliding windows i'm going to use a q here to uh to keep track of our current uh the punch times inside the current hours so uh i'm gonna use the dq right since we will be uh popping from the tail later on so now and we have for each time in the sorted time list now right and we first we add this thing right so for the sliding windows we add these things to the end of the queue here and then we'll try to pop all those uh invalid times so basically this is how we do while the time miners right the current time minus the last one in the queue is greater than what than the uh then 60. basically you know then 60 minutes remember since we have already converted everything into this into the minutes format so that's why we can simply check basically if the current time and the last element the difference is greater than 60 then we know okay so we can we need to pop that things we do we just do a pop left we do it until uh the last one is within the 60 range then we check basically if the length of the current queue right is equal greater than three then we know okay so this person needs to be alerted which means we need to add this person to the uh to our final answers okay and we can simply break the four loop here because we there's no need to continue for the current person okay so yeah and that's i think that's it and in the end we simply return a sorted version of the answer here since we need to sort it in the alphabetically way right so let's do a sorted answer cool i'm going to run this code so we have daniel here and let me try to submit it yeah cool so it's accepted i mean cool and oh yeah and how about time and space complexity right so for the time complexity we have like n here so we have a o n here right that's o n and then we have uh that's this is like the number of the different persons here right so it doesn't do we have how many persons do we have here um yeah oh and here for each of the persons will be sort basically will sort the uh the times for each of its person i think the worst case scenario is the uh if everything is for the same person right basically we're gonna have like one name here and then we'll sort this thing so here the worst case scenario is that we're gonna have like a unlock n here right and log n and then this is like a for loop here right this is the n log n plus n here yeah because here we are only each of the time will only be added once here so and then we have a in the end we have uh sorted here okay so basically the worst case scenario for this one the time complexity is unlocked and yeah in the case every all the other times are for the same persons that's why the worst case is we're going to sort all the times for this person which is unlocked okay and space complexity i think space we have times here right it's over the times yeah so for the time for the sorry for the space complexities it's often so this is the time here and space is o of n basically we'll be storing each number each time inside our times dictionary that's the o of n here yeah cool i think that's it for this problem yeah okay thank you so much for watching this video guys stay tuned see you guys soon bye
Alert Using Same Key-Card Three or More Times in a One Hour Period
least-number-of-unique-integers-after-k-removals
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `keyName` and `keyTime` where `[keyName[i], keyTime[i]]` corresponds to a person's name and the time when their key-card was used **in a** **single day**. Access times are given in the **24-hour time format "HH:MM "**, such as `"23:51 "` and `"09:49 "`. Return a _list of unique worker names who received an alert for frequent keycard use_. Sort the names in **ascending order alphabetically**. Notice that `"10:00 "` - `"11:00 "` is considered to be within a one-hour period, while `"22:51 "` - `"23:52 "` is not considered to be within a one-hour period. **Example 1:** **Input:** keyName = \[ "daniel ", "daniel ", "daniel ", "luis ", "luis ", "luis ", "luis "\], keyTime = \[ "10:00 ", "10:40 ", "11:00 ", "09:00 ", "11:00 ", "13:00 ", "15:00 "\] **Output:** \[ "daniel "\] **Explanation:** "daniel " used the keycard 3 times in a one-hour period ( "10:00 ", "10:40 ", "11:00 "). **Example 2:** **Input:** keyName = \[ "alice ", "alice ", "alice ", "bob ", "bob ", "bob ", "bob "\], keyTime = \[ "12:01 ", "12:00 ", "18:00 ", "21:00 ", "21:20 ", "21:30 ", "23:00 "\] **Output:** \[ "bob "\] **Explanation:** "bob " used the keycard 3 times in a one-hour period ( "21:00 ", "21:20 ", "21:30 "). **Constraints:** * `1 <= keyName.length, keyTime.length <= 105` * `keyName.length == keyTime.length` * `keyTime[i]` is in the format **"HH:MM "**. * `[keyName[i], keyTime[i]]` is **unique**. * `1 <= keyName[i].length <= 10` * `keyName[i] contains only lowercase English letters.`
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Array,Hash Table,Greedy,Sorting,Counting
Medium
null
63
question so this one's about graph apparently let's read it a robot is located at the top left corner of a and by n grid okay the robot can only move at the down right at any point in time the robot is trying to reach the bottom right corner of the grid okay now um consider some obstacles are added to the grid how many unique paths would there be okay obstacle and space zero one so yes do some something like this zero zero one zero um i'm trying to start from here and um bottom right is the end point okay we're starting from s to e so one is obstacles right and we're asking how many unique paths would it be so yeah definitely we can do so we're counting the path so um a search based algorithm we can do for example dfs or bfs we think about d of x how is a dfs gonna work here um there's a two path apparently here so changes to zero would be like one path two paths three paths i can only go at the down right so it would be 1 one two three four path so the way i'm gonna approach this would be like how many yeah so bfs dfs the problem is that um a crew spend it could be something like exponential okay so the second solution be account with dynamic programming so it's quite um straightforward to know that um the number of path number path arriving at i j will be the number of path 5 plus 1 j and add them pathways i j plus one it's like this one path going here if you are at this position you can choose like let me give a draw for example if you have one path here you have multiple paths here you don't actually have to re-run the path again re-run the path again re-run the path again right you don't have to do it again for those two you just have to add the number here so that's the secret of dp um we can actually do it in search can we um let's see no we cannot um i think if we can do bfs because that first search i just run two days straightly but with bfs i think yeah potentially you can do that because you're going one run on another round right there's obstacles here can you arrives here directly because there's no other way to go around to be at the same location again right because we're just going down right so you can potentially do that so it'll be in a m i think you can do that so we're doing dp it's already in an m space is essentially the same can we optimize the space well between the last line and this lens second so we're always updating note from this and this let me think can we get rid of it um yeah i think supposing i can with the order right i can do it or i can just do like a rolling basis so the space will just be of m you can do it backwards just do like right and if you care so much you can even do mango phone and ham okay yeah so let's go so we're using namespace for some classity and now define a solver for this question and there's just one function that is get number and we return into the graph can be represented as a 2d array that is graph yeah and start it from the top left so do some initialization um n will be lines graph the size m is graph 0. let's assume it's a valley graph okay and we have my number vector um number vector would be like m right so let's just do the rolling basis this would be two and a vector of m that initially just have zero and um yeah and the number zero one okay calculate this so the way we're doing it is using two loops so we now have the obstacle so if graph i j is some kind of obstacle right is one then we don't do it house we're doing this so because we're doing rolling one technique would be doing zero and once so we add one instead of minus one okay so we're just doing it all right yes after we've done it i just retain this um return number last line will be n minus one so m plus one mode two and the last line would be m minus one so let's be careful if it's zero we should return minus one there's no row to it or just doing this it'll be fine i'm adding my test case um it'll be something like this zero one now it's like zero also zero one zero and zero yeah so a big test case um just using a graph got a silver okay 75 58 okay 58 i miss one more two definitely right okay let's do 58 j will be my should be 2m right yeah it should be 2mm sorry four two three four i totally agree and we're doing imj zero this is zero minus one oh yeah sure so let's see if j is zero if j zero shouldn't do minus one right but i we're using rolling bases i don't need to care about it this number is zero we have zero way of getting it which is zero you should add this one so j is not zero i'm adding hmm maybe you try a different x 0 and 0. if it's one we continue or else so now doing the first row will be so we should not doing from the first row right now we should know from a better engineering way to do this is like just initialize the first row and first column right i think it's right way to go maybe two okay so about the example here we should do four yeah that's crap
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
91
this video we're going to take a look at a legal problem called the codeways so we're basically given a string with numbers like this and we want to find the total number of ways to encode this number so in this case we want to uh if we have a right if we have a one that match with a if i have a two that match with letter b if i have 26 that match with letter z right so in this case we're only working with from a to z right so in this case to decode and uncode a message all integers must be grouped then mapped back into letters using the reverse of the mapping above there might be multiple ways for example one zero six can be mapped into a j zed right one symbolize a just like this one right here ten symbolize j 6 symbolize f or what we can do is we can have 11 instead of 1 right we can either group them together or separate them so in this case 11 symbolize k so now note that the grouping 1 1106 is invalid because 0 6 cannot be mapped into f since 6 is a different from 0 6. so we cannot have in coming 0 right so in this case if i have incoming 0 that will not work and in this case if i given a string s containing only digits return the number of ways to code it the answer is guaranteed to fit in a 32-bit integer okay so here you can see 32-bit integer okay so here you can see 32-bit integer okay so here you can see we have a couple examples here so one of them is 12 right if i have only 12 i can i have two ways one is i can have uh just a right so a and b like this or we can have l right which basically 12 right and we also have 2 and 6. so we can break 226 down into either 2 26 or we can do 22 and 6 right so in this case we have v bz or f uh vf right and if we have 0 in this case because we are going to go from 1 to 26 right go from 1 to 26 so this is the limit this is the range if i have numbers that are outside like less than 1 right if i have values that are less than one or bigger than 26 this will simply not work right so and you can see we also have another example if i have incoming zeros if i have upcoming zero right so pretty much if i have 0 6 that's not going to work and same thing if i have like 60 just like i mentioned if it's something that's bigger than 26 it's not gonna work so we pretty much have those edge cases if i have like zero or negative values right if i have um x right the current integer value is actually less than 1 or if i have a value that's if i have value that's bigger than 26 right then that's not gonna work either um if i have a string that's uh has incoming zero like this it's also not going to work so we have those cases here right so we have those uh things that we have to watch out for let's say we have an example of nine zero nine how many ways can we decode this in this case we can't because if we were to break down like this where we have nine zero nine this has an incoming zero this will not work right so if this is not going to work but this works then this will give us a false answer we cannot encode this if i have nine zero nine and i want to group those two together right and this one by itself then we this will also not work because 90 is actually bigger than right is actually bigger than 26 so this will not work so in this case total number of ways to code this is gonna be zero if i have one zero nine and i can either decode this way where i can uh ten nine right so that's this is the only way right because we can't really have one zero nine here and we can't really have one zero nine because one zero nine is actually bigger than uh 26 and zero nine it has the incoming zero so that's not going to work okay so now let's take a look at how we can solve this problem so to solve this problem first i'm going to talk about how we can do this using a brute force and then we're going to talk about how we can use a top down approach as well as the bottom approach so in this case you can see here let's say we have two one two five right in this case how many ways can we break this down in this case how many total of decoder ways is going to be 2 in this case 2 12 and 5 right so that's one way right and the other way in this case is going to be 21 so 2 12 5. so the other way is 21 2 and 5. and the another way is we can be able to do two um or i should say 21 and 25 right that also work and we can also do um let's see we can also try to do two right one and two five right or we can do two one two five so you can see we have total of five ways of decoding this right so in this case these are five ways but how can we get those combinations in this case we can be able to do a um a depth first search right basically for each and every single elements that we have in our string we have two decisions one is we can take this item and add it onto our current uh subset or a current group right we group it doesn't matter if we group one character or two characters together because we can only maximum group two characters together if i have like for example one zero we cannot group them together because we know that if we have three characters it's always going to be bigger than 26 right 100 is always going to be bigger than 26. so the limit for the group per group the maximum characters we can have is gonna be two right and once we group those two uh characters together we can check to see if the current group right the current subset of the string is um is a valid string right the valid string basically means that if the string is actually uh within the range right within uh between 1 and 26 right uh less so less than or equal to right so in this case if it's actually between 26 and one right so that's what we're trying to do in this case you can see here we can draw the recursion tree out so let's say we have the string we can take the first character the first two characters as a group right once we've done that for this decision we can still make two decisions either we take the next character take the next two character and then same thing here i can take the next character or next two character and uh because we're done right we reach the end of the string then we know that there is a way so we can just return one because there is a way there is a path that uh that gave us a decode away and in this case we can continue down this path so five we can take the current uh the current character two character but in there in this case there is no next character left so we're just going to take the current character and you can see we have a path and this will also give us one right it will return one for this path because there is one decode away and same thing here if i were to take the first two character in this case it's going to be 12. we know this is a valid uh string and it's between um one and 26 so that's good right and there's no incoming zero so we can just move on to the next option five that's two character right in this case we don't have any characters left so we're gonna take the first character which is five and same thing down to this past wall so we have 25 in this case we can take two uh the first character or end the first two characters right in this case they both work right so we have 21 2 and 5 just like i mentioned that's one combination and we can also have 21 25 and that's the that's another combination so both combinations work both path works so in this case we're getting total of five right so one two three four five if you draw the recursion tree out it's really clear right so you can see here for each decision we have uh for each stack recursion stack we have two decisions we take the current item uh the current first item take the uh the current the first two items right and then from there we can still continue to make uh its two decisions and you can see that for each recurring stack we have to make two decisions and that will give us a time complexity of big o of 2 to the power of n which is basically exponential where n is number of items that we have in our string so you can see here that way works right and then let's say we have another example where we have a zero right so we have one two zero and the same thing if i have a situation where we get to a point where we have a zero right in this case if i have a just zero itself this will not work but if i group to another character or another uh number with a zero that's non-zero uh number with a zero that's non-zero uh number with a zero that's non-zero this will actually give us a path right so you can see we take the first character or if they take the two first two characters right and then we decide to see if we should take the next character or end next two characters right at the end when we backtrack to here when we're coming back right we will get the sum for total numbers of ways uh for both paths right maybe there's a path that give us zero maybe there's one path that give us uh different values we get the sum and then we're going to return back to its parent stack and then its parent stack will just calculate the total of dakota waste from its parent from this its children recursion stacks right so you can see here at the end we're getting one two three and basically there are three ways right because you can have 12 120 uh 1 21 20 1 2 1 20 right because you cannot have one two zero uh you can also you cannot have one two twelve because you have a zero left right so those are the ways right and uh you can see we also if we have a zero we want to make sure we filter that out right and in this case if i have a different value like this one for what uh five one so same thing here if i can uh there are two ways right we can have fourteen five one four five one those are the four ways uh sorry two ways right so in this case it shows here i can take one character first character and i can take this uh the first two characters so if i take the first one character i have one four five one take the next the first two characters we have uh 14 5 1 right so in this case we continue right in this case we can take the next character or and the next two characters won't work because 51 is bigger than 26 and then 5 1 in this case is actually between this range so we continue and then one is also between this range so this is a one path so 14 5 1 right so you get an idea this is one path and this is one path so at the end we get a total of two path right so now you know how we can do this in a brute force approach right and this will give us a time complexity of big o of 2 to the power n so how can we optimize this and use a top-down approach top-down approach top-down approach so to do this using a top-down approach so to do this using a top-down approach so to do this using a top-down approach and basically what we're going to do is we're going to memoize this right you can see here if i have um you can see here if i have this step right here it's the same answer for this recursion stack right you can see here if i have just um if i have just one two zero right if the string is one two zero or i should say if the current position is the third character in the string then in this case we're going to have the same answer right we're going to have same decoder ways you can see here for this stack we have for this recursion stack we have only one decode away and for this recursion stack we have only one decoded way returned back to the current stack right so in this case we can be able to cache this result in a uh in an integer array so that we can be able to return the pre-computed result if we are return the pre-computed result if we are return the pre-computed result if we are at that current position so this is what i did here so i basically have a class called solution basically a function right in this case takes a string and then we're going to have an array uh convert the string to a character array and we also have a cache array which is the size of the array.life or the is the size of the array.life or the is the size of the array.life or the size of the string and then we're going to have a helper method we're starting from the index zero the first character that we are that we're on in the string and then what we're going to do is we're going to have our base case if we successfully traverse the entire string and for each and every single step we know that um the current string is valid is a valid decoder way or the code of string then we can continue traverse until we get to a point where the current step the current index is the last character right then we can just return or sorry successfully traverse all the characters then we can just return one because we found one decode way and if we have a situation where we uh have a index right which was com pre-computed before then we can return pre-computed before then we can return pre-computed before then we can return the pre-computed result the pre-computed result the pre-computed result then we're going to have total dakota ways this is basically total decoder ways to iterate so in this case we're starting from index and we have two statements here so while i is less than array.length right we want is less than array.length right we want is less than array.length right we want to make sure that we didn't go out of bound and we also want to make sure we only going to uh two decisions right and notice that we have a strain builder here basically for each iteration we append the current item onto the stream builder so first iteration we have one character we check to see if the current string is actually a decode way or sorry decoded is actually a decoded valid decoded string if that's the case we're going to traverse down this path right if we only take one character and then for next iteration we're going to add the next character onto the string builder we'll check to see if the current string is actually a correct decoded strain and then if it is we're just going to um uh traverse down that path as well if we take the first two characters right so how many decoder weights do we have and then at the end after the loop you can see here we're going to cash the results of total decodeaways for the current position onto the cash and then at the end we're going to return the total decoder weighs and this will give us a time complexity of big o of n where n is number of characters that we have in a string so now this is our top down approach and let's take a look at how we can solve this problem using a dynamic programming approach or in this case a bottom-up approach so or in this case a bottom-up approach so or in this case a bottom-up approach so to solve this using a bottom-up approach to solve this using a bottom-up approach to solve this using a bottom-up approach what we notice here is that if we were to use this 2d oh sorry just one directional cache array you can see here uh when we have five right in this case five have one decode away right so this five element right here has only one decode away and if we have 25 you can see here we have one two decoder ways if i have one two five in this case one two five we have one two three we have three decode ways and if i have two one two five how many decoder ways do we have five right one two three four five of them do you see the pattern if you don't let me show you another example so if i have this string right here right zero how many path how many decoder way do we have in this case if we only have zero we have no path if i have 20 how many decoder way do i have okay let's see 20 is right here there's only one decode away how about there's only one right how about um 120 how much decoder way do we have 120 one only one path okay so we only have one what about 2120 how many decode away do we have one we have two okay how about one th how about including the one in this case we have one two three right in this case we have three right we have total of three decoder ways for this entire string do you see the pattern if you don't let me show you another example then if i have this right if i only have one how many dakota weights do we have in this case i have one how about 51 you can see i only have one decode away okay cool how about 451 in this case for 451 i have one uh yeah one dakota way right in this case i only have one decode away and how about one uh how about including the one in this case i have one two total of two decoded ways do you still not see the pattern if you don't see the pattern let me tell you right now the pattern is that we're going to work backwards and you can see that if i were to go from bottom up approach right because what we're doing drawing the recursion trait we're going from the top to bottom and now we're going uh from bottom to top then you can see that for this element right here because let's say we were to start from here you can see this has zero decoder ways if i have zero decoderweights here then in this case the next item is going to um have a value that's based on the current dakota number of dakota ways that the current item have right you can see here um for this value right here 20 is going to be one right we know one decode away and that's kind of obvious we can get it right we check to see if this is a dakota decoded string if it is then that's then we have one but what about 120 in this case you can see this result this data right here this value right here is actually based on the previous two values right because you can see here 120 this zero right here is this path it has zero and this 20 right here has this path right here and that has one uh dakota way right so for 120 is basically a sum for all this for all those decisions uh that we're making right the total the code awaits for all the decisions that we're making so it's actually going to be the previous two because we're only making two decisions it's going to be this the total decoder ways for the previous two computed values okay so now we know that so in this case this one right here right is actually got from one plus zero from the previous two data okay so now we know this what about the two it's the same thing it's actually gone from the previous two data so you can see here we have two ones right so you can see we have two ones here one and one plus one is two what about this three one plus two is three right so you can see here the curve uh the data that we want to compute is actually based on the previous two data if we don't have previous two data we can just get check to see if this current string is actually the correct decoder string right we just basically get the data if we don't have it right this we check to see if this is a decoder string in this case 0 is not we have 0. 20. in this case 20 is a dakota string so we can put 1 there right so in this case what about 25 right it's the same thing so in this case one because this is the code away the coded string and two in this case you can see because this 25 is one combination and we can also have two five so that's two combinations so that's the number of decoder ways for this up to here for up to this current position right so we have two and five a two and one right uh and what we can do is that we can be able to calculate this based on the uh the previous value if this is a um decoder string or decoded uh valid decoder string we want to check to see if the previous character is also the code of string if it is then i one plus one right and then for the next one in this case one two five is going to be computed based on the previous two results so one plus two is three five is going to be two plus three is five right same thing here you can see that one is a valid decoder string so we have one here right one valid uh decoder way and uh for five in this case five can only be one because five can be uh a just one right in this case we can just have five alone right and that will be a valid the code string so we have 51 that's not gonna work so we have one there so the idea is that if we group them together and this is not a decoded valid decoded string then we can just inherit it from the previous computer values because it's just going to be one right and for 4 in this case 4 5 is actually bigger than 26 so we're just going to inherit it from the previous computer value which is 1 in this case is actually 14 i should say because one group was 14 is actually a valid decoder string so we're just going to use the pre uh previous computer value in this case one plus one which gave us two okay so this is pretty much how we solve this problem and you can see the time complexity is still the same big o of n right but we're on the right path to optimize this but space complexity is also going to be big o of n right because we're using a one directional array to store the pre computer results so in this case if i have this dakota decode away and this is our this is my submitted code you can see that basically i have a character array a string to character array then i have an integer uh cache array by default it's going to be all zeros in inside the array and then we're just going to because we're going from back to the front right so we're going to go from n minus one which is the last position in the array all the way to the first item that we have in the array and then first we check to see if this if there is if the current item is zero right if it is we can just continue because like i said earlier uh when we declare this array initially all elements will be zero okay so in this case we can just continue right so then we check to see if the current index is actually the last item right last item in the or in the uh in the array because we know if this is if the current position is not a zero right then this cr the last character the last element must be something between one to nine so we know that the current item should have a one decode away okay so we compute that value and save it on the cache then we continue and if we have a situation where i is actually less than n minus one then we do the following we check the c we get the string substring from i to i plus two right so this will give us the uh the precomputed value right the string for two elements in the string right uh two numbers in a string right so we check to see if this is a valid decoded string and first we check we convert it into an integer we check to see if it's bigger than 26 if it is we're just going to inherit it from the previous computer value just like i talked about if we have a situation where it's actually we don't have the um the previous two computer value right if we're on n minus two which is the last second element then we're just going to get uh cash at i is equal to cash i plus one right so in this case we're just going to plus one because we know at this current position it's not a is a it's actually a valid decoder string right um and then what we're going to do is we're going to check to see right if this current index is actually less than n minus 2 and bigger than or equal to 0 if it is we're going to compute the previous uh we're going to compute this current value based on the previous two values so cash at i plus one plus cash at item plus two at the end we're just going to return cash as zero which will give us the first items that we have in our cash right so we're working backwards from the last item all the way to the first item so this will give us the time complexity big of n space complexity is also big of n but how can we optimize this one way we can do this is we can because all we need here is we need the previous two computed values so what we can do is we can have a current variable as well as a previous variable right and this will basically keep track of the current and the previous element and then based on those two values we can compute the current uh current value or i should say not current but like previous the first previous item or previous one and previous two the second previous item and then based on those two previous items we can compute the current items value at the end we're just going to keep the uh the space complexity to be big o of n oh sorry big o of one right so this will improve the space complexity to big o of one and this is how we saw this lee co decoder ways in dynamic programming approach
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
345
all right this question is called reverse vowels of a string it says write a function it takes a string as input and reverse only the bowels of the string so for example 1 the input is hello and the output is hol L e because the e and the O are flipped and for the second example you have the word leet code and the output is le OTC e de because every vowel is flipped note the vowels do not include the letter Y alright so the key to solving this problem is to use two different pointers at once and by pointer I don't mean real pointers that can C++ I just mean pointers that can C++ I just mean pointers that can C++ I just mean references to two different elements at once so what we do is we start one pointer all the way to the left of the string and the other pointer all the way to the right and what we're gonna do is we're going to move the pointers inwards until they land on a vowel and when they land on a vowel then we swap them I'll show you what I mean so right now we start off on the letters H and O is H a vowel and we can check the valves down here is H a vowel no so then we just move it one letter to the right now we go over to the second pointer is that on a vowel yes it is so we don't have to move that one to the left so now that we're on two different vowels we just swapped them whatever is in pointer one gets which the pointer to and vice versa so now we do it again but we have to ensure that the pointer is never cross so we'll move this pointer one to the right one is this a vowel no and finally try to move it one more and now they're on the same element so we're done one thing to note is that strings are immutable in JavaScript so we're not actually doing this with a string the first step we're going to have to do is we're gonna have to make our string and let me just put this back to the original string we'll have to make it an array then we swap the variables like I did before and then at the very end we just convert that array back to a string all right time to get to the code what leet code has given us is a function called reverse Val's that accepts the parameter s and s is just the string of characters remember I mentioned that in JavaScript strings are immutable so the first thing we have to do is convert our string to an array so we'll say let string R equals s dot split empty string so that will convert leet code to an array okay now we need our two pointers we'll say let pointer one equal zero so that'll put us here and let pointer two equals string array dot length minus one so that'll put us here all right so the first thing we have to do is we need to have a while loop that moves our pointers and we have to make sure that our pointer is never overlapped so while pointer 1 is less than pointer 2 then we can do some stuff but what do we actually need to do we need to move our pointers inwards until each one of them hits a vowel so for the left pointer we need to have its own while loop that makes sure the pointers don't overlap and will say if the letter were on is not a vowel you remember this is pointer one we're talking about what do we need to keep moving it to the right and when it's finally on a vowel will go into this L statement you'll just break so far that will look like this are we on a vowel for pointer one no because it's on the letter L so we move it over to the right one are we on a vowel now yes so now we break we need to do the same thing for pointer too so we'll keep moving it until it's on a vowel so we'll say while pointer 1 is less than pointer to if pointer to isn't pointing to a vowel then we'll just decrement it so move it to the left until it is and when it finally is will go into this L statement we'll break out of the loop what that'll look like in the drawing to the left is it'll check whether pointer 2 is on a vowel is it yes because it's on the letter E so that will break so now that both pointers are on Valve's what do we need to do we just need to switch the valves we'll do that using a typical swapping mechanism so we'll save whatever's in pointer 1 to a variable called temp then we'll replace whatever's in pointer 1 with the vowel in pointer to alright so now that we've replaced whatever is in pointer 1 we need to replace whatever is in pointer two with whatever was in pointer one before remember we saved that in a variable called temp so now if you look to the left in this example both are on the letter e but when you swap them just picture them being swapped if they're on different letters it would be more obvious that we're swapping the variables alright so now the last thing we have to do is we just have to move winter 1 up 1 and pointer two down 1 all right so that would look like this alright so now we get to the next loop is pointer one less than pointer to yes so now we go into the inner loops is pointer 1 on a vowel yes it is so we go into the second while loop is pointer to on a vowel no it's not it's on the letter D so we just move that over 1 now is it on a vowel yes so we break next step is we swap the two variables so he becomes o and o becomes e then we increment our left pointer decrement our left pointer now we start the outer while loop again is pointer 1 less than pointer to yes is the letter at that pointer 1 is on is that a vowel no it's not so we move it to the right but now notice that the pointers have overlapped so we just stop here and if we take a step back we'll notice that we've swapped all the vowels in our original string all right so remember that strings are immutable in JavaScript so we had to convert that to an array now we'll have to convert it back to a string so it will become L e Oh d-ii the way we do that is by using join d-ii the way we do that is by using join d-ii the way we do that is by using join so return string array dot join all right so now all there's left to do is to implement our is bowel function remember all that does is checks whether the letter we're on is a vowel so is Val equals a function will pass a character into will have a variable that just holds all of our vowels and lowercase then we'll just check whether the letter were on is one of those valves so does AEIOU include the string that we're on and just note that we're making whatever string we're on a lower case because they might pass in an uppercase vowel and to compare to our vowels in line 39 we just have to first make it lowercase so the comparison makes sense alright so we've now implemented that and we've implemented the whole solution so let's run the code looks good let's submit it alright so our solution was faster than about 76% of other JavaScript about 76% of other JavaScript about 76% of other JavaScript submissions as usual at the code and written explanation are linked down below if you like the video just hit the like button and subscribe to the channel it really helps me out see you next time
Reverse Vowels of a String
reverse-vowels-of-a-string
Given a string `s`, reverse only all the vowels in the string and return it. The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. **Example 1:** **Input:** s = "hello" **Output:** "holle" **Example 2:** **Input:** s = "leetcode" **Output:** "leotcede" **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consist of **printable ASCII** characters.
null
Two Pointers,String
Easy
344,1089
1,473
hello everyone welcome to coding decoded my name is sanchez deja i am working as technical architect sd4 at adobe and here i present the 8th of july liquid problem the question that we have in today is house paint three this question is a hard level question on lead code however i don't feel the same and i'm pretty sure that subscribers of coding decoded would feel in the same way why i am saying this because this question is based on the concept of 3d dynamic programming and we have already solved plenty of questions on the lines of 3d db if you go and check out the coding decoded sd preparation sheet based on the concept of dynamic programming then you will find a question named cherrypricker2 and i have marked this question with double asterisk sign that means it's highly important from interviews perspective in case you would have done this question before this question would have been a cakewalk for you so i would request you guys to kindly go through this video first and then come back to this one and i'm pretty sure that 90 percent of you would be able to solve today's question by themselves for those who are not aware of this cherry picker problem too let me just help you out so without further ado let's quickly walk through the presentation where i'll be talking about the algorithm to go about it in a step-by-step manner it in a step-by-step manner it in a step-by-step manner paint house 3 lead code 1473 also in case if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to drop a message on the telegram group or the discord server of coding decoded both the links are stated below now let's shoot for understanding the definition of the question which is find the neighborhood for the below array and i have taken a sub problem of out of the question and if it is given to you then what would be the answer for this how do you define a neighborhood the number of consecutive groups that are getting formed so here we have a group wherein the house is painted with color one the next group is painted with color two the next group is painted with color three next paint group is painted with color two and the next group is painted with color one so in total how many groups are formed one two three four five so as per this array configuration the house is the neighborhood would come out to be as five units now let's go and iterate over the question in the question you are given various houses wherein few of them are not painted what you are also told the number of colors that you have it will range from 1 till n that means you can color all the non-painted houses you can color all the non-painted houses you can color all the non-painted houses with any color of your choice starting from color one to color n you're also given the cost to color the ith house with color j so j can vary from one till n and i can vary from the number of houses that you have so this information is also given to you in the form of an array also the question specifies that after coloring all the houses the total number of groups that should be formed should be equal to t that means for this array configuration t neighborhood should be the value now let's get back to the same example here the house's configuration that is given to us is 0 two one two zero represents that the house is not painted to represent the house is painted in blue color one represents that the house is painted in orange color so one way to think about the algorithm is to try out all possibilities and what we are going gonna do we'll paint the first house with all possibilities starting from the color one up till color n and we will keep on iterating ahead in this entire array with each iteration let's see how can we keep track of the target value that we have the target neighborhood value that we have so let's hypothetically assume that we first paint this house with color orange so do i have orange color no i don't have orange color over here so let's assume that orange is same as red so that means i have painted this house with red color as a result of which i have created one uh one group since i have created one group the target group that i have been looking for the rest of the elements gets reduced to t minus one that means one group has been formed in red color and the number of groups that should be formed for the remaining elements should be equal to t minus one and what we are going to do will recursively iterate over the same algorithm one by one so let's proceed ahead the next house that we see happens to be blue in color since it's blue in color what we should be checking what was the previous value of the house the previous color of the house was red since both of them are different that means they will form two separate groups had it been the case that we have painted the first house with blue color this particular house which has already been painted would have lied in the same group let's run understand both these cases in detail so we painted the first house with red color and since we painted this house with red color we have created the first group which is of color red and let's represent it with one the number of groups that are to be formed for the remaining houses that we have which in this case is one two three four so for the rest of the houses fourth houses the number of groups that are to be formed should be equal to t minus one and again there could have been two cases the immediate next house would have been the same color which is not in this case the immediate next house happens to be in blue color so this house is in blue color as a result of which we can say that these two houses can't be clubbed together as a result of it we have definite that this house would contribute to a new group as a result of which we can say that a new group will be formed over here at this particular position and the value of t gets reduced by one further as a result of this we can say that for the rest of the houses that we have starting from the second index till the end one two three rest of the three houses that we have the number of groups or neighborhoods that are to be formed should be equal to t minus two so this is the first possible case and if you carefully see that we need at each index what is the color of the previous house so that we can make the decision whether the current house can be clubbed with the previous one or not here in this case the house was already painted in blue color and the previous house was painted in red color as a result of its two groups are mandatory to be formed had it been the case the first house was painted in blue color something like this we would have created the first group and the group count here was one the number of groups that had to be formed across the remaining elements would have been t minus one and the number of houses that we had would have been four and let's iterate over to the next house was already also in blue color and we would have percolated this information from the previous hour that the color of the previous house was blue the color of the current house is again blue as a result of it these two houses became part of the same group the t value remains the same it gives us more leverage that more groups can be formed across the remaining elements which is this one so the number of remaining houses that we have happens to be three and across these three houses at max t minus one groups can be formed so this is the crux of the problem if you have understood this much you have understood ninety percent of the algorithm as per the question we have to iterate over all possibilities for each house starting from color 1 up till color n and we will be doing this using recursion and since recursions are expensive in order to optimize the time complexity the first rule of dynamic programming is to identify overlapping solutions as a result of which we will be using memoization technique what i am trying to say let's quickly walk through the coding section and have a look at the algorithm the first thing that i have done here is to create my dpra this dpr has three indexes to it the first index represents the house id the next index represents the number of groups that are to be formed for the remaining elements that we have followed by the color of the last house that was painted so it has three indexes m target and n and the problem crux lies in writing this dfs method appropriately in case this dfs method returns the max value that min means this configuration that the question is looking out for with this particular target value is not possible we have to return -1 in those possible we have to return -1 in those possible we have to return -1 in those cases otherwise the value is something other than max that means such configuration is possible and we have to return that particular value so let's walk through the dfs method and let's talk about various parameters that are passed through this dfs method so the first one is houses pretty simple and straightforward cost followed by index so this represents the current index that is to be painted followed by the total number of groups that are to be formed for the remaining elements uh followed by the color in which the last house was painted followed by the number of colors available so in case the target goes less than zero that means uh the target value that we are looking out for is less than zero for the elements that we are to be painted it simply means the configuration is not possible this is the first abortion condition and we have to return minus max value in those cases otherwise what do we check if my i value the index that i am currently painting targeting to be painting it happens to be greater than or equal to houses.length what do we check if houses.length what do we check if houses.length what do we check if target happens to be equal to zero that means there are we have reached the end of the uh house array that we have and there are no more groups that are to be formed that's a happy case that means we have found out one possibility of answers if that is the case we simply return 0 from there otherwise we return max because such a configuration won't be possible let's proceed ahead we this is a very simple case we check whether we have pre-computed dp of i target and last pre-computed dp of i target and last pre-computed dp of i target and last color if it is already computed we simply reuse it up let's proceed ahead we check if my current house is painted or not painted in case it is painted that means house at the ith index is not equal to zero that means the house was painted last year we checked whether my last color that was being passed in the question is not equal to the current house color if that is the case both of them are not equal as a result of which we'll have to reduce the target count by one had it been the case both of them were equal the target count would have remains the same so we reduce the target count depending upon this particular if condition and we invoke the dfs helper method and carefully look at it because the first parameter houses remains the same cost remains the same we increment to the next index in the array the target value remains the same or it gets reduced by one depending upon this particular condition we pass in houses and the value n again really simple let's proceed ahead next we have created an ans variable initialize it to max what do we do for each house that was that this set that is still not colored because line 29 was not met that means the current house is not colored we check out for all possibilities of colors that we have starting from color 1 up till color n with each iteration we are incrementing the color value what do we identify the value that is minimum of all the possibilities so let's try and understand this particular equation so this represents the cost of coloring the ith house with this particular color we added to the cost that comes from the dfs helper method for coloring the remaining houses so let's walk through this so the first parameter is house the next parameter is cost and since we have already included the cost for coloring this particular index with this particular color we increment to the next index i plus 1 and the interesting part lies over here so what we are doing we are checking whether the last color happens to be not equal to the current color since both of them are not equal that means we are creating two different groups as a result of which we have to reduce the target count so whenever both of them are not equal we will reduce the target count by one in case they turn out to be equal the target count remains as it is so this is an interesting statement that i have written and the next parameters are color followed by n so this will become the next color the last color for the subsequent operations in the recursion tree and once we are out of this loop we have identified the minimum answer that comes and we assign it to dp of i target and last color and we simply return that up so let's try and submitting this accepted 70 faster it's pretty good with this let's wrap up today's session i hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel i'll be adding this question since it's a very interesting question based on the concept of 3d db to coding decoded sd preparation sheet and i'm attaching this link as well in the description so if you are interested in revising the entire annual grammy series then this sheet is for you and i'm pretty sure once you will go through the sheet dynamic programming will be on your tips thank you take care
Paint House III
find-the-longest-substring-containing-vowels-in-even-counts
There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. * For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`. Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where: * `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet. * `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`. Return _the minimum cost of painting all the remaining houses in such a way that there are exactly_ `target` _neighborhoods_. If it is not possible, return `-1`. **Example 1:** **Input:** houses = \[0,0,0,0,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3 **Output:** 9 **Explanation:** Paint houses of this way \[1,2,2,1,1\] This array contains target = 3 neighborhoods, \[{1}, {2,2}, {1,1}\]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. **Example 2:** **Input:** houses = \[0,2,1,2,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3 **Output:** 11 **Explanation:** Some houses are already painted, Paint the houses of this way \[2,2,1,2,2\] This array contains target = 3 neighborhoods, \[{2,2}, {1}, {2,2}\]. Cost of paint the first and last house (10 + 1) = 11. **Example 3:** **Input:** houses = \[3,1,2,3\], cost = \[\[1,1,1\],\[1,1,1\],\[1,1,1\],\[1,1,1\]\], m = 4, n = 3, target = 3 **Output:** -1 **Explanation:** Houses are already painted with a total of 4 neighborhoods \[{3},{1},{2},{3}\] different of target = 3. **Constraints:** * `m == houses.length == cost.length` * `n == cost[i].length` * `1 <= m <= 100` * `1 <= n <= 20` * `1 <= target <= m` * `0 <= houses[i] <= n` * `1 <= cost[i][j] <= 104`
Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
null
1,706
So and the question is where will the ball fall so like we got a grade here so like here we have a grade so here this ball is zero ball you are so this is telling if this ball zero if this grid If we drop it, from which place will it come out and from which column will it come out? What does it mean? Like if we drop the ball zero here, then there is a grade here, we have this whole grade, so there is something like a slope in it. So if when the ball drops, if it has a slope in the S direction, then how will the ball perform, it will start falling in this direction. Okay, and then in this grade again there is a slope like thing, then our ball. It will fall from here and start following here. Okay, so our slope in this grade is kept in this direction, so when we keep it in this direction, our ball will fall from here to here, then we will get it again, so on this If it remains till the ball, then our ball will fall here in this direction, then there is a slope placed here, then when the valve hits here, it will come out from here like this, so what he is asking is that if the ball is zero, if we drop it from here. So from which column will it come out like the ball zero dropped from here then from which column it will come out from the column van Okay so now in the question slope would not have been kept then something would have been kept there so what does it mean so like Here, if the ball zero is dropping from here, it means that if the van is placed here then it has to be moved in the right direction. Okay, so when the ball zero is dropped here, then from where did it move in this direction? Then it has to be moved in the right direction. Then if you get the van, then it will drop forward, so now this negative means the ball is falling, that is, backward, so when the mines van is placed here, it means that this ball is falling in this direction. What we have to do is that once we get the van again, it will start falling in this direction, then what will he get here? If we get -1, then as soon as we then what will he get here? If we get -1, then as soon as we then what will he get here? If we get -1, then as soon as we get the mines van, then our ball will drop from here, then our ball will come out of this column, so we have to return the same. Okay, it will fall here, then we will get 1 here, if it is in this direction, then that ball will follow us, it will fall somewhere here, which means it will be going like this while falling from here, but here, the mines van is placed here itself, so it means the ball. As if there was a drop from here, it was going to fall further, so here it got another slope, it got that -1, so if there is any such slope, there will be some got that -1, so if there is any such slope, there will be some got that -1, so if there is any such slope, there will be some such slope in the C shop, then this ball will get stuck here, it will be below. If you speak honestly then how does it fall, it falls here, then from here it falls on this, falls here, then it falls here, then from here it falls on this, then it goes down like this, but now the slope has been placed here, so it says, it will come from here, it will fall here, then it will fall here. Like this, it will remain here, eating the tappa, it will remain somewhere in the middle, like B2 ball falls on it, then it will eat the box like this to go down here, then it will stop here, doing like this, now like here. But anyway, in a grade like Van Mines Van, the grade is made like this is our grade, okay, if you get a van, then you have to move it towards the right. If you get a mines van, then it means that you have to move this negative factor of. He has to go backwards, so now what do we have to return in the last, like if we have to return one, then what size will it be, our area will be of the same size as our ball, because every ball has to tell which one it is. If it is coming out of which column then b zero which column is coming out of van column b1 which column is it coming out of any column it means we have to return minus van if it is coming out of any column If it does n't come out from A then we have to return Mines van B2 also not from any column Mines van B Three also not from any column Mines van B four B will not come out from any column B4 will keep going like this A will go here that too the ball will get stuck somewhere So that also mines van, so as many balls as there are balls, that much size will be ours, to return that much, first of all we make what we have to return, what size is ours, this will be made as much as the balls, that means as many columns as that many columns. If the ball is being dropped, the number of dots will be formed in the column, then this becomes ours in which our answer will be returned, so first of all from how many balls, for the number of balls there are the number of balls here, then we will do some operation for that. For this, we will put the follow loop, how many balls do we have, how many balls will we have, if we put the ball zero then whatever is the position of the grade what will become of us whatever is the position of the grade what will become of us whatever is the position of the grade what will become of us If he is watching here then here What would you have read here, what will happen with this, but after two-three times, I will start understanding you, but after two-three times, I will start understanding you, but after two-three times, I will start understanding you, then stay tuned, so here, our van has gone in N position, so now, whatever the van position is, it has If we are storing we in the current ball position, then how much will our van a go to the causal position? Then when the value of i will be our increment, then how much will the value of i become our van? So i will be our van and current will be how much our ball. The position was done, so the van, so from the van, what will he see from the van, where will he look, so what is read here the van must have read because it is such a slope, so from here our van will come and how much was read by us in the current ball position. Van to van plus van kitna hoga 2 to n cos me tu ho hoga to current ball position hamara tu ho hoga now you will understand the value of i when now when hamara tu ho hoga to greet hamara 2 current ball position here But what would have been read here is -1, so when we here But what would have been read here is -1, so when we here But what would have been read here is -1, so when we do Minus Van plus current position, what will be the current ball position? From back, it means that he was moving forward in the column, when he got -1, then we will subtract it moving forward in the column, when he got -1, then we will subtract it moving forward in the column, when he got -1, then we will subtract it from Minus from the current ball position. So this means that now it has gone backwards like what happened here was you plus here what was read 2 + - 1 so this is our here what was read 2 + - 1 so this is our here what was read 2 + - 1 so this is our N nearby what will happen van A will go Okay now when I = Now our when our will be 3 now when I = Now our when our will be 3 now when I = Now our when our will be 3 Okay when our will be free So I our will be 3 here Current ball position How much will the van be So from 31 where will he see Where is the third row first column over here So, this will make van A, 1 + 1, how much will it be? If you 1 + 1, how much will it be? If you 1 + 1, how much will it be? If you become Tu again in N pass, then the current ball position becomes 2. This means that now go to the second column and look. Okay, so when our i increment will be row increment, then that will be. It will go till four, it is okay here, then what will it do after that, how much will it be? It has been read that there is a van lying here, if we go to the second column, then here we have -1. go to the second column, then here we have -1. go to the second column, then here we have -1. How much will the van come, then the van will come in the current position, okay, now our follow will end, so next time when we come, we will be in the current position. The value that will be stored is which column is it coming out of, so then we will store the same thing in our Oh, okay ours but our ball like now let's take our ball that if it is a here Let's take a mother here, A goes here, like if it has got a mines van here, it is starting from here, if it is going in the negative direction, then it means that it is not coming out of any column yet. He has come out of the row and has not even done the entire road journey. So it could be the case that if from here he is lying at -1 here too, that if from here he is lying at -1 here too, that if from here he is lying at -1 here too, then he will try to bolt from here to here, then he is out of some column. If he is not doing it, then we will have to handle both these cases. Okay, so now how do we handle this, which is our next position, which we have kept in the next position of the column, if it will come out of the column, okay and there is a van here, then only we can We are able to move forward, as we see in this case, here is my van, here is my -1, here is my van, here is my -1, here is my van, here is my -1, if both are not equal, then we are not able to do the movie further, then we will be able to move only if our current comes in it. Position is the current ball which is the position meaning like let's take the mother if we talk about here if it is van and look at the next ball position if it is the next position then in the next position yes if these two are not equal to each other like here each other If it is not equal to then what will happen to us like what will happen to us here that our current ball position is equal to you, we will make mines vane and we will store -1 only and break from here. we will store -1 only and break from here. we will store -1 only and break from here. Will do it is fine like if these two are not equal to each other then what will be the current ball position, our -1 what will be the current ball position, our -1 what will be the current ball position, our -1 and will break from here and then will break here and will store here what will be the current ball position. From here -1 will come, okay, that's it and what will we return in the last, if we return, then there will be some mistake here, this will be our grade, so all the three tests
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
1,042
hi everyone I'm Jack how are you doing today let's take a look at this problem 10:42 flower planting with no adjacent 10:42 flower planting with no adjacent 10:42 flower planting with no adjacent we have n gardens labeled 1 to n each garden you want to plant one of four types flowers so these paths XY describes the existence of a bi directional path from God and extract garden why also there is no gun that has more than three paths coming into or an imminent your task is to choose a flower type for each gun such that for any two gardens connected by a path they have different types flower mm-hmm return any such types flower mm-hmm return any such types flower mm-hmm return any such choices as an array answer where and Sarai is the type of flower the flower gotten denoted one two three or four is guaranteed as a sir exists this example we're given three pass 1 2 3 or 3/1 so we're given three pass 1 2 3 or 3/1 so we're given three pass 1 2 3 or 3/1 so it's a circle and we can just plant the 1 2 3 so each adjustment on guidance or not that's are not with the same flower I so solve it I think it's pretty straightforward so we can just start from the first garden and to the last garden and plant them one by one if one is picked is planet and the gardens connected to this garden or have fewer options for your possibilities so the whole the up the total possibility for a garden is 1 2 3 4 so we just we can just say when we plan a garden we just remove the possible flower from the possible for guidance for possible for flowers right so it's free sorry for things that the path is actually bi-directional we need to so divorce bi-directional we need to so divorce bi-directional we need to so divorce sorry first so let's see we can see that there are some paths is for one we actually need one for so we first actually I didn't try this problem before it says it's labeled as easy let's say if I can't finish we can I can make it so the first one sort the bi-directional pass to one directional okay so there's paths right paths so sort a be our sales for each path sort a be a minus B so this is the one directional and then we was sorted by sorted sort path a eight b return a 0 minus b0 so now the passes are all sorted and we need to create because not all of the yeah we just uh removed the possibilities yeah okay so let's start with the first one start with one for the first Scotland cost results equals 1 for 4 let's I equals to that one I is smaller than and that's enough we will check for each carton oh okay yeah actually we no we were just account the first skirt and also into the for dub let's say there is a cast pass so we let's say new map yeah and a new map okay if I equals zero we will say cast result results push one and then let J equals zero well our paths J zero equals I cause what let what because new fx0 was a plant was one if not we will get it from the new possibility if it is zero oh no ok it's actually not like this if possibility as if possibility has if it doesn't have plant if doesn't have fun okay sorry that poltroon sequels possibility gets high if there's nothing so it should be one okay cost plant equals options zero or one okay so and for each path if start with I and then we watch a plus I we were four sets the possibility so cost options equals possibility and get past a one if options okay if there is we use it if not if there is no options what set it with new set one two three four if doesn't have has it and then we will get it no options equal yeah I think this Way's better maybe and we set with options so we now get the options then we options delete think it's delete right new set point to delete okay three option delete give it what delete planet and then we just do it until this stuff this police are carton is down is done and then we push it result push plant when everything is done and while J is equal to it and well J is more than paths that's planned Oh K and then turn the results let's run it oh okay ah I made a mistake it couldn't be changed options uh in I was sorry and is a number okay what one options undefined cochon defined so when options found we actually we got one two three four outfits cell not options console.log JJ okay console.log JJ okay console.log JJ okay one I'm fine yeah and then one on the 5y aye i-10 yeah and then because J is what we call so long I Jane yeah j11 paths 1-1 it is the same so actually one okay so when i get i 2j is - yeah and burn plant is on the phone but we will okay console possibility well it's a map because j is 0 at is 0 mmm what's the pastor gonna do something also log back in the past is over alright okay i won a zero times one option is divine so j is more than the ninth ray and passes 0 is 1 ah actually this the path start with one based index so and it actually added for one and when I get passes here oh yeah well why don't we just put all one bit one-one based so why is all one bit one-one based so why is all one bit one-one based so why is still one Wow Jay should be zero base but I should be huh we will I'm really confused but it's all stick to that's all stick to a zero-based so this that's all stick to a zero-based so this that's all stick to a zero-based so this year should be patties J zero equals n minus 1 here is passes so minus 100 minus 1 okay one map 101 of k1i sorry should plus one okay Jacob zero and then we get to and then when you get possibility of one because there's no options we set it to one two three four and then the options should be deletes the plan clamp this one so it should be two three four after it we say two three four two four that's right so we map so we console.log the so we map so we console.log the so we map so we console.log the possibilities and we return push one and then we go to the second one the options this idea to this 100 how can I get a set the first a set is set a body's it's a weed eater Oh next got it I need to say values next absence this should work but I'm not sure whether you can pass the time net time limit I don't oh it's luckily in passes but it's really it is really slow it's really slow I think there is something we can improve about reusing set to keep the possibilities let's say four one two three four some is ten one two three should be one two three okay whether we can have a number to improve it I have 1 2 3 is 6 1 2 3 is 5 2 3 4 is 9 2 3 you let's say it's a 120 304,000 something let's say it's a 120 304,000 something let's say it's a 120 304,000 something like this ah yeah now I didn't meeting any of them will lead to a different song okay let's have a try so I'm not sure possibility yeah it's a you could be a map and the options can should not be so when the option is not well say you option is a 3 2 4 3 2 1 and possibility was set its options and then the options is not delete the plant I was sitting back options set options it should be options is - by the it should be options is - by the it should be options is - by the plant okay plant times laughs oh and flat these really updates the options by a number right okay without push the plant but let me get it should be options get so it's options so it's how can we get the options should be hmm nice eh it's oh it's we were said set it to the minimum get optional I'll put it in another function it option is a number so Wow well option ma by 10 is bigger than 10 no it's not bigger than 10 there's 20 how can I get first one it's a anyway doesn't actually doesn't matter what's the plan is so if option it's bigger than four x four thousand four and often this bigger than 303 counsel option speaker than twenty turn into two one you wanna code options to D there is no options to the old yeah but he said oh wait a second J zero the options on the phone plan is one now J is one market still on the phone okay so the first one is one zero force the options the J is zero so next one is two so it's option is undefined and then we - planned by poly plan I made a mistake yeah this is should be the right thing 143 yeah it works it doesn't matter where that is 1 2 3 or 1 4 3 actually we can change the get option here to return them in a small one but we get the large one it's wrong answer 1 4 3 1 2 3 says Kenny right so the last one is connecting 2 3 1 2 wait a sec 9 so connected to three two seven one four one five one okay it should be okay one four five eight it's different two nine three two three nine to nine there's mistake here - nine - now there's mistake here - nine - now there's mistake here - nine - now there is some mistakes we will lock down console law I possibilities one zero two three one zero possibility is sorry oh okay first one always first one we get four three seven that's right so they should be without one sure and this we got let's get to the second one too because there's no 1 2 so 2 is also 1 so we got 2 &amp; 3 taste one so wait a second here we just say okay I we get one zero the second one is one should get one it's also a zero but we set what we said is to this four three seven that's right and when I is one so you should start with two to three and we add it so it should be set to two and eight it was the same right okay now we go to three is six and nine so five and eight we got five Julie's only this so we set it to 4 5 is 301 4 8 is 300 0 a zero yeah and then we go to three we are only get three zero four five four six so four five remove five is okay yeah here's the problem I see what happens the only - but if I see what happens the only - but if I see what happens the only - but if it's more than if the so it should be Delta is this Delta is a smaller option laughs Delta is option it must be zero so math.max zero so math.max zero so math.max zero oh this should be divided from the Delta but in my beard and Delta if that's bigger then we don't need to delete it's weird if the Delta is smaller than options then options can remove it like I say we if we can improve that's still there still mystic let's see when we go to the four or five there is a five there's no 5 so it's should we get the same hmm four five six five seven yeah there is so for its to read three to remove three and it is uh like this that's right four five and do we say three two one so we say it is three and there is six seven six so you should be six ah yeah it's still there's mistakes yeah we cannot just if we will just remove the part of Delta because it's smaller than it should be checked if they can maybe the new set is to remove our return back to the original solution but we're stopped using we are stopped using the new set but we just use a new it's a little faster because oh sorry I forgot to remove my console maybe we can just use a new set it's one two three four and we can just use fly source cities faster I don't know here we just say the option is zero and also we get it's fiction and plant because we said the plan actually we can just access this through index we splice it we splice plants - one hmm it we splice plants - one hmm it we splice plants - one hmm it should be keeping the right same I don't know it's not right okay we get it okay we set it okay say the options option zero yeah we splice it that plan a plan actually expose it as this yeah it should be the same what something wrong here also targets oh okay one two three four and then it's a second one say the two because we put we already pushed a second one to two so we should remove the - ah it is a said the - ah it is a said the - ah it is a said actually anyway last one it's not get we will create another function to get this or equal zero small options and post lots of options I get zero return option this type we get options we run a code Oh gay there is a time limit exceeded ah okay let's look at the fastest one wow this guy this solution is really fast Connor is okay I don't know what about doing but they really fast anyway I'll take a look at it someday later our solution this solution is really easy to understand and we passed and yeah I remove this good option okay not good but we can't prove hmm in the future okay that's all for today thank you for listening oh but you can hear something I can hear something also it's really drains my brain for some tricks for a mad amazing there's problems actually I've hated I like simple solutions just some make our brains confusing but anyway that's good when he needs I don't know why yeah I know why yeah there's no other way and yeah see next time bye
Flower Planting With No Adjacent
minimum-cost-to-merge-stones
You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers. All gardens have **at most 3** paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._ **Example 1:** **Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\] **Output:** \[1,2,3\] **Explanation:** Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\]. **Example 2:** **Input:** n = 4, paths = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,1,2\] **Example 3:** **Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `1 <= n <= 104` * `0 <= paths.length <= 2 * 104` * `paths[i].length == 2` * `1 <= xi, yi <= n` * `xi != yi` * Every garden has **at most 3** paths coming into or leaving it.
null
Array,Dynamic Programming
Hard
312,1126
377
hello everyone welcome to quartus camp we are at the 19th day of april late code challenge and the problem we are going to cover today is combination sum 4. the input given here is an integer array nums and a target value again an integer and we have to return the possible combination of ways we can form the target value from the given values in the nums array so let's understand this problem with an example here is our given input array numbers and target is equal to four the possible combinations we can form from this arrays value are these seven values so the output we need to return is seven so now the things we need to observe here is the possibility of forming 4 is 2 and 2 then adding 2 ones and 1 2. so here as this is a combination of the given numbers the repetition of the same set of numbers is applicable because we can put that in this form 1 2 also we can put 1 2 1 and the other combination we can make here is 2 1 so we should consider all three combination of the same repeated numbers so how are we going to approach so we have seen a similar problem which is coin change already in our channel where the input given is the different denomination of coins and we need to form the given target amount by considering any denominations of given coins it is very similar approach we are going to use the same algorithm and same logic here as well so let's get into the problem solution so before going into the bigger solution let's break this problem and solve it for smaller solution and then go to the bigger solution so first consider our target is equal to one so we are going to start forming one with the given coins or given values so now if you see the values given are 1 2 and 3 straight away we can rule out the values 2 and 3 as they are greater than 1 and we cannot consider that for the combinations so the only possible combination we can have one is one so overall to form one we have one combination so now moving on to two consider our target is equal to two and we have to form 2 from the given numbers straight away we can rule out 3 as 3 is greater than 2 so now we can form 2 with 2 options by considering the value 1 and by considering the value 2. so if we are considering the value one we can do one plus one and if we are considering the value two we can have only two that is also one combination so overall we have two combinations to form the value 2. so now moving on to our target is equal to 3 it will get clear now once we solve the solution for 3. so now i'm going to form 3 with the given numbers so we can consider all three numbers as three is the greater value so now the possibility of forming three with the coins or the values one two and three are so first we have the value one so we have to form three so now we found value one and the rest of the value we need is two so we clearly know one is the value and we have to form two what are the possible ways we can either go for one plus one or we can directly consider two given in the array so overall this is something that reflecting here so if you see the combinations we got for 2 is the same so now by considering 1 plus 2 the combinations we can form is 2 now moving on to 2 so if we are considering 2 to form 3 the value we need extra is 1 so to form 1 the only possible value is 1 so by considering 2 plus 1 the combination is only 1. now moving to 3 so if we want to form three the only possible way by considering three is three only because it satisfies the target so here one combination so overall it took us four combination now moving on to four with the values 1 2 and 3 so if we want to form 4 with coin 1 or with value 1 the rest of the value we need is 3 so here to form 3 we have 4 combinations so overall by considering one we can have four combinations moving on to value two the extra value needed from two to form four is going to be two so to form two the combinations we have is go to 2 this is the combination we need so 2 and with 3 we have that we need the extra value 1 so the overall combinations to form 1 is going to be 1. so now the only combination is one so overall we need seven common we have seven combinations to forms four so hope you're understanding this concept so how am i telling there are four combinations by considering one so if we are considering this alone this four combination what are the possible combinations we have that is one comma three one comma two comma one and 1 comma 2 so these are the four combinations we are actually representing here so this is kind of missing we are going to have a dp array to solve each sub problem at each stage and arrive at the bigger solution so let's see a dry run before getting into the code so here is a dp array representing the values 0 1 2 3 and 4 where this indexes represent the target value we need to form and we are going to fill in the values such that the number of combinations needed to form that target and finally we are going to achieve our solution here where a target is equal to 4 and the number of combination will be the value inside our dp array so we are going to start our array with value 1 at index 0. you will understand once we complete the iteration so now moving on to the next cell the value or target is equal to one and we need to form the target one with the given values so start considering the values we can rule out two and three by 1 you can form the only combination is 1. so how are we filling this value before understanding the pattern so here the value you can form is 1 so from 0 you can add only one value to get to or to reach one so the only possible combination is adding one if you are not understanding you will understand once we reach the value three so now the next target is two so to form 2 let's start considering the values starting from 1 so from 1 what are the possible combinations here the place 1 it is a only possible combination so we are going to put 1 plus moving on to the next number or next value two so by two the only option you have is considering one lead two so that is another combination so overall you need two combinations to form two so now coming on to three it will get clear now so now the target is to form three with the given values one two and three so first start considering with value one so we have one in hand and the rest of the value we need is two so to form 2 what are the possible combinations so at 2 the possible combinations are 2 so we are going to consider 2 plus so now moving on to our next value which is 2 so to form 3 we have 2 in our hand so what is the rest we need 1 so at 1 what is the possible combination to form 1 is 1 hope i'm not confusing you so now moving on to the next value 3 so to form 3 we have 3 so the only possible value is 3 so we are going to add 1 so how we are adding if you have 3 the rest of the value we need is 0 so at 0 to form 0 the possible combination is going to be 1 so we are adding that here so overall we got 4 so finally moving on to 4 so we want to form for target 4 with the given values so the first value given here is one so if we have one in our hand and we want to form four so the rest of the value we need is three so to form three the possible combination at the place three is going to be four so we are considering four so the next value is 2 so to form 4 from 2 we have 2 in our hand the rest of the value we need is 2 so at the place of 2 the combinations to form 2 is 2 so we are considering 2 again so finally we are moving on to the value 3 so we have 3 in our hand and the target we need to form is 4 so having 3 the extra or the rest of the value we need is 1 so to form 1 the possible combinations are the position 1 is 1 so overall we have 7 combinations with the given values 1 2 and 3 to form the target 4 which is actually our output so we are going to return the value at this position once we fill the values at all the cells for our adp so hope i made it clear this time so we are going to hydrate this dp array and fill this array for the target value given and the number of values given in the nums array so overall it is going to take big o of t into n where t is the given target value and n is the number of elements given in the num sorry so let's go to the code now so yes we are going to have a tp array of size target plus 1 because we are going to start with the value 0 and our target is the actual value we needed and i'm assigning dp of 0 is equal to 1 and i trade through my given array because we are going to consider each target from 1 to the maximum target given and for each target we are going to consider each value given in the nums array so first i'm going to fill my dp array so at each cell i'm going to add the values at dp of i minus n so i is actually the target value and e n is the given value in the numbers for example our target i is actually 3 and the value we considered is 1 so we got 1 in place and the rest of the value we need is 2. so we are going to check at the position of 2 that is dp of 2 and get the value and add it to the value at that position so now before filling the value i am going to check the basic condition that if i minus n is greater than or equal to 0 because if the given value is 5 and the target we need to form is 4 we cannot consider 5 at all for the combinations so yes once it is filled we want to get our solution at the last cell of the dp array and finally we are going to return dpr target so yes solution is done so let's run and try so let's submit yes the solution is accepted hope you understood the solution and i made it clear so thanks for watching the video if you like the video hit like and subscribe i'll see you next video thank you
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
917
hey what's a Knick white a Tekken I do tech encoding stuff on Twitch in YouTube and if you check the description you can find everything and I do all the hack ranking link code solutions I play for playlist for both of them so I just check those out this is called reversed only letters and we did reverse string and reverse number already that's basically the same concept it's only just a little bit harder and time and space complexities are worse because of that it says given a string s return the reverse string where all characters that are not a letter stay in the same place and all letters are in the reverse position so we're still reversing the string it's just anything that's not a letter has to stay in the same place meaning that the index of any character that is not a letter for example this - that is not a letter for example this - that is not a letter for example this - at index 1 in the input string is going to stay at index 1 in the output string so anything that's not a letter will stay at the same index so there's two ways to do this you can use this stack or you can use a counter so let's do the stack way first so we're gonna stack characters we're gonna do two characters letter and that's where this character class is useful because you can literally just call the method is letter and determine whether a character is a letter so if the character is a letter then we're just gonna push it onto the stack otherwise we're not going to do anything so letters dots push that stop char so what happens during this loop so we look through the string we push all the letters onto the stack so that reverses only the letters and that's literally the name of the problem it reverses the letters because when you put things on the stack the last elements gonna be the top of the stack is going to be the last letter in the input string so when we do the second loop we can just pop off of the stack and it'll be in the reversed order so that's what exactly we're gonna do we're is going to do this here it's gonna be kind of the same conditions here so if the character is a letter then we're going to pop off of we're going to put we're gonna we're also going to need a stringbuilder to store our new it's gonna we're going to need a stringbuilder in both of these versions to store our new string the reversed version so we've the string builder I'm gonna pen to the string builder letter stop pop now I'll explain this in a second and then otherwise we'll just append turn into character okay so what we're doing is we're looping through the second time we have the reverse version of the string and what we want to do is we want to keep anything that's not a character in the same order so if we see something that's not a character this else will get executed and we're just gonna offend the current character so that's gonna work perfectly otherwise if we saw a letter at the beginning so say a then we have this stack of reverse letters we just pop off the stack and get the ending because we want the reversed the actual reversed version of that so that's pretty much it that's the I think this is the easier way to do it easier way to see how it's working and understand it then you just return a string builder dot to string and this should work no you have to return it sorry okay so there you go that's it that's pretty much that's pretty simple you just have to kind of it's I mean hopefully I explained that well enough you just we're just keeping anything that's not a character on the same word it's not about hard to understand that's why this works we reverse all the characters we get the reverse character unless we see a character that isn't a letter and if it isn't a letter we just want to keep it the same so we just append it otherwise we have the reverse letter obviously so there's another way this seems more optimal to me even though in if you're dealing with something that's large-scale it's still the same time large-scale it's still the same time large-scale it's still the same time complexity and space complexity both of these are linear time and space so we're just gonna have the stringbuilder once again and then we're just gonna instead of having a stack we're just gonna have a counter J is equal to s dot length minus one kind of a pointer to the end of the string and we're just gonna kind of you know implement these stacks functionality in this problem with a pointer to the end of the string instead so we'll just use a condition in the little inner loop here so if character dot is letter so if the character is a letter then just like in the last one if we see a letter we're gonna want the characters at the end instead of the ones at the beginning and if we don't see a letter then we're going to want to just append it's kind of the exact same thing it's the last version just a little bit different you'll see the second so if we don't see a letter we want the same exact order and everything so you just append to the stringbuilder and it's the same thing we're just turn the stringbuilder got to string at the end and then if you do see a character this is the only thing you have to think about here is Wow character while it's not a letter of s dot char at J so this is kind of handling the stacks functionality because what we don't want is we don't want to reverse like it says reverse only letters so we don't want to reverse things that aren't letters so if we check the end of the string because when we see a letter we just check the end of the string and that we actually grab you know the we would check you know in this case we would check for J at the end of the string we see a we check for J at the end of the string we put it at we put it into reverse string but if we were to see a dash here we would want to grab that because we don't want to reverse things that aren't letters so what we do is we just keep decrementing J so we would skip over anything that's not a letter until we found a letter and then once this loop breaks we have found a letter that we can add to reverse string to keep reversing it and then we just append that in the decrement J so yeah that's pretty much it hopefully that works first try let's see there we go first try so those are the two solutions the same time and space complexity differences you have this little loop and condition versus a stack it doesn't really matter which one you use let me know if you guys have a found a better solution to those this one's pretty easy but I'm gonna do a bunch of them right now so let me know what you guys think and please check out the rest of these alright thanks
Reverse Only Letters
boats-to-save-people
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
Array,Two Pointers,Greedy,Sorting
Medium
null
1,530
uh hey everybody this is larry talking about a number of good leaves notes pair uh recently code contest so you'll see me solve this live later um but so this one is a tricky one i think the thing to notice is that distance is at most 10. so that um along with this which is a really awkward 1000 uh or i mean i know it's a little bit over a thousand um allows you to brute force it uh with if you remember the cache uh at least that's what i did uh but basically so there was so i did a really brute force um but as long as you cache or do something like that i'll be okay so basically my solution is for every node for example in this uh full tree i go okay if one is the root how many good pairs are there if two is the root how many good pairs are there if three is the root how many good pairs there and so forth um and so that's this part of it of a 40 name function called go uh and then for each one i go okay so how many good pairs are there of distance um so the question pair here is okay so this is how many good pairs are there for uh for this node as the root and this is for um distance is equal to um this thing is uh how many good pairs are there for this node as the node is the root with distance equal d right um and then now if you do that then you know oh that you can also put first okay if this distance is a fixed say two distance um then that means that one has to be on or then you could uh move first number combination which is you know zero node on the left two on the right distance wise and one to one so like kind of a balance kind of check the number of nodes of that route i also have a jet leaves that check that takes the distance uh so for every node for and every distance it will get me the number of leaves that distance away uh so this is the recurrence uh take a look at it um so the hard part about this right is try to figure out the complexity so this is proof for us uh take a look at this and you know you'll probably try to understand this a little bit but um so this is exactly by the way uh how many leaves are exactly distance away from node right um yeah and so the question is how many you know this looks really expensive really complex right so how what is the complexity well the complexity here is what get leaves what is get leaves well get leaves is over one for each pair because it just you know does one or it does two recursion but all of one work will do well so all of one work purse per car uh how many cars are there's no number of causal n for nodes and times some you know absolute value of distance right so that means that this function the entire function in aggregate will do o of n times uh after the value of distance amount work right total work uh number of course right here okay how many notes are there well of course are number of cars uh number of different cars right um but each one of them does how many work does it do well there's this for loop that goes literally your input distance which is at most 10 and then this one also does another distance right so that means that each core does roughly uh this time right uh work per core so the total number of work here is n times distance squared right total work so then this complexity as we saw is o of n times distance squared plus n times distance which of course just simplifies to the first part right because it gets dominated uh and this works because again distance is 10 and n is a thousand so it's about you know 100 thousand right so yeah so that's uh both the time and the space complexity because we store you well uh actually now the space is actually only o times distance because it gets dominated by this which is the number of cores uh because here the space is actually just of n so for each node so yeah uh so that's the complexity and ours is for this form let me know what you think this is a hard problem though to kind of you have to make sure you break down and really ask yourself for each function what question are you really asking and then really analyze the situation um yeah let me know what you think hit the like button the subscribe button and you can watch me stop this prom live now hmm okay that's one yeah okay this uh now you um ah so oh my god well slightly better this one hmm oh hmm chopped cheese oh this my hmm um fast enough
Number of Good Leaf Nodes Pairs
check-if-a-string-can-break-another-string
You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`. Return _the number of good leaf node pairs_ in the tree. **Example 1:** **Input:** root = \[1,2,3,null,4\], distance = 3 **Output:** 1 **Explanation:** The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\], distance = 3 **Output:** 2 **Explanation:** The good pairs are \[4,5\] and \[6,7\] with shortest path = 2. The pair \[4,6\] is not good because the length of ther shortest path between them is 4. **Example 3:** **Input:** root = \[7,1,4,6,null,5,3,null,null,null,null,null,2\], distance = 3 **Output:** 1 **Explanation:** The only good pair is \[2,5\]. **Constraints:** * The number of nodes in the `tree` is in the range `[1, 210].` * `1 <= Node.val <= 100` * `1 <= distance <= 10`
Sort both strings and then check if one of them can break the other.
String,Greedy,Sorting
Medium
null
63
this question is unique paths too it was requested so this one's for you midilesh a robot is located at the top left corner of an m times n grid the robot can only move down or right at any point in time and it's trying to reach the bottom right corner now consider if there are some obstacles added to the grids how many unique paths are there so that's really the only difference we are given a grid like this and it's going to tell us that ones mean there's like some sort of obstacle blocking the robot from passing so it can't go right or can't go down to that path so how can we solve this then well the approach is actually the same we can still use a dp solution is just that now we need to account for this obstacle make sure that when we find this obstacle here we no longer calculate a path there so the first thing we want to do is calculate our base numbers right and here if we had our dp away it would all be ones on the first row and all ones on the first column but if there's an obstacle here say there was an obstacle here then the number of paths there should be zero right there can't be any path there and on top of that there can't be any path underneath that either all the rest should be zeros as well same with up here if there was like a one here that means that this would have to be zero and after that really the only thing is to account for those zero numbers and still sum up the cell on top and the cell to the left only difference being if there is an obstacle there then we make that a zero and we just continue our algorithm and that's really the only difference so let's first initialize some variables we'll have m which is going to be the length of obstacle grid and we'll have n which is going to be the length of obstacle grid first array so these are the columns essentially now we want to have a dp array right and the dp is just going to be a list of lists so save for the columns it'll be 0 for in range of n and we want a list for each one for whatever in range of m so great now we have our dp array and we want to first calculate the first row and the first column so keep in mind that this obstacle grid is going to be what allows us to know if we should stop so we're going to build these up say we'll start with one you know one but just check every single time to see if there's a one here and if there is since all of these are already zeros we'll just break there and say that this was like if this had a one in here this would actually be zero and everything to the right of it would also be a zero so four let's say the columns uh we'll say four um c in range of uh let's see n what are we going to do we'll say if obstacle grid i'm going to copy paste that if the first one c equals one then we'll just break our loop we'll just break out of it otherwise we'll make it a one just like before say zero and c make it equal to one and all of them should be ones right because there's only one distinct path there now we'll do the same thing with the first column we'll say if the first column zero equals one we break it otherwise just make r zero equal to one so now we'll have in like in this example all these would be the same would just be all one like this wouldn't be zero but keep in mind there was an obstacle there right now one so this accounts this if statement makes sure that it's going to be kept at zero if there's an obstacle there because afterward we don't care if even there's more obstacles like the result is the same it'll all be zeros anyway since the robot could only go right or going down now it's the typical way of just going for row and let's see range of m and column range of n and make sure we go from the second element since we've already calculated the first row and first column and we'll check all right dp or not dp obstacle grid rc if you're equal to one well make this dp rc equal to zero because there's no way to get there's an obstacle there so you can't get there right otherwise we just do the same exact thing we say just it's the sum of whatever came above it and whatever came to its right after that we just return our dp the bottom right corner and that's actually it's a little more simpler than you would think so looks like that's working let's go and submit that and there we go so nothing to it's just a little bit of you know intuition and just experimentation to figure out oh it's really the same algorithm just we need to account for all these zeros and make sure that if especially on the first row and first column if there's a one we have to make sure everything else that comes after is also a zero all right thanks for watching my channel and remember do not trust me i know nothing
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,029
hey guys welcome to the core Matt if you are new to the Channel please do subscribe we solve a lot of competitive problems today's problem is a to city scheduling so the problem says there are two and people a company's planning to interview the cost of the flying the ID pass sent to the CTA is caused by of zero and the cost of flying high person to city B is cost of I of one so we have a two-dimensional matrix of course as a two-dimensional matrix of course as a two-dimensional matrix of course as given a zero conducts says cost to travel are to the CTA and first and X havinga cost to travel CT be written the minimum cost to fly every person to a CT such that exactly n person arrives in each city so what we are expecting in a result is we want to get a minimum cost but the constraint is its city hangar there are two n people in a company so we have to each city should have total n person visited for the interview so we need to get the minimum a cost of the flying to CT a as well as B for the N n number of persons so let us understand with the example so here the cost matrix is given 10 and 20 so 10 percent traveler a CT and 20 is to travel ctp same goes for the other person here we have total number of persons is equal to 4 and the cost is equal to 1 0 now let us understand so out of given a 10 and 20 the first person goes to CTA for a cost of 10 so because between a and B first person has selected to travel to city a second has selected to again travel to the city a and next to person selected to travel to P because we also want to get a minimum out of it so total minimum cost is 10 plus 30 plus 50 plus 20 so all hosts total is equal to 1 0 that is what the total minimum cost we can get out of given cost matrix now let's understand solution approach for this problem alright so we have written city a and B and with respect to that or cost it is going to be to travel CTA so this is your cost matrix ok now let's say instead of a traveling on about the city let's consider in this way so let's say if we are only traveling to the city a so let's say if we are only traveling to the city for all the persons what is the cost total cost it is going to be so it is going to be always a total of all these numbers from CT a ok now as in the problem statement it is given like we also want the person or the number of person to be divided equally so saw half of the person needs to travel a and half of the person needs to travel B so let's say we have considered all to travel a and we would like the half of the person to travel beyond now how to select which all best suitable person or having a low cost to travel B how to get those and by 2 or half of the person from the B so to get that we can do one thing is like we can see like what is the cost to travel a for this person with respect to B whether it is possible to select location B for this person instead of selecting a right ok and this we need to check for all the locations because we cannot directly select this person to travel be directly without comparing the other difference with this pace right ok so we can do one thing like we can let's say here the difference between this two are to dude cost is let's say if we go with this way let's instead of a we will take B minus a so that's a difference between this two is are ten mine 20 minus 10 is equal to 10 same for the second pair so it is having cause differences 13 so that is going to be 170 okay here it is going to 50 minus 400 so it is going to be minus 350 okay and same goes for this one 20 minus 30 so it is going to be minus de okay so this is what the our difference between the cost if we travel to be instead of way okay so this data gives a better understanding like instead of for first two percent instead of the towers to be it is okay but it is good to travel a location a and if you see the last two person and it is good their travel to be because the cost to travel B is less for these two persons okay so how to get this data like how to get this 2 percent data or to select these two persons which are having a less cost with respect to the all other a given person so what we can do here is what are the result we have right in the Delta let's say we call it as a filter okay so we can make a heap or priority Q of this data and we can hold the dis values so first when you have a 10 so it will be value will be 10 and then 170 because it is always you know increasing order and then when you have - 1 - 350 so it is then when you have - 1 - 350 so it is then when you have - 1 - 350 so it is going to be first element and again - 10 going to be first element and again - 10 going to be first element and again - 10 okay so this gives a clear idea like this first 2 is going to be your lock your persons which is having her which they are going to travel to point to be okay now previously how can we get a total minimum cost so previously you already calculated our total minimum cost travel to a so let's say this is going to be our 10 plus 30 plus 400 plus 30 okay now here the difference is 350 so we already added a 400 and instead of this person to travel to B we would like that person to travel to this location like be okay so we already added a 400 we can take the first Delta because the Delta is going to do - 350 we would like Delta is going to do - 350 we would like Delta is going to do - 350 we would like to add a 15 instead of 400 so you can your whatever the total minimum cost till now and you can add a delta of the first person okay this way we are neglecting the 350 which is going to which we already added as extra R to the now your total minimum cost same way you can repeat this tilde and by 2 okay so it gives like fair idea like for this n by 2 person we have added distance from P instead of a so this way we can achieve the total minimum cost now let's go back to the code editor and go through the code now let's understand the code so first we have define a total sum which is we are interested to return and then length of the whatever the given number of persons and we have divided that length because from half of the person we would also like to get it from the be okay and then we define a priority Q which is again me based on a normal order it will short based on in increasing order okay we'll iterate it hour through 0 to the length and then this is what the cost from the a if we are planning to travel all the persons to the city then we accumulating those total cost to the some okay and then as we discuss we are also maintaining the Delta to travel B instead of a so we are adding the difference or Delta to the priority queue now this condition suffers when you yo already calculated up half of the person's Delta okay now if your eyes greater than half of your Delta then at that time we also would like to start picking the delta and edits so this will suffice condition where we would like to take half of the person so this two from the B so when we reach to the N by 2 we would like to go to the a big priority queue and start taking a delta from there so we are adding the Delta to just settle the entry between a and P okay and then we are returning the sum so that's it in the core let's run this code okay you've got finished so this is what they expected outlet submitting okay it got submitted so that's it in this video hope you liked it please add comments if you have a different approach or you are looking for solution for a different problem thank you guys
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
111
hey guys in this video i'll be going through how to solve lead code question 111 minimum depth of a binary tree okay so for this question we're going to be given a binary tree and we just have to find the minimum depth meaning the height of the first node that is considered a leaf and a leaf is just going to be anything with no children so looking at this example we're given nine is the closest node to the top that has no children branching off of it um and so since nine is on the second level of our tree with this three being on the first level and then this would be the second level we would return a two here okay um so there's kind of two approaches you can take to solving any kind of like binary tree searching and it's either going to be depth first search or breadth first search and the approach that we're going to want to take here is breadth first search because if we do a depth first search here we are gonna have to search every single node in the tree because um you'll have to essentially like look through every node and store the depth and then at the end um return whatever the lowest number was that you found whereas with breadth first search you can loop through um like level by level and so then the first leaf that you encounter um is going to be the one that's the closest to the top so we won't necessarily have to check every node in the tree and that'll make this a faster algorithm okay so if we actually start coding this the first thing we're going to want to do is make a cue and we're going to store nodes for a tree and this is just going to start with our root node and then we'll loop while um nodes is not empty and this loop is basically just going to be um like a while true because we'll never not return from this loop but we're going to have to put a return statement outside of it because otherwise the c plus compiler will complain that not all paths will have a return value so basically in this loop what we have to do is check whether or not we're at a leaf um if we are we want to return the level that we're at and if we're not at a leaf we're going to want to add the children to our queue and then kind of do some calculations to determine what level we're on so we'll first handle checking whether it's a leaf or not and i'm just going to paste this code in to save time typing so this if statement is going to check if the current node which is dot front or the first one in the queue if that's left child if that one's left child is null pointer and its right child is null pointer then we know that's a leaf node and then we can return a min depth variable which left to declare up here okay and then if that's not the case um we're going to have another variable another integer that subtracts the size of our current level and we'll also do one to tell us how many nodes we've gone through on the current level okay so since we just looked at a node we can increment our scene variable um and then since we have not found a leaf yet we need to take whatever node we're just on and add its children to our queue because we're going to have to check those as well and i'm just going to paste this in again okay so these if statements just make sure that we're not looking at a null child um so like if there is a child to the left of a node we want to add that to our queue and same thing on the right side and then we're done with the current node that we're on so we can just do nodes.pop to remove it from the front of nodes.pop to remove it from the front of nodes.pop to remove it from the front of the cube okay and then the last thing we need to do is our size checking so i'll just paste this last segment in here okay so all this is doing is saying if um the size of our level so like the level in the tree um if that is equal to how many we've seen then we've completed the level so we start with this at zero like we haven't seen any yet and the first level size is just one because there's only going to be one node on the first level so after we check that root node this will be equal and then we're going to set level size equal to the size of our next level because at this point we'll have every node on this next level and then we'll put our counter back at zero so it can track to see when we reach the end of that level again and then our depth or like the height of the tree that we're on is going to increment so that we know when we return this which level that first leaf node was seen at and that should pretty much be it so i'll run this to make sure it works and we need to do one thing i missed here um at the very beginning we didn't we need to make sure that our root node is not null um and if it is null then the return value is just going to be zero okay and that was accepted so for the complexity of this algorithm um i'll start with the space complexity we're storing a q here so that's gonna be based on the number of nodes that we see obviously and in the worst case it'll be the size of the total nodes in the tree so this is going to have a o of n um space complexity and this is the only data structure that is based on the input um these variables will just be the same every time so this is our space complexity of n and then for time um we're going to have o of n as well because we're going to be just looping through up to the number of nodes that we have and within this loop we're only doing constant operations so this check is constant incrementing is constant doing accessing the front element in a queue pushing to a queue or popping from a queue those are all constant operations um and then accessing the size of a queue again is constant so um our largest like time complexity to worry about is just the loop itself which is o then okay um i hope that going through this solution was helpful for you guys and thank you for watching
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
1,630
hello and welcome to another video in this problem we're going to be working on arithmetic sub rays and in this problem a sequence of numbers is called arithmetic if it consists of at least two elements and the difference between every two elements is the same more forly they Define it for you so for example this is arithmetic because the difference here is two this is also arithmetic the difference is zero this is also arithmetic the difference is -2 is also arithmetic the difference is -2 is also arithmetic the difference is -2 and this is not arithmetic because the differences aren't the same here so essentially what we are given is we are given an array of nums and we are given two arrays left and right and we need to perform queries on this nums array where we start at the left element and we end at the right element and we need to check are they arithmetic so for example for this first query we say okay starting at zero going to two is this arithmetic and it doesn't have to be in the right order like so you can so it might be out of order so this is arithmetic right 465 because we can just sort it and get 456 and that is arithmetic 0 to three is 4 659 which is not arithmetic and then we have 2 to 5 so 2: arithmetic and then we have 2 to 5 so 2: arithmetic and then we have 2 to 5 so 2: 5 is right here so 2 three four five right 2 three four five yeah and this is also arithmetic because it is 3579 when sorted so basically the second example is like this but essentially the easiest way thing to do well let's actually look at the constraints first of all so the constraints n is 500 m is 500 meaning you have 500 queries on an array of 500 elements so quote unquote root fors here would just be for every single query let's just get the elements and sort them right and then they would be very easy to find if it's an arithmetic sequence or not so how long would that take well that would take and for you would have M queries right and then for every query you might have all of the elements so that would be n and then to sort would be log n so MN log n and this would actually pass right this is 500 * 500 * log 500 which right this is 500 * 500 * log 500 which right this is 500 * 500 * log 500 which is basically nothing so 500 * 500 is basically nothing so 500 * 500 is basically nothing so 500 * 500 is like 25 with four zeros so that would easily pass so actually you can do this right for every single query you can just make a function that just slices into your array for example let's say we have the array for uh let's actually take yeah we take the first one it's not very hard um actually let's do the second one because we are going to use it for the second example as well so let's actually take the second or instead so we'll have -2 second or instead so we'll have -2 second or instead so we'll have -2 93 12 6 15 20 - 20 - 20 - 255 - 20 255 - 20 255 - 20 15 10 essentially what you can do for any query is you can basically slice whatever indices you need like let's say we take these sort them right so if you sort the numbers here you would get something like -25 -126 20 and then basically you just find -126 20 and then basically you just find -126 20 and then basically you just find the difference between the first two elements so like in this case it's 13 and then you just make sure for the ne for every other set of elements is difference the same so it's very easy problem right just take the query sort there you go and that does work but we're going to try to have a linear solution so we're going to do a slight modification it's not too bad um and the easiest way I found this after doing it a few times is it's actually easier to do a slice of the array instead of just passing in the left and the right bound and doing something so essentially what it's going to look like let's actually go through these queries and kind of show what's going to happen so for the first query we have zero and four which means the slice is going to be let's actually uh index these as well just to make it easier for us so 0 1 two three four five six seven so we're going to go through these queries in this example so 04 is going to be this chunk over here so let's write out these elements and we are not going to sort them this time to make a better solution so there we go and now basically we are asked like is this an arithmetic sequence so how can you do this without sorting so you can do without sorting and the way we're going to do it is we're going to get a Min and a Max and if you think about it for any kind of sequence right with n number it's going to be like n or the numbers is going to be like one and then one plus that uh that whatever difference is between the two numbers right one plus the difference plus the second number and so on so actually let me write another way to make it easier so let's say we have like the first number and then or actually I know the best way okay so let's say we have a bunch of numbers right let's say we have five numbers here so the difference between any two consecutive numbers has to be some constant number right let's call this like d so basically for five numbers you add the difference four times right because you have four additions and every addition for an arithmetic sequence adds that exact difference so for example for sequence 1 2 3 4 the difference would be one now basically we can calculate this difference because the difference has to be if we take the max number in this uh sequence so the max number here is uh -3 sequence so the max number here is uh -3 sequence so the max number here is uh -3 and the M number is -12 we get the and the M number is -12 we get the and the M number is -12 we get the difference there so we're saying like what where does our start and where does it go right and because it's not sorted um if it can go one way or the other right so we can always make it increasing if we want to right so basically like if something like this is an arithmetic sequence then the other way is also arithmetic so like 5 4 3 2 1 is so we're just going to say let's just have a Min number and our Max number and let's always go increasing so our Max number will be this our Min number will be this so we're going to do Max minus wi Min so we get3 - minus wi Min so we get3 - minus wi Min so we get3 - -2 and we get 9 so our difference is 9 -2 and we get 9 so our difference is 9 -2 and we get 9 so our difference is 9 now how many numbers do we have five so remember you add the difference n minus one times so we have to go from this sorry it's not the difference this is what this is like the total increase you need right so from the smallest to the biggest number this is how much you need to add total and how many times do we add it's n minus one so that's going to be four so our difference here should be 2.25 now in any arithmetic sequence if 2.25 now in any arithmetic sequence if 2.25 now in any arithmetic sequence if your number is not an integer that means invalid right we can't add 2.25 we can't invalid right we can't add 2.25 we can't invalid right we can't add 2.25 we can't do like 1 3.25 and so on so right away do like 1 3.25 and so on so right away do like 1 3.25 and so on so right away whenever we get a difference that's um non integer we can just return false so this query right away would return false and it doesn't make sense because we have 12 twice so this wouldn't be an arithmetic sequence so for this first one this is going to return us false and let's see if that's what it was okay now let's go to the next one so we have 14 so let's get this slice now right so um instead of actually uh instead of uh writing out the actual slice I'm just going to highlight it so for this slice what's our Min and Max well our Min is -12 and our Max is3 so let's do this -12 and our Max is3 so let's do this -12 and our Max is3 so let's do this difference again so -3 - -12 we get 9 difference again so -3 - -12 we get 9 difference again so -3 - -12 we get 9 how many elements we have four remember you had the difference n minus one time so 4 over three so now our difference is three is that a valid integer yes it is so now once we get a difference all we have to do is we have to Traverse from the men oh and there's one more thing I forgot to say so there's one more step but because our difference failed the first time so what we're going to do is we need to somehow figure out like how to get rid of duplicates right because the only way you can have duplicates and have a valid Ari metic sequence is if your entire sequence is um all the same number right so like the 7777 thing so what we're going to do to get rid of duplicates is turn this array into a set right so we're going to turn this array into a set so what's going to happen here is in this case this is going to be the same thing and we're basically going to say okay let's start the minimum number which is -2 and let's the minimum number which is -2 and let's the minimum number which is -2 and let's just keep adding the difference until we get to the maximum so we need to get to3 and anytime we add a number let's just check is that number in our set and if that number is in our set that means by the time we go from the Min to the max we would have valid arithmetic sequence right so we start -2 we would add three right so we start -2 we would add three right so we start -2 we would add three we go to9 that's in our set okay we add three again got A6 that's in our set add three again got A3 that's in our set so every single number was in our set and we added the same number every time so we know this is a valid sequence so that's how you could do you just take an array convert into a set and I found it's easier to take an array convert into a set than to take indices and convert them into a set because there are a lot of like edge cases for that so it's easier to take the array and because you're using a set anyway your space is going to be o anyway so it doesn't really matter um yeah so the second one will be true so this is done actually let's uh get rid of this line here okay so there we go so this is done now let's take our third query so our third query is 69 so that's going to be over here and yeah so same thing calculate our difference so our difference is going to be smallest number is -25 biggest number is -25 biggest number is -25 biggest number is 20 and then we get the difference so that's going to be uh 20 - -25 which is that's going to be uh 20 - -25 which is that's going to be uh 20 - -25 which is 45 how many elements we have three we have four minus one right you have the difference nus one times so three here this is difference of 15 we have valid difference now what's the smallest number we start at -25 and we keep going number we start at -25 and we keep going number we start at -25 and we keep going remember we convert this into a set so basically when we convert it into a set it'll be - 255 20 it'll be - 255 20 it'll be - 255 20 and5 actually no these are all unique Numbers Never mind these are all fine right yeah okay so we go to -25 that's right yeah okay so we go to -25 that's right yeah okay so we go to -25 that's in our set we add 15 then we have -10 and -10 is not in our set so this -10 and -10 is not in our set so this -10 and -10 is not in our set so this should be false right because this should be our difference for this to work has to be 15 but -10 is not in our work has to be 15 but -10 is not in our work has to be 15 but -10 is not in our set so this is invalid right so we just Traverse up anytime your number is not in your set then you know this is invalid and indeed for this to be valid if it starts at NE 255 and ends at 20 it would have to be -25 -10 5 and 20 right for a four number -25 -10 5 and 20 right for a four number -25 -10 5 and 20 right for a four number sequence this is what it has to be so essentially we can easily figure out like what does it have to be and just check are the numbers in our set so for this one we're good let's keep going for the fourth one we have four and seven let's uh actually this okay so for four and seven so same thing what's our Min and Max so our Min is -25 our Max is 20 so Max so our Min is -25 our Max is 20 so Max so our Min is -25 our Max is 20 so our difference here is 45 over3 which is hopefully I didn't do the same in twice I don't think so but let's find out yeah well I guess we'll see okay so our difference here is 15 um I don't think we did but anyway yeah so our difference is 15 uh so we do the same thing so we start at25 and we add 15 right so add 15 we get 10 or NE we get A10 sorry so is10 in our set so our set would be these numbers obviously we're going to see like this6 can't be in here so this clearly can't be uh clear conve answer but1 isn't in here once again this had to be - 255 -10 here once again this had to be - 255 -10 here once again this had to be - 255 -10 5 and 25 for it to work so this is clearly not a valid arithmetic sequence so we can say false for that one and we have two more so we have eight and N so eight and n's right here uh so what's our minim Max -20 our minim Max -20 our minim Max -20 and15 obviously for any two length arithmetic sequence is always going to work but let's just do it anyway so our difference here is five and it's 5 over one right 5 over n minus one so five valid difference now we start at um -20 valid difference now we start at um -20 valid difference now we start at um -20 add five5 right so we got from our minimum to the maximum and it's a valid sequence so this is going to work so true there and finally for the last one we have 710 so 710 is right over here um okay so the minimum is -25 the maximum is -10 so the difference -25 the maximum is -10 so the difference -25 the maximum is -10 so the difference here is 15 and our elements is 4 - 1 so three so 15 and our elements is 4 - 1 so three so 15 and our elements is 4 - 1 so three so our difference is five now we check all our elements so we have -25 that's in our elements so we have -25 that's in our elements so we have -25 that's in there we add five we get -20 that's in there we add five we get -20 that's in there we add five we get -20 that's in our set um add five5 that's in our set add five1 and that's also in our set so we manage to get from the smallest to the biggest element so this is true as well so that's kind of basically as a sum up we're going to have a helper function that will just take an array get min and Max calculate difference check if it's valid right if it's not an integer we can just return false try to get from Min to Max with adding difference each time and if we have all elements then we made it right okay that's basically it so it's a lot easier with sorting um but this is also not too bad and this should be faster in theory okay so let's C it up so we're going to make a helper function at the top and then we can just process our queries and this is kind of an easy problem just because you can basically process every query without doing any kind of pre-processing like you can kind of pre-processing like you can kind of pre-processing like you can literally just run this you know and you don't need especially with the Sorting way you don't need any kind of optimizations like normally when you for harder problems when they give you a bunch of queries you can't just run the queries directly you have to do some like optimizations because especially for query like this is very easy to check if something is in arithmetic sequence by sword so we're going to say d query Checker it's going to take an array we're going to get a Min item Min array Max item Max array now we're going to get our difference so we'll just say diff equals Max item we could have actually done this in one line um that's fine we're going to reuse variables anyway so max item minus Min item over the length of the array minus one now we need to check is our difference an integer easy way to do that is you can just say if difference mod one so basically what's going to happen here is if it's like 2.25 you happen here is if it's like 2.25 you happen here is if it's like 2.25 you will get 0.25 so if this is non zero will get 0.25 so if this is non zero will get 0.25 so if this is non zero then we have an invalid difference so we can just return false now we do uniques is our set of all our numbers to get rid of the duplicates and we'll say per is min item and we'll basically say while Cur is less than Max item and we just keep checking is our current item in uniques if it's not then we can return false right so if Cur not in uniques let's return false and we'll just keep adding the difference and finally at the end if we made it through this whole thing let's return so now at the very end this is very simple all we need is a result array and we can basically say 4 I in range one of the lengths left or right we'll just pick right um so we can append the actual result of the query right soend query Checker and then we basically have to slice this array so it be nums the left index is going to be left I and then the right index is going to be right I + one right index is going to be right I + one right index is going to be right I + one right because it's non- inclusive so if left because it's non- inclusive so if left because it's non- inclusive so if left was zero and right was three you want to have zero and four here for the slice then it'll go 0 to three essentially append them all and finally return result and yeah this is easier than passing an indices and making a set right away because if you do that there are a lot of edge cases and I did that before and this is like 10 times easier so I definitely recommend this and like I said uh in actual Theory this doesn't cost you anything because you're still making a set in practice it will take up a little bit more space because like let's say your ARR is all your items um you know your has a ton of duplicates then you are you know this does take more have more space in set but on the bright side this runs a lot faster and has way less edge cases if you just pass it an array directly instead of indes let's try that and there we go very solution um yeah better than sorting like I think this problem with sorting is probably like a very easy media problem I have to say and then without the Sorting it becomes like an actual medium problem um and let's think of the time and space here so we are performing M queries so that's already M for every single query we are slicing the array and worst case scenario obviously that whole array is uh length n right so that array can be length n and we are going through our entire array so turning an array into a set also takes the length of the array that's already length then and then going from the smallest number to the biggest number uh worst case scenario you're basically going through like if your arrays all unique elements and doesn't make up a valid um it doesn't make up a valid arithmetic sequence then this part would also take length n so it's like length n and then length n which is just length n total so for every single query it's going to take end time and then we have n queries um yeah and we save that n logn from not working so space basically every single time we are building an array that we're turning into a set so that's just oen because array can be every single element in this noes and yeah I think that should cover everything so hopefully you like this one and if you did like it please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
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
338
Jai hind is tutorial am going to discuss a program in question counting bags for the problem statement given unknown negative interior number name and for every numbers of indian research data from 129 for example de villiers number 15 it means number which ranges from 0257 what do you How to Calculate Number of Ways in the Representation Returns The Amazing So Let's Understand This Problem for Example T Input Number to Numbers from 2102 and Tours to Calculate Number of Ways in the Representation Subscribe Representation for Presentation 0 4 Times End 110 008 1000 CR Number One in 1000 Subscribe Number One End 218 Views on What Happens in Number 345 vs Number 90 Presentation 1000 Returns 90 Number 90 To A Politician Who Left Subscribe Button to 4 Only One Way John Isner Patience Problem Clear and How to Solve This Problem in time in one possibly in single subscribe to play list start with the simplest approach and similar to approach to run away from zero two given number and anti number encounter number of wave in the representation for example of a given number subscribe its 6085 60045 From zalul 0252 number account number of representation for the f-18 pass number to the representation for the f-18 pass number to the representation for the f-18 pass number to the number of the first number 200 run life in numbers quite u0 and when we find one in the representation increment divine of account and will reduce the number and where keep doing This Enter The Number Is Not Equal 2051 Adhir Awal Number 201 Miles 251 KM Return Gift Veer Awal Number One More Types In Teachers Day Whatsapp Decimal Part Strike Rate And Values ​​000 Return Also Account Awal Northern And Values ​​000 Return Also Account Awal Northern And Values ​​000 Return Also Account Awal Northern One Number To End Day Increase Number Stuart Is Value of Note 0212 Models Operator 2828 From This to Models 2030 This is a Condition Subscribe and Use This Number to Divide 251 More Account Number 90 is a Hero Turn on the Number of 101 Representation Supremacy One Similarly for Three That 939 22201 Squid Three Models to Soft Merge Give Women Tax Account Which Survey Increment Divine Male Supremacy Where And When Will Reduce The Number Neatly Divide Into Which One Adheen Na Wicket Vwe Romantic PF Account Notes2 And Finally Reduce The Number 900 Female For 1000 The Number Of Vwe To Similarly With U With For A Great Mood With Subscribe 1000 Results Subscribe Crush 3232 Number Running From Name 3232 Subscribe 1512 Subscribe 110 Approach Not Listen To Optimize Are Approach To Solve This Problem In One Time Complexity Let's Discuss How They Can Optimize Pages Approach In To-Do List Optimize Pages Approach In To-Do List Optimize Pages Approach In To-Do List One Decimal numbers in the representation of decimal numbers and observation and while doing all this presentation important points first number dial numbers and one for example 20430 and similarly divide of 98100 400 points 211 friends with 0n and numbers and 2nd important point acid Representation of the number and click the last one more last 60 years of equal to enter into water 98100 liquid witnesses who already knows not done in more subscribe 200 fear to talk about button representation s e no its last but not least equivalent to two a 300 also very important of the nation not third number this day last date of mind representation will give what is the meaning of this problem in one time complexity subscribe number 102 108 2340 1234 the five numb smoke condition specific number 201 simply return darkness of science one And values ​​phone and let's move to next values ​​phone and let's move to next values ​​phone and let's move to next important point statement day will declare a of eyes give number plus 2 and no representation of 1000 inform 2all words from to number incident to WhatsApp divine president way 205 plus teachers who have given number of president of way in The 12322 witches 800th the last date s one plus one witch S2 already discussed by doing a representation of number one neck blouse id 2nd in case of 10000 fluoride to 9 2012 0 461 most 2051 that 9th has this number five world and road show affidavit field Bye to sweetest to so I know the number of present in the representation of wave in third shift improve last date as one more subscribe Video subscribe complexity subscription more pure word this video channel for programming videos subscribe our YouTube channel subscribe like this video thank you
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
62
in this video we'll be going over unique paths so a robot is located at the top left corner of m times n grid marks start in the diagram below so the robot is here the robot can move either down or right at any point in time the robot is trying to reach the bottom right corner of the grid mark finish in the diagram how many possible unique paths are there so we're trying to start from the row back and try to reach here and the grid is three times seven basically three rows and then seven columns there will be 28 unique paths let's go over the dot process so we are trying to reach from top left corner to bottom right corner this is the same as going from bottom right corner to top left corner so instead of we're trying to go from here to here we'll be going from here to here instead and we are giving three rows and seven columns or m and n we can start with m n and then we're trying to reach one at one because if this is three here then this is two this is one so we're currently at row one here if your start and the column is going to be we're trying to reach column one because if this is seven we have six five four three two one so the moment we hit row one and column one we have found one possible path we will be starting from the cell at n and then we will try to find the number of unique paths to the cell 1-1 we will first implement a brute force recursive approach in each of the recursive call we will have two choices we can either move upward or move leftward we will want to find the total number of unique paths from both choices now let's go over to pseudocode so we're going to implement the recursive approach first now we're going to ask ourselves what parameters do we need it's going to be m the current row and n the current column then what's the base case is when we've reached the top left corner to our robot so if m n is equal to zero uh is equal to one then we can return we found one possible path we can return one if n or n is equal to zero this means we have went up we have went out bound to here or to the left side because we're only allowed to move upward so we can we may hit out of bound to these cells and we're only moving to the left side when we get when we hit out bound to d cells here so if mon is out of bound we can return zero we fail to find a path then each of the recursive call we will recursively find the number of paths past one if we move leftward now if we move leftward that means our column is decreasing so it's gonna column minus one then recursively find the number of paths if we move upward that means our row is decremented by one decremented is decremented by one then we can return the total number of paths going leftward and the total number of paths going upward and that's our result let's go over the time and space complexity so the time complexity is equal to of 2 to the m plus n where m and n are the input values and this is because each recursive call we have two choices and a depth of m plus n our space complexity is also equal to of n plus n this is because of the recursive call stack memory so we have recursive call stack memory now let's go over the code so let's first go over a base case so m is equal to one and n let's go to one then we can return one we have found one possible path on the top left corner if m is equal to zero or n is equal to zero then we have went out of bounds over return zero we have failed to find a path then we want to find the number of unique paths going leftward plus the number of unique paths going upward this approach is not efficient enough and will result in to ever and then in the next video we'll be going over the memorization approach that will optimize the brute force recursive approach so this solution is not efficient enough and will result in teal error but we will optimize this using memorization in the next video let me know if any questions in the comment section below like and subscribe for more videos that will help you pass a technical interview i upload videos every day and if there are any topics you want to cover let me know in the comments section below
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
125
Hello friends, welcome to the new video, question number 125 is on the loot court, Velvet is the name of the first in Rome, this is the question of this level, this question is basically of the springs category, you will get an interview with the talent from the string, it is okay with the name, let's start the question. The string given is to tell whether it is a belt paint rom, is it a balance rom or not. Let us first take some examples of rom like you are seeing. The first back pain is from the string. It will be read from the front, it will be bob, this hair will grow from the back. You will see that the second one is also a palladum string and the third one is also a painting. If you do not know but end drop then I will tell you that the first character is equal to the less character, the second last character is equal to your second character and the third last character is equal to your third character so this is Before the method, there are these ROM settings and what is given in the question. In the question, first terms and check have to be given. Mixing is given and tell whether it is velvet print ROM or not then it is ok. A strange, you will see, you will check and tell you. But it is passed with some conditions, the first condition is that the alphanumeric that has to be considered is just the meaning of this, what does this mean, capital A small baby capital A small and capital middle small also means all these characters 1234, so this is all we have to consider, extra. Character like special comma is controlled by not taking it in Ignore case meaning if big and small are equal then we can assume that if you ignore it in the house then you have to ignore it. In the midst of contact with people, small and big should be equal. So when we compare the comeback in this small capital, there will be no problem, so first of all, I am seeing that if I drink this, first of all, I will take it as step one, this is my spring, you assume this and I am my string gas. First of all, I should convert all the capital letters that I am seeing, I should make them all small so that I can do this hard match, so that all the letters are small so that there is no problem, okay, after that, if I build the string, then this is my remaining trick. In that time, I should remove all this, okay, I should remove all these special characters and space, then after that, I can check my painters easily, then we will beat, we will also name this, so you saw this confusing setting was given to it, shot. We made it in this way and now you can first check these ROMs, so first how do we check that Bigg Boss, let's quickly see, you will match this last character with the first character, EDM, second class and third AC with third class. Meet us, basically we will walk in the loop till half, that means we will only coat half and half, this etc., this trick, this man will this etc., this trick, this man will this etc., this trick, this man will match the springs, then the way you will see, it will move forward in the same way, in this way we will continue to move forward from here also. So we will come to the center on time, if all these matches are taking place, we will do the position sperm, we will reach the pintro, we have to write the chords with simple calendars, just toss the train first and make it such that we can check it, so first do it in lower case. Let's quickly take the function of 80's that by using this we convert it into lower case. Okay, now what will we do? Cut it. I told you that you have to make this trick in which all these characters are director special characters, this is Chrome, you have to remove the space. So, this trick of yours will have to be run completely once and if you have to remove it, then how will we do the remote? By removing it, if we delete all this and create a new one, then how will we create a new one, if we have this, we will put this face. Will not consider, then we will see, we will write, then see this friends, then it is visible, then if it will be useful to me, then I will call, ignore it or space, then next, we will copy this one, so we will keep copying in this manner, so what to copy in this? Which is our character, it should be either a digit or a letter and then we will copy it below. Okay, let's code that there is a function of tractor class, very good, use it, you will see that it should be a digit, we have to take digital, okay, and Second, what was to be checked ? There is a digit at this position. In a second, I had to check ? There is a digit at this position. In a second, I had to check ? There is a digit at this position. In a second, I had to check what letter is at this position. So, I pick it up from here till here and copy it and check this letter. This is a function, so whatever letters and numbers there will be in this. We will get to know all of them and using them we will create a new team, so I declare that StringBuilder will have a little performance, let's name it B. Okay, and let's create a new Spring Builder. Okay, this is how we created it. Now what can we do, if a number comes or a character comes, a digit comes or a letter comes, then we keep painting in our builder so that our new stretchy is being made, so in this way we have processed this trick and made it, so finally. Now, even if these people are finished, what will you get, which is 20 fur in buildwar in FD, in this we will get this movie, when Meena had processed this, we will get this movie, now you can check the screen that Petrol is very basic, first we will write the checking cord, which you will find in many places, we do not run it in the entire string, basically a beans have to be checked, neither in the middle, we have to make a spring in this, parents and check. So we will run it completely on 20 in this way that we will see once and basically we will check it till half, meaning this part is equal to this part is ok, we will not run the first character with lakhs, we will run it till half inch. The work will be done, the code of very common calendars, you will vote everywhere like this, then what is the size of the last index of the prisoner, if I do the last interview and see, then the last friends, my anything lens - is made, if my last index is then lens - is made, if my last index is then lens - is made, if my last index is then If I check that the first index is safe till the last, then something like this will happen, if i is equal to two then i is in the first ROM, ok, we don't have to do anything in this, ok, it is the last index, but what will happen next time, i will keep increasing. And you saw that this contact of ours is decreasing from the back, so if we make plus and minus high, then this is our one, from here it will decrease and one will go forward and there is nothing to do with equal, if the house is not equal, then we You will understand that this is a problem and here we will return the cards. Before checking it completely, before it is completely finished, we will end it from here. Okay, if it goes completely successfully and there is no match even once, then we will understand. In the end, whatever is ours, we have to return it is cash subsidy, just run this simple code once and compare and see, after beating some, we will mix, the village is being set and after submitting and see, it is simple. I am testing Velvet Balance ROM is getting accepted. See you again in new video. Will cover more questions. Will cover valid front ROM part to back. Thanks a lot for watching this video. Thank you very much.
Valid Palindrome
valid-palindrome
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_. **Example 1:** **Input:** s = "A man, a plan, a canal: Panama " **Output:** true **Explanation:** "amanaplanacanalpanama " is a palindrome. **Example 2:** **Input:** s = "race a car " **Output:** false **Explanation:** "raceacar " is not a palindrome. **Example 3:** **Input:** s = " " **Output:** true **Explanation:** s is an empty string " " after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. **Constraints:** * `1 <= s.length <= 2 * 105` * `s` consists only of printable ASCII characters.
null
Two Pointers,String
Easy
234,680,2130,2231
230
hi everyone welcome to my channel I am solving my little challenge and today is a day 20 and the problem is K the smallest element in binary search tree so we are given a binary search tree and we have to return the K the smallest element in that tree so like you may be familiar with the binary search tree so binary search tree has the property like all the nodes of the left side has the value less than that the root node and all the right subtree nodes has value greater than equal to the root nodes and this will follow and every route every nodes follow the same pattern so this is the given example 1 if let me draw here the example like 3 1 2 &amp; 4 so we will do the example like 3 1 2 &amp; 4 so we will do the example like 3 1 2 &amp; 4 so we will do that after search and try to use like go to the left node if we will do inorder traversal so inorder traversal we first which is the left child and then root node and then the right child so let me start from this is our root node 3 is our root node we are going to the left is it has a object yes it has then we will check for one is it has left hand no we will get the know then we will process the root itself so this will cross is 1 then we will go to the right supply child so right L is 2 so we will process 2 then we will back come to the hair 3 so we will process 3 then we will go to the air right child I change so like the important property of one is s 3 with in order to rustle we always get that all the values are in a sorted form so these are the inorder traversal of our first string let me write down the second tree in order to versal so ii 3 you know example 3 is inorder traversal is simply 1 2 3 4 5 every process in the same way so finding the key element for first example is the first element so first element is 1 is here so baby return 1 and for the examples and we have to find the third smallest element so third is shown as an a so what we will do for solving this problem we will iterate the inorder traversal and store all the values in one list or we can do achieve by constant let me start with first quick implementation and the easy limitation so I will use a list here to store my all the values of the nodes so this is list and it will be new ArrayList and then I will call my you till method or DFS in order or let me write in order name itself I will and also and after that once I here types so this is node and this is a list root is passed here beta is void in order and this should be what is the wrong line number 25 it is wrong in order let's try to compile it now it should ideally gone fine I guess so yes it is combining and what is actually let's try to test the second test where the K is 3 and that if for the different tree so this is our tree and we have to find that so for the same tree just find the fourth element for the smallest element as well so this is running it's judging and what is expected we are reading let's try to submit this is yes this is so this is the very basic simple solution for this example using the recursive approach and the in order so the time complexity for this solution if I wrote I will visit all the nodes in my tree so let's say n nodes and also in worst case the space complexity is not vessels we are restoring all then also space complexity of Hawaii so this is like
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
1,732
hey everyone uh today i'll be going over elite code 1732. uh find the highest altitude so this one is very easy but that doesn't mean i'm not going to do it and post it so basically there's a biker going on a road trip it consists of n plus one points at different altitudes a given array gain each gain of i represents the net gain and altitude between the points i and the one after it return the highest altitude it's a really confusing way to write it really all it means is you start off at zero each one is the step you make so you go negative five you go up one you go up five so after each climb or descent um what's the highest altitude we ever reached so we start at basically we start at zero so that's the highest altitude we've seen yet we return res and the algorithm is very simple we just go to the gain and also we want to keep track of our current altitudes i'm going to call this alt and we're going to go through each gain in game so basically i'm going to call this a climb so each climb in game basically we increment the current altitude so we're going to add the climb to altitude and then next what we want to do is we want to set the current max altitude so math.max whatever the current max math.max whatever the current max math.max whatever the current max altitude is and the current altitude so basically if we run this uh it should be right and we'll get that and we can probably submit it i actually haven't done this one a hundred percent and 84 so basically it's just like that and the reason why this works is because we're so just reiterating what's going on here is we have a max altitude and a current altitude we go through each climb in gain and we set the new max so we climb up or down and we set the new max altitude that we've ever seen so talking about time and space here time we have to go through every single step in gain we just have to do that so that's going to be o of n nothing else here max is o one this is o one so it's fine talking about space this is just o one uh the reason being uh we just have some constant variables here so it's just constant time for space so yeah very simple i hope this helped um i didn't really explain that much but i just wanted to walk through it and show you that it's very simple so thank you for watching i hope you appreciated this
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
258
so in today's video we are going to discuss lead code problem number 258 that is ADD digits so let's get started given an integer num repeatedly add all its digit until the result has only one digit and return it so in the example you can see we have been given one number that is 38 so we have to sum its digits which is 8 plus 3 that is 11 and then again we have to sum its digit 1 plus 1 that is two so we have to keep doing the sum of its digits until we get the one digit as the answer right so now let's understand how we are going to solve the problem so let me write it here for example it's 38 so 3 plus 8 that is 11 and then again 11 that is 1 plus 1 which is equal to 2 which is the answer so basically I have written this to make you unders how it is going to work so basically if the number is 0 so the sum is going to be 0 for 1 it is going to be 1 so 0 to 9 it is going to be the same digit so when the number is two digits right 1 plus 0 it will come as 1 plus 1 2 plus 1 3 4 5 6 7 8 9 and then again 9 plus 1 that is 10 1 plus 0 that is 1 right similarly for this two three four five six seven eight nine we are going to do here we are going to use the divisibility rule of nine so what does the divisibility rule of nine states that if any number is divisible by 9 digit is going to be 9 itself for example let's take this number 18 right so when you divide 18 by 9 what is the remainder zero correct so if 9 completely then what if what is the sum of its digits that is 1 plus 8 which is equal to 9 correct let's take some other example for example 27 so if it is 27 when you divide 27 by 9 you get remainder as 0 correct it is completely divisible so definitely some of its digits is going to be 9 for example 2 plus 7 that would be equals to 9 correct so that means we have got one case that its number is completely visible by 9 then definitely some of its digits is going to be 9 correct and also if number is going to be 0 then obviously some of its digits would be 0 itself so two cases we got how we are going to find the sum of all these digits that would be number divisible by 9 whatever the remainder we got for example let's take the number as 13. if you divide 13 by 9 what is the remainder is 4 then definitely what would be the sum 1 plus 3 which would be equals to 4 let's take some other examples also to understand this let's take some random number 23 right so when you divide 23 by 9 what do you get 9 3 is a 18 so what is the remainder that is 5 so that means some of its digits is going to be 5 2 plus 3 is 5. this is how we can find the sum of its digits in the three parts one if number is 0 what is going to be the sum would be 0 itself and second if number is completely divisible by 9 that means remainder you are getting is 0 then sum of its digit is going to be 9 itself and the third one if number is not 0 or number is not divisible by 9 then some of its digits is going to be num number divided by 9 and what whatever we get the remainder for example 25 when you divide 25 by 9 what you are going to get the remainder as 7 so that means some of its digits is going to be 7 2 plus 5 which is equals to 7. now let's write the solution for it so this is our class that is that digits now let's write the method that would be public static in add digits in Num and then if number is 0 then we are going to return 0 so we have excluded the case for 0 now otherwise what we are going to do we are going to return if number is completely divisible by 9 that means it is going to give the remainder as 0 then you have to return 9 otherwise it should be remainder num percent nine correct so this is how we are going to solve this problem now let's write the main method let's take the number as 38 let's write the print statement add digits num let's run the program and see the output so the output is 2 correct let's take some other big number let's take three eight five four so if the number is 3854 what is going to be the sum 3 plus 8 plus 5 plus 4 it would be 20 and then 2 plus 0 that is going to be 2 correct so now let's run the program and see the output for this one so the output is 2. so this is how we can solve this problem if you have any questions any doubts please let me know in the comment section don't forget to like share and subscribe our Channel thank you for watching
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
1,544
Hello hello everybody welcome to my channel it's all the record problem one too spring red problem 154 president problem solve in this problem give a string is of lower and upper case english latest if destroy subscribe between 20 - more than 200 subscribe between 20 - more than 200 subscribe between 20 - more than 200 plus one is the same letter But you can choose the correct but you can keep doing good and answers to give notice given the example subscribe this Hair Getting Addison character small and capital E saw between satisfying this condition in that case they can remove at this time characters once removed at this time Characters After Death From All The Lower Case Characters Laptop Suds Answer Is Liquid In Small Case Inch Example E Have A Piece First Big Guide Id Small And Capital Addition Will Have To Remember Once You Will Be Amazed To See Some Health Benefits To Remove Anc C S Well So After Visiting Chief Minister And Subscribe Will Solve This Problem Like This Anil Reddy String And Complete The Two Addition Characters So Let's Check For This Hair Bf2 Character Same Selection Tabs Example Subscribe 508 Character Tied Plus One Is Difficult Is Note Key Value Of Small Is 90 Is Video 6 To 9 News Room 302 IPC The Difference Between The Small Kids And Charitable Case Characters Is Thirty Two In Every Similar Repair Like A Small Bittu Capital V Pizza Sauce 3250 Make Use Of That Thing Souvenir Processing Let's Also Plus One Will compare like if character like character bhed like s.sc character like character bhed like s.sc character like character bhed like s.sc fiber is equal to fennel side plus 132 like subscribe and will always be a plus 32days character candy capital and second character can be small 100s if i plus one so ifin described in the to remove the Character Amazon River In The Process Of Sydney Process This Is Not Getting Same Hair Cutting This And Will Be Removed And You Will Imbibe Scan Right From Share subscribe comment Very Simple Five Valid For All Characters From 108 Loop Subscribe Ludhiana To English i plus knobs check this is not a good idea a plus 3202 start track i plus one and 32a also and dissatisfied man i don't like this and per person absolutely destroy the evil returns from the distic will benefit subscribe from two plus two subscribe from a Plus B Plus To The Return Of The Day The Sweetest Come Positive And Brave Solution Code Hai Member Jhala The Solution Saifi CBSE * Condition Member Jhala The Solution Saifi CBSE * Condition Member Jhala The Solution Saifi CBSE * Condition With And Also Alarm Set A Difference Between The Two So They Can Reduce To Like So They Can Reduce To Like So They Can Reduce To Like Ki Obscene Difference Between Disaai Faila Plus Characters Of Ki Shirdi Ki Equal Store 3257 Veeravar Compiled Radhe Ki Settings Accepted Member Approach Using Questions Basically How Do We Solid So Let's Understand Invitation Proceedings Of The Character Hair Oil Withdrawal Back To Back Side Subscribe On The Topic Subscribe Popup Will subscribe The Amazing Turn on the mode Defined contribution They will reply you from the pick Penis's second grand slam Subscribe to Bigg Boss with exactly this mentality Video Small Subscribe will continue to all Subscribe Solve soft characters directly A knotted call stack and lies with is trick plan width oh characters you see in the water can provide chapter note will check is stage show that and a pan math dot s lord of the daughter of a stagnant water active - current track is 32.5 with oh A Text Dhan Vansh After Win With This Will Check And Constructive Stock Plot Size That Is Crater 200 Catch All The Character Up And Stringbuilder So Let's Apna Delhi Distic Point Tours And Different Thursday Subscribe Stringbuilder Hua Na After That Vijay Simply Return Springboard is Thursday Sharing is the space complexities of immense wealth development council thanks for watching this Video then subscribe To My Channel Please subscribe thanks for watching this
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
123
what's up nerds welcome back to tee time with your favorite software engineer so i know i've been missing a while finally got my desk set up and like settled into my new job so i'm going to be making videos more often now um just preparing for interviews in general so today well actually first i wanted to mention we're doing a legal competition in my slack channel so it's got everyone super involved actually everybody's doing way more problems so i recommend joining that uh the link to the channel is in my description also subscribe if you guys haven't already i'm trying to hit 10 subscribers a day i think i'm at like five right now so i mean not growing very fast but whatever so today we have a tough problem it's uh this one's pretty tricky compared to the first two that i did videos on um so say you have an array for which the i element is the price of a given stock on day i design an algorithm to find the maximum profit you may complete at most two tr transactions and i realized i forgot to open my ipad so it's just like the other problems we can separately just uh we can only do two transactions and of course my ipad is not plugged in sorry guys it takes so much stuff to make a video nowadays so you may not engage in multiple transactions at the same time so we must like buy sock and then sell it before we buy another stock basically is what they're saying so that actually makes it like easier in my opinion so um here uh i'm guessing you'd buy zero and then sell four and buy three and buy er yeah would you buy buying day four so on day six then buying day seven oh so zero and three and then one and four okay so it gives you a total of six so basically we just gotta want to find the uh two biggest differences between the buy and sells um so where's my ipad it did not switch the ipad so let's think about how we want to do this let me move the ipad out of my video um basically we're going to want to have a let's think of it as a buy by one variable um and so this is going to be um we're going to want to do math.max of math.max of math.max of buy one or it's going to be um we're gonna so we're gonna loop through this array price of prices and so it's going to be since we're buying it's going to we're going to want to represent it as a negative number since we have to buy it we have to spend money so it's going to be negative price so price just representing one element in the array and then we're gonna wanna do profit one you can call this whatever this is going to represent um the profit from the first transaction so like the um yeah one of the two main transactions so we're going to want to do math.max of i believe it's math.max of i believe it's math.max of i believe it's profit one and we're going to want to do um so price minus no price it's going to be price plus buy one since buy one is um negative so we want to add that negative number because it's basically like subtracting the price i know that's a little confusing but that's how we're going to do it and so then we're going to have our second buy but to take into account our second buy we're going to have to account for the profit we make from the last transaction so um because we're the fourth variable we're going to have is going to be our total profit so we're going to want to keep track of the uh our profit from the first one and take it into account for our second buy i know this is confusing this actually took me quite a while to wrap my head around so if you guys don't pick it up right away don't blame yourselves um the intuition behind this is i mean i can't imagine coming up with this in like 30 minutes under pressure in an interview in my opinion so um for buy two we're gonna have uh buy two or it's going to be profit one um and it's gonna be i believe it's so we're gonna do minus by two is that right i don't know we're gonna have to debug it i honestly profit one so if we have profit one yeah because we have to um we have to notice it's supposed to be price minus price we have to subtract the price because we have to buy it again so we want to subtract that since we're going to be keeping track of our total profit and then finally here it's just going to be total profit and uh i believe price plus by two so um hopefully that made some sense i hope so let's create our variables so we're going to have it by one equals uh prices uh zero but we're going to do negative because remember we got to um subtract it we want to basically subtract it so let's add a negative and then so by two is going to be the same thing and uh so in profit one from our first transaction is just gonna be zero and our total profit is going to be zero as well and then let's just loop through our array prices and so um by one if we go let me pull this up so make it a little easier so you guys can still see that perfect math.max um uh so it's going to be uh it's always going to just be the variable itself we want to so basically we're just like updating it and it's going to be negative price because we have to buy it so think of it as like subtracting and then we have we want to update our profit one equals math.max one equals math.max one equals math.max of profit one and this is going to be price plus buy one correct yeah all right sweet and let me zoom out why is it i can't even see it all right that's a little better buy two equals math.max of buy two equals math.max of buy two equals math.max of buy two and it's going to be profit one minus price because we have to buy the stock again but we want to keep track of our profit that we've already made and this is going to be our total profit even though it's our second transaction so let's do math.max so let's do math.max so let's do math.max uh total profit so it's always the same variable followed by the what we're updating it possibly with so it's going to be price plus buy two and then we just want to return total profit uh what is it i honestly don't remember sweet okay so there you have it that's how you solve this problem uh so 98 don't worry about my memory it's getting worse every time i think the catch is messed up or something but so basically we're just looping through the array one time so it's oven um run time so linear runtime and constant space complexity because we didn't need any data structures or new arrays um so hopefully you guys understand that problem just uh re-watch the video if problem just uh re-watch the video if problem just uh re-watch the video if you have to i mean i haven't heard of anyone who like came up on the spot with this so don't beat yourself up too hard if you didn't and that's all i got for you guys hope you guys learned something and i'll see you in the next video and smash that like button if this video helped
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
1,748
hey everyone uh today i'll be going over lead code 1748 some of unique elements uh this one's a very easy one um and i'm probably just doing it just the most basic way possible but that doesn't mean i'm not going to make a video on it because we all start from somewhere and i'll try to explain it so anyways we're given some lists and we simply just sum up all the elements that are unique so they have to by unique they mean appearing exactly once so just return the sum of all those numbers so to keep to count each number we could do this a number of ways so we use a hash map and have the key be the number and the value be the count or if we look at the constraints the num is only ever between one and a hundred so let's just have a count array right let's go new in 101 because it'll represent zero to a hundred now what we want to do is just count each number so let's go through each number in nums and let's just simply increment the count right and then next what we want to do is we want to have some result here and we know we want to return it at the end and let's actually go like that and then what we want to do is we want to count all the unique elements or uh sum up all the unique elements so by unique what does that mean it means it appeared only once so that means that count should only be one for that number so now let's go through each count in counts and if it's a unique so if the count was one then we return that number and actually we don't want to do this because we want the number and the number is the index so let's go through this way and we use 101 because we know that it's bound to 101 and then let's just simply uh you know count the unique ones so if counts at i is equal to one so that means it would appear exactly once and let's just uh add to the result the number and then let's run this like such so it's like there let's submit this and yeah pretty good 71 so yeah very basic all we're doing is just counting the currents uh finding all the ones within occurrence of one making sure it's unique then summing up the numbers so talking about time and space complexity of time is actually uh well time is actually oven because we have to go through every count in nums and there might be like a million of the same numbers so time is o of n uh space is over the reason why space is o1 is because it's bound to a fixed value and that's due to the constraint right here if there wasn't this constraint then we'd have to use a hash map and the space would be o n but it's actually over so yeah thank you for watching i know this was really simple but yeah thank you
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
462
hello everyone welcome to learn overflow in this video we will discuss about the another liquid problem there is a minimum moves to equal array elements and this is the second part of the question so other elements two uh this is a middle level question we'll understand what this question is trying to say and then we'll try to figure out what the solution uh what kind of solution we may have over here so we'll look into the all possible solutions and then we'll ultimately find out what is the best case we can go ahead with before starting this video make sure to subscribe this channel if you haven't already also comment down your thoughts or any questions if you come across throughout this video i'll be happy to help you out in the comments as well so let's start this video so the questions is given an integer array nums of size n so there's an integer array for us nums and it's of size n and this return like we need to return the minimum number of moves required to make all array elements equal okay so it has some elements and we need to find out the minimum number of moves uh using which we can make all arrow elements equal okay that's good to know like nestor says in one move you can increment or decrement an element uh of the array by one okay so one move means we can increment any element or we can decrement any alloy element by one okay next we can have like uh like the three sets the test cases are designed so that the answer fits in 32-bit integer so uh that's the return 32-bit integer so uh that's the return 32-bit integer so uh that's the return type is there so how many moves will be there will be less than 30 like 32-bit there will be less than 30 like 32-bit there will be less than 30 like 32-bit integer so you can be rest assured about what the return type and the methods will be there okay now let's understand this examples given to us and let's try to find out what exactly we are supposed to do over here right so here we have an arms that is one two and three being the array elements and it seems like there should be two moves so uh moving ahead it says like only two moves are needed uh like each move being increment or decrement of one element so what are the two moves first from one to three we increment one and we make it two okay then from two to three uh we decrement three and make it two so we have actually two steps one in is in increment of the element one and decrement of the element three so uh those two moves and make it all the elements uh equal right so uh just looking at this think carefully a solution that might come into your mind is that uh what we are trying to do is more or less finding an average of the uh places like average of all the values we have right it's like if it was something like say you wanted to make all the elements as three okay then how many moves you would have required like increment one two times to make it three then increment two one times to make it three right so that would uh result us you know like a more uh value so that's not the minimum number of moves right and also in the first case if you wanted to make all the elements as one so in that case also you could find that the value we have is not exactly what we are looking for i mean uh if we wanted to decrement all the elements to 2 1 then also we will find that there will be three moves right so the minimum number of move will be uh more or less looking towards the average of one two three is two itself so we incremented one and we decremented to uh three so that's the idea of this question okay so uh but think carefully average is the condition that we are more or less looking for but we need to think is there any other way that might help us in reducing the complexity and also what's the complexity we are coming across when you're thinking of average right let's try to understand and let's see if we have any other things we can think of but before then let's understand other examples that is a 1 10 2 and 9. so now how do you do that because it was a sorted array you then you simply came across the 1 plus 2 plus 3 divided by 3 is more or less 2 is the answer and you found out answer to it now if we are like one ten two and nine is it like any value that we don't need to increment or don't need to decrement we need to change all the values here to come across a value that is uh like to the value wire like minimum number of moves are required right so what can be something like that it can something like this first find the average here so what can be 11 then uh and 9 20 22 so average will be more or less 11 right so if the average is 11 then in the first case we need to increment 10 then we need to increment one uh it's not 11 as a value but it's like more like we need to find like the common point where more or less everything will be sorted it's not eleven why it's not eleven like the sum is 22 and we should divide it by four so it's more like five point five will be the value around five point five right so let's say we take it as five or we take it as 6 the answer should uh be same actually because uh it will be like incrementing or decrementing either way the answer should be same so it's like one plus there will be four steps and then uh like i'm taking it to five okay and then if it's like 10 plus there will be like we should subtract something ten plus minus five uh five steps will be required so that is nine step required and then two take it to five uh exactly take it to five then that will require us three moves and then nine uh minus four steps so do this uh subtraction so this two uh substitutes seven and there's nine seven and nine is 16 see that's the answer we are looking forward so we find that the answer is looking towards the average right now how will you do that to do an average look uh there's a problem in this particular approach i will tell you in a moment to do an average you need to first look through the whole loop right and then find out what we need to look the whole loop and then find out the sum actually and then with the divide it with the total number of elements in the array okay so find out the sum and divide it with the total number of elements and then again look through the uh like look through the whole array and then try to find these values and then find the sum of this value like this is not the simplest way we can we think anything simpler than this so yes we can do something say we have 1 10 2 and 9 okay what can we do let's sort the error whatever it give us like 1 then it gives 2 then it gives us 9 and then it gives us 10 okay so that's what we sorted that so arrays dot sort is something that helps us with this so in the first case that is the sort will be of n log n complexity okay now see what we can exactly do we need to do the average right so we can do something immediately what i mean is without refreshing the whole array like after sorting without traversing the whole array can i do something like this 10 minus 1 by 2 why i'm doing this it's more like see average will be we have the extreme ends at both times right so extreme like ten plus one eleven by two is more or less five okay and then we go ahead with something like two plus nine by two something like that and that's the idea actually behind this question if you remember there's an important question actually the question uh goes ahead with something like uh meeting point problem if you uh remember this is a very popular question so the meeting point problem is like uh there are a few people's like few friends whose uh home are at different locations in a city and they want to meet at a certain place right so in a certain place they want to meet and they don't want like anyone don't want to travel a larger distance unnecessarily okay so it's something like we find out the like median of the particular like all the locations and then we subtract the median from each of the places right so that was the idea behind that so this question is exactly similar to meeting point problem so here we need to find the minimum number of moves okay so like on the meeting problem we had something like what is the minimum a distance each of like total minimum total distance we had to cover something like that was there in the bidding point problem if you don't know make more problem make sure you search it over the google will find out like it's a pretty popular question okay now what exactly we are trying to do over this question is like uh say i'm just let me explain this again so say you have one and ten like being two extreme ends so anyways you either need to increment one to some extent and you do it decrement one to like you decrement 10 to some extra so how many steps you need to uh like cover up in the total case in total place one will increase to some value in between this right one will increment and fifteen will decrement so more or less we are traveling the like say only single person is traveling then it's travelling the focal distance covered by both will be uh like more or less this is going here this is the total distance being traveled so how much is this so that's basically 10 and 10 minus one so that's the nine is being the total distance traveled by uh both of these extremes so both extremes should travel to some total distance so how this is actually working i'll tell you how what this works working or not let's see like 2 and 9 is there so uh subtract 2 from nine and we find that we find our answer of seven right so nine plus seven it ultimately ends up in a sixteen we have over here right so how this is actually working this is working in the formula like we are finding the average we have a sorted array and we are finding the average uh in like every case what's the average is more or less like five if i take it average being five so one needs to take four step and ten has to come back five steps right so ultimately how much distance is covered by both of them is the distance between them right so say there are two friends you and your friend is there and you both wanna like meet at a point like whatever point it is right uh so what needs to be done say the point is somewhere between uh like in between the your home like you're both of your home and you're somewhere in between your home so what will happen you will move uh some steps towards that location and your friend will come uh towards the location right so like to that toothpaste and towards the location so what is the total distance covered total this is covered at the actual distance between you your home and your friend's home right your friend is moving back some step and you are moving uh forward some total distances some of the uh steps taken by both of you so that's how it actually worked or like one needs to increment to some values and 10 needs to decrement to some values so it's more or less you can say we actually ended up having uh like total distance being the exact value like we ended up reaching a median point like midpoint uh over here right so this is the basic idea behind this see on this case the first complexity would be going ahead with uh n log n like we need to sort the array and the next complexity will be a pretty smaller complexity that is we are traveling only half diary look whatever be it whatever long array we have we are traveling half direct so we are not traveling n elements rather we are traveling half of the elements so if it says like n is nums dot length and numbers are left maybe 10 to the power 5 just consider you are traveling 10 to the power 5 and in between you just traveled only 5 into 10 to the power 2 all right isn't it like well you just traveled half the distance so that's how you just reduce the complexity to many folds actually so that's the idea behind these questions and that would be the easiest explanation i think uh i can tell you and to do this is like simple array the first will sort uh and then we will uh run a wireless and count the total values we have over here okay so let's uh go ahead and write some code yes so you can see exactly that this is a three millisecond solution and more or less you will find that based on when you run this code and how you run this code it may end up like three two or one somewhere sometime it may end up in zero millisecond as well so that's how a small uh error you can think in that time frame but it's the model is the fastest solution you can come across so what exactly we did we just sorted the array then took two pointers being one being the zeroth element like one at the extreme ends okay both the xml and other being the maximum element that we have in the j position the num dot length minus one okay and that then we have a final answer element so this answer is like we initialize it to 0 so initially we are considering that there's zero moves that we need to do okay and then what we're doing we are just checking that while i less than j so that means while uh like while i is less than j so we are ensuring that we traverse half there okay and what are you doing we are just adding the difference between i and j to our answer array okay and then incrementing i and decrementing j so higher it is less we will keep on adding the differences and finally we'll find the answer and you will find this is the solution that works for us as well so this is like exactly the question if you remember the meeting point problem i told you a few minutes back exactly that kind of question that's a meeting point problem okay and uh you can actually think of it in that manner so i hope i can uh make you understand how what this question is and how you can solve this question and how you should think on finding a solution of this question right so uh if you haven't subscribed to this channel make sure you subscribe the channel and also uh make sure you just comment down any thoughts just come across or if you just couldn't understand any parts of it comment on your thoughts and also like this video i that gives me a motivation to make more such videos and uh so thank you all for watching this video i hope to see you soon in my next video as well thank you you
Minimum Moves to Equal Array Elements II
minimum-moves-to-equal-array-elements-ii
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. In one move, you can increment or decrement an element of the array by `1`. Test cases are designed so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 2 **Explanation:** Only two moves are needed (remember each move increments or decrements one element): \[1,2,3\] => \[2,2,3\] => \[2,2,2\] **Example 2:** **Input:** nums = \[1,10,2,9\] **Output:** 16 **Constraints:** * `n == nums.length` * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Math,Sorting
Medium
296,453,2160,2290
752
hey everybody this is larry this is june 4th of the june the code daily challenge uh hit the like button in the subscribe button join me on discord let me know what you think about today uh and the daily challenge and stuff like that uh yeah i usually solve these live so it's a little bit slow you know well fast forward or whatever you need to do uh i trust you can do the right thing uh okay so you have a lock in front of you four circular wheels you have ten slots you're going up and down nine goes to zero goes no okay dead ends okay so you cannot get on any of them and okay so i mean this is gonna be um this is basically a shortest path problem where you're trying to go from zero to the target and you can move one digit at a time so that's pretty much it uh and of course there are some places where you cannot be you know meaning the dead ends and that's pretty much it so and being the shortest path where it's unrated uh you know the graph is unrated so that's just first search so that's pretty much how i'm going to do it and of course if we cannot reach the target we just return negative one um yeah i mean and you know if you uh wanna you know because they're four digits i keep saying you know as well so i don't make this one guys but i hope you're counting at home uh but yeah but as you can see there are four digits and you're going from a standard zero to nine so that means that there will be at most ten thousand states uh so that means that breakfast search is going to be fast enough is the answer because refers to usually one in linear time unless you have a lot of edges i mean it still runs in linear time but it's all v plus d where in this case each node has was it eight edges or something uh like for you digit one up one down so that's gonna be you know eight times v at most give or take um or we well the number of edges is gonna be eight times we so it's gonna be like you know o of v plus d is going to be o of 9 we say which is all we um so that's how i did uh figure out that it's going to be fast enough uh it's going to be you know linear time in terms of well it's going to be like over ten thousand roughly instead of over ten thousand square or something like that right so that's basically the idea um okay so let's get started on the coding i'm gonna start with a q in python it is a deck which is the same as a queue except for you could do it make changes to both ends because it's uh a deck a double feel what the deck stands for but yeah it's just a deck um and we always start at zero so let's append zero and how do we want to represent the states and let's just do it with a string a little bit that one yeah let's just do it with a string it's fine no i mean that's just zero fine um okay uh and then distant we just need a hash table to keep track of the distance um okay and in this case we also want to add the step of zero is equal to zero and then now while length of q is greater than zero we get the current price is equal to q dot pop left uh we also have a list of dead ends which we can pre-process dead ends which we can pre-process dead ends which we can pre-process in a set so let's just call it that ends you go to set up this um just to make it a little bit faster um actually and we let's just make it into a number as well so because these are strings so yeah so you do something like that right and then now for each number we want to increment in a easy in an easy way you want to um the thing is the thing that's a little bit tricky is to wrap around um you know so yeah so it will just convert it word it a lot there's a lot of maps well not a lot of them apps there's a lot of operations but um but it's fine so yeah so we'll convert this into in a way of four elements say is that weird i'm trying to think that i really want to do this but it's fine if it runs out of time you know we'll uh look it up current positions divided by just say 10 to the power of index and then mod 10 something like that right just to get the digits i guess we can actually do this in one line right so okay so now we have all the current positions and we can print it out just to be sure that i didn't mess this up this is a you know by default just have zero yep okay and then now we just do for each right four index in range of four we now want to try drive for delta is equal to um oh just in range in negative one and one okay so yeah let's see next positions is to go to the uh how did i even type that so we make a copy of positions and then we do next positions of index delta and then now and this is probably pretty clunky i probably could have done this a little bit better i don't know maybe it's a little bit late it's 3 18 i'm tired um a.m so okay so now we i'm tired um a.m so okay so now we i'm tired um a.m so okay so now we convert it back so yeah how do you is it a criminal someone was trying to teach me how to do this so i'm trying to learn something new as well so yeah so accumulate exposition basically so i'm learning does it is as well uh it should take i don't think this is quite right it takes a function hmm yeah that should have two values i don't know which one is the accumulator actually so i have to see okay so let's just see someone like that right and yeah let's just point it out real quick because i'm just really tired right now okay that didn't help i'm thinking reduce which is really what i was thinking about but somehow we do is does it the other way okay fine learning something new today as well which is always nice don't know if i would use this but uh yeah that doesn't look that good though oh this is silly the way that i did it i mean to do put this here okay so this is at least somewhat good okay this has to be here as well i am being very silly today you know this is pretty straightforward okay so this is what i want kind of except for the negative one we want to mod it by uh by 10. in python it automatically converts it to a nine i think could be wrong on that one if not then yeah okay so yeah so now we have all this whoo that just took way too much effort to write but yeah if this is not in dead end then we can move on to the next then we can add this to the list to the q and then we set the distance to kill as you go to the current plus one and then at the very end we just return distant of target and that's it um well if target not in distance then we return negative one otherwise return distance target i mean that should be good enough um note that it was a little bit slow in the middle of it hopefully that uh became okay at the end if it's too slow we'll see because it's still judging for some reason am i printing somewhere no i took that out but sometimes when you leave your print statements in uh the system does take more time and oh i forgot one thing that's why but yeah when i'm really i don't know what's going on with me lately or the last two weeks maybe or something it wasn't that long but yeah wait did i miss something how come this is impossible i have to take a look at it maybe i misunderstood something because this oh because the that's weird that 0 is okay because it starts there okay but yeah but i also forgot to check that it is um not in distance this should be good except for maybe this case because it's a special case that's weird well okay huh let's take a quick look so we do construct stuff but only for the i'm really confused about this output because oh did it just cut itself after the first one okay maybe that's fair but what's the first target zero two hmm how did that happen did we get the right answer before maybe i didn't test it actually oh wait no because it ran in from the loop so we didn't get it but hmm what did that happen how does it not go to 0202 for six okay i'm just being very sloppy somewhere probably because i think this is roughly right but not actually right clearly okay six you can actually go back to six real quick so it goes to moves correctly three moves it moves correctly so what is going on even the four moves it moves correctly in here and oh i'm just being dumb okay because target is a string right and i did not convert it so i basically i need to convert this into a number so that's just i am really sloppy today my bad friends okay so at least this is better maybe um i mean it's not worse than before i mean this one was expected because we don't we need to handle it but the four is a little bit awkward well i mean the four means that is not handling the dead end correctly i think yeah because that's probably the minimum number of moves but what is hmm how did it get to this is so awkward this is so easy but i'm just having a rough time at it uh huh let's just let the code do it for me uh was it two or two so the curve is that with typo somewhere why is this so weird this is what happens when you don't know what you're doing oh just i need to reverse this that's why because i'm doing the thing um i'm shifting it incorrectly in the wrong direction that's why okay that is silly i am just being careless and i'm learning i mean i was trying to learn something but then i think i did a little bit carelessly um okay this is gonna be very uh computationally dumb but it still looks okay uh now we just have to remove this one and the timing is not great because we do a lot of operations we you can probably write this in a cleaner way but yeah but okay let's just give a submit i'm not happy with the time per se usually i'm not that sensitive to it but this i do a lot of silly things so if it gets time limit exceeded i probably ex um i probably deserve it even though uh you know the big o is going to be the same uh and this the big o is going to be o of v plus e because this is a breadth first search and we here is n which is equal to 10 000 i think i saw oh yeah because there's five digits or four digits and was ten thousand um we don't even care about the dead ends because it's just an old one look up after the pre the original processing so you do have to process it um so you have to go through it so if you have n is you go to well in this case just four from zero to one thousand or ten thousand uh maybe ten dollars about how you wanna define it and m is equal to the number of death ends then this is gonna be of n plus m because as we see v is um e is equal to eight times n and that's going to be say 880 k and but that's also going to be o of 9 times n which is of n as we talked about before and that's just on this part that's just breakfast search standard stuff i mean i know that there is a couple of weirdness here i'm gonna hand wave it for today uh you can if you really want to dig deep into it let me know in the comments but yeah but with respect to getting the you know setting the restricted areas the dead ends and that's pretty much it uh in terms of space it's also going to be linear space because or that depends on what we mean by linear space it's going to be oh of 10 000 space which is the size of the number of states um and yeah and of course we reprocess the dead end in a set so that looks a bit cheaper and take it as you will but yeah but it's going to be also of n plus m space um yeah uh that's all i have for this one uh let me know what you think hit the like button in the subscribe button and i'll see y'all tomorrow and have a great weekend if i don't or have a great weekend even if i do uh see you later bye
Open the Lock
ip-to-cidr
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot. The lock initially starts at `'0000'`, a string representing the state of the 4 wheels. You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. **Example 1:** **Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 " **Output:** 6 **Explanation:** A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ". Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102 ". **Example 2:** **Input:** deadends = \[ "8888 "\], target = "0009 " **Output:** 1 **Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ". **Example 3:** **Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 " **Output:** -1 **Explanation:** We cannot reach the target without getting stuck. **Constraints:** * `1 <= deadends.length <= 500` * `deadends[i].length == 4` * `target.length == 4` * target **will not be** in the list `deadends`. * `target` and `deadends[i]` consist of digits only.
Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n.
String,Bit Manipulation
Medium
93,468
86
hello friends uh welcome to my channel let's have a look at problem 86 partition list so this is a daily challenge problem so here in this video we're going to share first a broad first solution and then we trust form the brute force solution in a better format so this problem is the following given the head of linked list and a value x partition it such that all nodes less than x comes before nodes greater than or equal to x so we should preserve the original relative order of the nodes in each of the two partitions so here are examples so let's have a look at the questions so the first constraint says that maybe the linked list is empty because the number node can be zero and the length of the link linked list is um bounded above by 200 so the value for a node is between negative 100 and positive 100 and the value x is between negative 200 and positive 200. so with that said let's first look at a brute force plural false solution so this peripheral solution will help us build intuition so what we are going to do is that we want to traverse this linked list and then put the larger value and smaller value into two separate lists and then we drawn the join them um by making a number of lists and list node objects so with that said let's do this carry out this procedure so first i'm going to introduce a small smaller let's see larger so that's our two lists which are to hold the node values so then we are going to traverse this linked list so this is a very standard so well hide then we are going to check if had value is less than x or greater than or equal to x so if it's less than x we're going to add this value to the smaller list so append so hide value so let's do something like this so value equals head value and if value less than x then we're going to add this value and otherwise we're going to add it to the larger list so then we're going to reset the state of head by head next so that's it for this traversal so let me make some remark so here is a linear traversal this is very standard so next we drawn the corresponding nodes for that purpose let's first make a dominoed for convenience so list node as specified here so it's list node and we're going to use a value that is so let me use next to 101 because smaller than negative 100 and then we're going to traverse the smaller and large list so then we're going to do thin things like for um x in smaller plus this larger so then we're going to um make a note let's see temp equals list node so the value will be the x and then we're going to set the dummy next to temp and then let me do things like this maybe it's better current equals dummy and then we're going to set current next equals this temp and current equals temp so then that's it then we just need to uh return the dummy next so notice that we do this because the height can be representing a empty list so let's test a special case yeah it passes this special case and then let's check a generic case yeah it also passes the generic keys and now let's do another format so this format actually just translates this brute force solution but maybe more suited to the problem or more satisfactory let's call this one solution we want and then so this the brute force solution we work at the value level so work at value level so now let's do a solution so which we work at a node level so with the above solution i guess the second solution is a question uh clustered forward i'm going to specify uh two node so small dummy so let's call it this node so again i'm going to use a value negative 1 in view of this constraint and then argus also going to set a larger large so let's see large dummy so i'm going to use again value c negative 1 0 1 then we can actually do the iteration stem parallel to the above solution so well head then i'm going to check um the value so if head value is less than x then we're going to connect this height note to a small right so we're going to make small next equals height and then we move forward small to be small next in other words the current height and otherwise we're going to make large next equals this height in other words we connect the current height with the larger and then what we're going to do is that we set large equals large next and then after this conditions check we're going to reset the height to be the next pointer so with that said actually we finished the while loop parallel to the brute force solution and then what we are going to do is that we want to set the current state of small and to be the um the large the dummy large dummy next right so first i'm going to do something like this if large so the current stage is not um now so we're going to set large next to the now so this if actually plays a role so let's prevent possible circles so that's this done see we can make a connection right so if small then what we're going to do is that we connect the end of the smaller linked list with the one has large values that is large dummy next so that's this done so we're going to return dummy next so the use of dummy note is a standard practice for problems involving linked list so this is the second solution so now let's do a special case check so dummy is not defined let's see oh i need to use dummy small tommy small is not a small dummy all right so let's check again oh yeah it passes the special case now let's do a generic case check yeah it passes the generic case so i guess that's it for this problem so basically we present two formats of solutions the first one is very beautiful but it serves to understand the logic of the problem and then we translate the peripheral solution to a solution that will work at node level so in between actually we used a dominoed for convenience so this is a common practice for problems involving linked list so that's it for this video thank you very much
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
123
hello everyone so let's talk about baseline to buy and sell stock three so in this question you can only do a transaction in most two right so which means two for buy two for sale so in this idea um what you can actually do is you can use a method from 121 so 121 is actually you only buy one time and sell one time right so use this idea and then we implement better so let's talk about how do we actually do it so we have a buy in buy so i'm gonna say buy one and buy two and also sell one and cell two so just follow along so if i didn't buy anything yet which is i would set it to integer the minimum value so since the by two i haven't buy it so let's set it to the minimum value so what happened to sell default value is definitely zero right because i haven't sell anything because i didn't buy how to excel right so i would just diplo to zero all right you follow along then i'm going to traverse the prices array so price prices so when i say buy one right buy one can actually be either i'm currently buying oh i'm going to buy this stock so the stock if i buy the stock right and lose the money so which is negative so i would be initial like 3 and infinity right uh negative infinity minimum value negative infinity and negative three right so y will become negative three and cell that one is equal to maximum or sell one that i sell the stock right so which means i buy it and i sell at this price so even though i update for three right when i sell the stock at this moment it's definitely zero right why buy one is negative three and the price is three negative three plus three is zero so you don't actually update your cell one be honest and this current uh index for loop so sensing four by two so the larger are pretty exactly the same but you just have to think about it so by two is you still i mean you still uh take the money from your pocket so you losing money but you don't forget you need to uh keep your money on the first sale right so it sells one minus price because when you want to buy the second stock you need money to buy it right if you don't take money from your property how do you buy stuff so that's the idea and also cell 2 is becoming the max cell 2 and using the by 2 plus price so this is straightforward right so sell i sell stock right how do i sell i found my buy so i buy the stuff so i sell the stock at this price so the price from buy two and the price for prices for the for loop is different okay so uh just think about it you definitely know what i meant so when i return right i can either return the cell one or cell two it just depends which profit which property is the maximum so this is uh cell one this is two uh cell two is not cell two doesn't mean you have a maximum profit all the time maybe someone does right before the for loop right so this is just how you actually avoid the h case so let's just run it and see if i have uh complete yes okay so let's talk about time and space for the space is constant you know right for the time it's all the fun right because you traverse every single element in the for loop so it's all of um for time constant for the space and that will be the solution for this question and good luck
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
1,603
hey there today we'll solve one of the little problem design parking system it's problem number 1603 so in the given part parking system there is three types of vehicle that can come big small and medium size so for example in this case if big and medium is allocated then begin medium will be allowed and then remaining will not be allowed the size uh is respectively one two and three means big medium and small a car can only park in the parking space of its car type okay so only in given car type a car will be parked if there is no space then will return false and if there is space then will run true so let's try to add code for it so first of all let's initialize all these variables and then medium in the constructor let's initialize this and this not small equal to small that depends on the content and available space so i'll add if conditions if big greater than zero and our type equal to one small medium then i'll check with two and here i'll check medium and else small i'll check and small size 3 turn true else i'll return false now as soon as a card is allocated i need to make sure that uh this way its space will be review its if the so when we allocate it we assign one so we need to and if it is zero it means new car cannot be allocated so i'll just do make minus then medium minus and in this case minus means if it is already occupied it will make it zero so that new car cannot become cannot be allocated let's see if it works i cannot find symbol card type okay here it's part time variable name is different yeah so it is faster than the other online services and uh that's how we solve this problem so once again if you didn't understand the problem just go through this description and uh this is the solution for this problem was for designing the parking system from lake code 1603 problem statement so i hope uh this helps and if you think the videos are helpful do like the video and subscribe to the channel
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
1,642
hello guys welcome to another video in the series of coding we are going to do the problem which is called furthest building you can reach let's try to take an example to understand this so we are given some input of numbers okay by the way this question is a very beautiful diagram so let me explain with the help of this diagram this is a very beautiful diagram which they have taken okay so we have taken this area of numbers so first building is at a height of four second is at a height of two third is at a height of seven and so on so this represents the height of the buildings now they have given that the number of bricks is 5 and the number of ladders is equal to 1 right so in this question according to this information bricks and ladders you have to try to reach as many buildings as you can reach now let's consider the first building has a height of four okay second building has a height of two so for jumping from first to second building you don't need any brick or any ladder because you can easily jump right but to jump from a building which has a lower height than the previous building okay so let me say let's say that array of i is the current building an area of i plus 1 is the next building if this condition is true that is your current building is less than the adjacent building then only you need either a brick or you need a ladder okay but you have to use them optimally because you have to try to reach as far as you can this is the aim of the question okay so from jumping from four to two does not require any brick on ladder because uh this condition is not true right 4 is greater than 2 but for jumping from 2 to 7 jumping for 2 to 7 notice here we need to place some bricks then only we can equal the height and we can reach this so we are going to uh use either bricks or ladder we will see how to solve the problem but here what they are doing they are placing five bricks so we can see one two three four five bricks are placed here and after that we are able to match this height and we are able to go here right now for jumping from seven to six again you don't need any effort at all because seven is greater than six next you have six to nine so this height is six this height is nine again you need some effort because you need to uh place something but you had only five bricks you already use your fabrics here so now you have to use a ladder so in this case after this when we come here we use a ladder now we had only one ladder even the ladder is exhausted so this is the last height at which you can reach after this you cannot reach so you have to return that this building is the end building right so this has a very beautiful animation that's why i use this okay now let's uh come to our board so how do we solve this question right so we just saw the example okay let's try to take some other example to try to see how we can solve this question okay let me assume that uh the number of ladders that i have is let's say 10 here and let's say uh sorry the number of bricks i have is 10 let me rewrite it the number of bricks that i have is 10 and let's say the number of ladders i have is equal to 2 and this is the array given right this is also one of the test cases let's try to see how we can solve it for this so first we have a building of height 4 okay next we have a building of height 12 next we have a building of height 2. next we have a building of height 7 okay next we have a building of height 3 next we have a building of height 18 next we have a building of height 20 next we have a building of height 3 and finally we have a building of height 19 okay we have to return the maximum index that we can reach so let's start from the very beginning uh let's see how we can build approach so the simplest approach or the logic let's see what hint they have given right that hint is going to be very useful assume the problem is to check whether you can reach the last building or not okay let's go to hindu you will have to do a set of jumps and choose for each whether to do it using a ladder of bricks it's always optimal to use ladders in the largest jumps okay this is a very good hint we have to use ladders for the last just jump hydrate on the buildings maintaining the largest jump and the sum of the remaining ones so far and stop whenever the sum exceeds b okay so why do you have to use ladders for the largest jumps let's see okay let's start um first we have the building with height four next we have a building with height twelve okay let's say we don't want to use ladders let's say we want to use bricks only okay let's start using bricks and then we'll understand why we need ladders where we need ladder so let me place eight bricks here because we need at least eight bricks to math height so initially i have only ten bricks i have used eight bricks now i have only two bricks right so now i am able to reach here okay now let's continue from height to l to two we can easily jump the there is the height uh 12 is greater than two so we don't need any brick or any ladder so we can just continue we can just go forward now from height two to seven you again need uh bricks or ladder but you see you have only two bricks remaining because you already used eight bricks here so now the number of bricks you have is only two okay so now in this case you cannot use brick because if you use brick you will need five bricks to fit here why five because two plus five is equal to seven right the height difference is equal to five so you need five bricks but you don't have five bricks you have only two bricks so you have no choice but you will have to place a ladder here okay now what is the number of ladders so the number of ladders initially we had two ladders but now we have only one ladder because we have used one ladder okay now we have jumped here let's continue from jumping from 7 to 3 you don't need any brick or any ladder because 7 is greater than 3 right simple logic you don't need any brick or ladder for greater heights so let's just continue now from 3 to 18 again um you either you need 15 bricks right but obviously you don't have 15 bricks you have only two bricks right so in this case we will have to use a ladder we have no choice but we'll use a ladder now the number of ladders also we have is now for jumping from 18 to 20 you need two bricks so we will use these two bricks right so we can use these two bricks and we can come here now for jumping from 20 to 2 okay you um uh for jumping from 20 to 3 you don't need any brick or ladders you can easily jump now jumping from 3 to 19 you have no more bricks no more ladders the number of bricks and ladders you have a zero so you cannot uh you know reach this height so the last final index is this which is this index 0 1 2 3 4 5 6 7 and 7 so i need to use ladder okay let me take one example let's say i have buildings like this okay something like this right so the difference here is one the difference here is three the difference here is eight okay let's say i have lot of ladders and lot of brick so where will i optimally try to place ladders now see if let's say i'm giving given that i have only one ladder where will i try to place it okay so here in this case i will try to place ladder where i have the most where i needed the most and i needed the most where i have the most number of uh height difference because if i place the ladder here right then even with these lower numbers let's say i have sufficient number of breaks okay let's say i have five bricks sufficient bricks then i can place bricks in the lower numbers and i can cover it using my bricks and i can finally reach till the end but if i use ladder okay let's say in this example if any if i have only one ladder and if i don't use it here let's say i try to use it at some other position let's say i try to use ladder here and let's say i have only five bricks then in this case for this i'll be able to use a brick for this i'll be able to use bricks i have used four bricks i have only one brick remaining but using one brick i cannot cover eight distance right so this is the intuition if i use ladder here instead of using here then in that this case i can reach only up to this distance but you can see that if we use ladder optimally at the last position right i mean at the position with the highest height difference then in that case you can use a five bricks here if you have five bricks you can use the five bricks to cover these places or these heights and you can reach the last value so it's always better to use a ladder at the highest positions okay now once we have understood this now we will take in final example how we are going to solve this problem and then we can move forward to coding it so let's say we have let me take one example so we have 3 4 10 5 7 15 okay 12 16 11 and let's say 12 okay now let's again start let's say the number of bricks that we have is equal to okay let's say again 12 and let's say the number of ladders that we have is equal to 2 okay we are supposed to use uh very optimally so let's try to see how we can do that so first let me note the difference so first we will start iterating over there and we will note the difference is 1 here difference is 6 here difference is not relevant because 10 is greater than 5 here difference is 2 here difference is 8 here difference is not relevant here difference is 4 here difference is not relevant and here difference is 1. now what i am going to do as i start iterating right i am going to reduce my breaks so let me start from the very first the number of bricks that i have is 12 okay first i iterate i need one ring so let me do one thing let me try to place a brick there so now the number of bricks become eleven now let's iterate here i need six bricks let me try to use it number of bricks become equal to 5 now let me try to iterate here i need 2 bricks so the number of bricks become equal to 3 now when i iterate here if i reduce the bricks 3 minus 8 will become equal to minus 5 so i cannot continue with bricks right i if i have negative bricks it makes no sense so here within somewhere here i need to place a ladder and because if i don't place a ladder here within somewhere i will not be able to continue i'm getting a negative answer so where do i place the ladder as we discussed we are going to place the ladder in the maximum height difference so we will also use a priority queue data structure so let me also write it to store the maximum height difference okay so let's start from the very beginning so we are going to use a priority queue first number is one so i'm going to push one in the priority as we iterate through this we'll push the numbers next we see a six so what i'm going to do i'm going to change my priority queue and i'm going to place six first and then i'm going to place one okay next i see two so i'm going to place two six then two then one then i see eight i'm going to place eight then six then two then now i see that my brick has become negative means i should use a ladder if i don't use a ladder i will not be able to go further right i will stop at this index so in this case what i will do i will notice the maximum height and i will place a ladder there so maximum height is 8 so i have to place a ladder there so i will add 8 i had already subtracted 8 once so i will add 8 back so the number of bricks that i have is 3 because at the height difference 8 i am not using a brick that's why i have added 8 back i am not going to use brick i am rather going to use a ladder so again you see the number of bricks has become positive we can continue and here i am going to place a ladder here at this eight height i am going to place a ladder and the number of ladders will become equal to one okay now let me continue let's continue so next time we can continue here because for this we don't need any brick or ladder now we see the height difference 4 right so again let me erase 3 minus 4 will become equal to minus 1 again the number of bricks is negative right again the number of bricks becomes negative here that means uh that i cannot um continue i will have to first of all store um this value 4 and now i will have to see that the break is negative that means i cannot continue without using a ladder if i have a ladder otherwise i have to stop right so now i have a ladder so it's amazing i still have one ladder i can use it where will i use i will use at the highest difference is 6 right so that means i will come here and i will place a ladder here i am going to use at this maximum position because it is most beneficial to place with the highest height difference so i am going to pop this and because when i do this i am going to get six extra bricks back right if i would have taken any other quantity apart from six i would have got less bricks back but because i am using a ladder at the highest height difference then i am getting six bricks back so the number of bricks is plus six minus 1 which is equal to 5 right so i have total number of 5 bricks remaining i can still continue so let me continue i can continue here now i need only one height difference so 5 minus 1 is equal to 4 so finally i am going to reach till the last index and in this case we can return the last index as the answer now let's move forward to coding this so let me take one example and let's try to code this so the first thing that we know is we have to iterate over all the values in our heights array so let us start with that so we have to first of all note the differences right now what are the differences between two adjacent values right so we can note the difference so let us say that heights of okay let me take i plus 1 minus heights of i so here let me say i am starting my i from here i equal to 0 in this case i am noting the difference between 12 and 4 right 12 minus 4 is equal to 8 now if this difference is positive right if difference is positive then in this case i need to use a brick or ladder so let me write i have to use a brick or ladder without which i cannot jump okay so let's consider uh the case so first what we are going to do we are just going to do bricks minus is equal to uh difference right okay by the way just one quick thing when we are doing i plus 1 right here we have to give minus 1 because otherwise it will go out of bounds right so the last value that you have to check is for this i here right so okay this is just one quick note okay now let's continue so breaks minus is equal to difference we were writing this line so in this case what we are doing let us say the number of bricks initially we have is equal to 10 now 10 minus difference so 10 minus 8 will be equal to 2 so let me write this so the number of bricks that you have after this condition is going to be equal to 2 okay now let's continue and then we'll further build the logic so let's go to the next index you are seeing the difference between uh 2 and 12 will be negative right if you take the difference 2 minus 12 will be equal to minus 10 so it's negative that means you don't need any brick or ladder you can just continue okay let's just continue next you see the difference between 2 and 7 if you take 7 minus 2 is going to be equal to 5 so in this case again you need you have to use a brick or ladder so let's come here the number of bricks that you have remaining is 2 right if you have to use a brick in this case what will happen 2 minus 5 will be equal to minus 3 so after this condition what happens is the number of bricks that you will have will be equal to minus three now it turns negative so this is a problem so you'll have to give a condition if the number of bricks it has turned negative in this case you have to go back and try to put a ladder somewhere right so this is the simple condition so let's see where we can put a ladder for that you need a priority queue data structure right so let me write here in the next line so you need priority queue to determine where to put a ladder you have to put a ladder the maximum height difference so let me write the syntax for priority queue let me call it pq okay it's a maxi by default so this is the syntax okay now what we are going to do in the priority queue we are going to push the difference along with it okay so that's why i'm giving this line we are going to push the difference so that later we can use it when the number of bricks turns negative okay so if i have given this condition what is this extra line going to do i am going to store the differences right so what was the first difference was eight so i am going to store eight in my priority queue okay next difference it doesn't matter to us we are not going to enter into this condition now this difference is five so i am also going to store five in the priority queue so now because of this simple line i am storing the differences eight and five in the priority queue what is the use of this now i can go back and place a ladder somewhere how can i go back and place a ladder so if i am going to place a ladder that means i get back some bricks this is the entire logic if i place a ladder i am going to get back some bricks okay so let me write a variable get back these many breaks okay and what is that value that is going to be the topmost value of a priority queue you can see that in the priority queue i have stored the differences eight and five i am going to get back eight bricks so this is a very beautiful logic i am going to get back eight bricks right so now i can add that to my answer so the number of bricks will be equal to how many bricks i am going to get back bricks okay so the number of bricks had turned negative right so the number of bricks had become equal to minus 3 right now i am going to add 8 bricks i am going to get back 8 bricks because i am going to place a ladder there i'm not going to use 8 bricks i'm going to place a ladder there this is the logic so minus 3 plus 8 will become equal to 5 so after this line the number of bricks that will become equal to 5 but my number of ladders will decrement because i am going to use a ladder there i am going to use a ladder here so after this condition what will be the number of ladders i had two ladders initially but after this condition the number of ladders that i have will become equal to one right i have only one ladder but i have been successfully able to use that one ladder and now i have remaining also one ladder and i can continue with my problem okay now let's continue further so now let's go to the next i value so the number of bricks that we have is equal to 5 and the number of ladders we have is equal to 1 these are my values in the priority queue let's continue in the next value so next i we can see is equal to 7 so 7 if you see the difference between 3 and 7 is equal to minus 4 it is negative we need not pay any differ any attention to this value because uh because we don't need a brick or a ladder here let's continue now the difference between 3 and 18 okay 18 minus 3 is equal to 15 okay by the way one thing which i forgot to do when i wrote these three lines because i'm using a ladder i have already placed a ladder there so i will also have to pop this value from the priority queue okay forgot to do this so before continuing let me just pop this valley from the priority queue right so when i pop this the priority queue has only five okay because i have already um placed a ladder at this position when the difference was eight so i also need to pop it from the priority queue okay and now let's continue further so the difference between three and eighteen is equal to fifteen right so i use fifteen now uh the number of bricks that i have is only 5. if i use 15 when i have only 5 bricks then it's going to turn negative right i cannot do this that means this is not allowed okay this is not going to be allowed so first of all i place the difference in my priority queue so um the difference is 15 i place 15 in the priority queue now i'll see if i can use a ladder why do i need to use a ladder because the number of bricks have turned negative that means i can no longer use bricks i need to place a ladder somewhere okay so where i'm going to place i'm going to get the topmost value what is the topmost value top most value is 15 now how many bricks will i get back since the number of bricks have become minus 10 i can get back 15 bricks which is the top most value so again the number of bricks becomes equal to 5 so i have 5 bricks you see the number of bricks again became positive after i got back these bricks and now the number of ladders has become equal to 0 okay now i'm going to pop this topmost value from the priority queue i have only 5 remaining in the priority queue right okay so and the number of bricks is equal to 5 okay let me continue now after this let's go to the next i value the difference between 18 and 20 is equal to 2 right difference is 2 the difference is 2 ah the number of bricks we have is 5 minus 2 is equal to 3. so i can first of all just push 2 in the priority queue because 2 is the difference and the number of bricks that i have remaining is equal to 3 let me uh let me just write 3 here right the number of bricks that i have is 3 i will not enter into this condition because i don't have negative number of bricks i still have positive number of bricks so i'm going to continue let me just continue now the difference between 20 and 3 it doesn't matter to us right because 20 is greater than 3 so let me continue now the difference between 19 and 3 is equal to 16 okay it's equal to 16 so it's great uh the difference i have is 16 but the number of bricks that i have is only three right so first of all if i do 3 minus 16 it's going to give me minus 13 right it's going to give me minus 13 so i cannot use a brick here because i need to use 16 bricks but i have only three bits first of all i will place 16 in the priority queue okay and i will try to get back bricks what is the top most value is 16 so the bricks has become equal to minus 13 plus 16 has become equal to um 3 okay and the number of ladders is 0. now if you enter into this condition number of ladders is 0 you are making ladders as negative okay this is wrong because if you don't have a ladder how are you using a ladder right so this is totally wrong you cannot use a ladder right so here we can give a condition check if ladders is negative then in that case you can just return i which is the current index because in this case what we are doing see you need 16 bricks because the difference is 16 but you have only three bricks since you are not able to use three bricks to get a difference to reach a height difference of 16 you try to use a ladder but you cannot use a ladder because you don't have ladder is 0 ladder cannot become negative so you'll have to give a condition check so when we give this condition check before entering into any of these lines itself we can give a condition check so if ladders is negative you can return i that means bricks is also negative ladders is also negative so in this case we are going to return i you cannot reach after this index so this i value is going to be our answer what is that value 0 1 2 3 4 5 6 7 so in this case your answer is going to be 7 and you can return that as answer okay that's it this is the simple entire code with the dry run okay now let me do one thing let me make i several by the way ladders is not just a negative lattice is less than equal to zero when the number of ladders become equal to zero also you cannot uh make it negative right so this is the condition that i have to give okay now let me make i as my global variable so that in the end if we are able to ever reach all the values i can just return i okay that's it this is the simple code now let's run and see if it's working so it's working let's submit and see if it's going to work for all the test cases this is the code okay let me do one thing let's see if it worked yes it worked thank you for being patient and listening
Furthest Building You Can Reach
water-bottles
You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`. You start your journey from building `0` and move to the next building by possibly using bricks or ladders. While moving from building `i` to building `i+1` (**0-indexed**), * If the current building's height is **greater than or equal** to the next building's height, you do **not** need a ladder or bricks. * If the current building's height is **less than** the next building's height, you can either use **one ladder** or `(h[i+1] - h[i])` **bricks**. _Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally._ **Example 1:** **Input:** heights = \[4,2,7,6,9,14,12\], bricks = 5, ladders = 1 **Output:** 4 **Explanation:** Starting at building 0, you can follow these steps: - Go to building 1 without using ladders nor bricks since 4 >= 2. - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. - Go to building 3 without using ladders nor bricks since 7 >= 6. - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. It is impossible to go beyond building 4 because you do not have any more bricks or ladders. **Example 2:** **Input:** heights = \[4,12,2,7,3,18,20,3,19\], bricks = 10, ladders = 2 **Output:** 7 **Example 3:** **Input:** heights = \[14,3,19,3\], bricks = 17, ladders = 0 **Output:** 3 **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 106` * `0 <= bricks <= 109` * `0 <= ladders <= heights.length`
Simulate the process until there are not enough empty bottles for even one full bottle of water.
Math,Simulation
Easy
null
725
200 Bluetooth is the problem No fog Play list How to split into quantity Milenge is the length of parts Rate occupations 75 Question is the language of Bagasi College and school name and password Have size different by more than 1000 Subscribe Return of the day That Sonakshi has this problem Settings Open Example2 Zinc List Cheese 123 456 Subscribe And Tay Jatin Software To Fix Difficult English Into Three Parts Like One Does One Part In The Sense Of Different Size For All Elements Size Chest Size Condition Mein 12345 Speech After Entering Subsidy From Bigg Boss Members Basic Problems Statement Solitaire Dainik Jagran and How to Solve This Problem and Drop Earing Divided into Three Parts of Delhi Government in the Fight for Minister and Party and Subscribe to this Channel Shampoo's To-Do List into Three Shampoo's To-Do List into Three Shampoo's To-Do List into Three Parts Interested Hours Click on To-Do List Heer Voor Oo Parts Interested Hours Click on To-Do List Heer Voor Oo In Sab Business Tha Na Pluto Ki Chamak Ko Maximum Si Na Example Ko Subscribe Now To Receive Key And Gypsy Is Cream Jai Hind Strip Previous Song Vikram Singh Aur Darshanshastri Lalchand System Un More subscribe and subscribe the Channel and tap On a tree 123 to me send a message on install New Delhi if it has happened then it will be sent to a customer in Greater Noida Android phone number 9483 one day you are marching a rich man is a then here to use one small arch And Jeera Saunf 125 Do subscribe to World Channel Share and subscribe the Channel Ko hai to agar kisi aur in two variable Kankamal Jain hai ka record suit karun zero do the whole dharan 202 current kaun length hai ki vikalp hai next kamal length Till then we sleep by wp rich in amlo a flu vid oo hai tu sign doctor hijra ki a list a lesson white scientifically spa Thursday happened Arvind declaring rule chances less language change do enter ke include hello friends basically na Thursday morning clip Arts Result 991 A Times And The K Songs Play Song A Times Of Var Ke Ramgarh Chain Aa Ki A Ka Ras Ki Shankh Saath Ki Bigg Boss Tiger Ki Yeh Mangha Long Chain Hai A Movie Motors Size Pet After Defeat Know How To Play List 10 Interesting Facts on the intervening list and Pink where is Karna Vikal tank in Kamrup campus? No I am in human letter has come in this list. Notification of voting rate of burning club will collect. Previous date is 222 Name is Are you with current list of accused Next Question Of Presents Quite Vinya Beating The Number Of Freedom Tourist The Next Notification Is To Support His Highest Peak Into Thin Work Encroachment To Games Fitting Healthy Media To Switch Board The Result Of Class Fourth Position On Here I Am Range And Demand One Day When The Number Is Said to reduce the light of Kargil war current will be conducted on that health kitni ganga setting together agri list will return Dixit went back innovative content code obscene clipping is submitted that reddy success in this poster 98% be that reddy success in this poster 98% be that reddy success in this poster 98% be renewed listen safe sex please Like button and subscribe our video please like this video and subscribe the channel more interesting updates coming very soon
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
221
okay guys so let's solve today let's go daily problem it is lit code number 221 question number and it is maximal square so this is the question you are given an m into n m binary matrix played with 0 and 1 find the largest square content only once and return its area so i have taken this example number one so let's get back okay so before that uh you can see there is two or two into two matrix means for area is four so one is this red one and another is this one so the answer is four and for the example number two there is only two one d uh one by one matrix so one into one is only one and the for the third example is only a single zero there is no one so it is zero okay so the constant let's look at the constant uh here m comma n is between 1 to 300 and of course matrix of i and j is only 0 or 1 so let's approach to it this is a pretty good question you can see here the like amount is like quite high or quite high and don't know why people dislike this okay let back to the our main topic uh first of all what should be our approach how to think uh so let me explain the approach like why it work uh what it is and then i will explain how why it work okay so let me given the index 0 zero one two three four one two three okay sorry for the belt handwriting uh i am using my mouse okay so here for any instant let's take a instance of this one let's take the cell this one for this cell what we need to calculate like we need to check if this cell and this cell uh contain one what i mean is uh in this example uh this cell is not one and this cell is not one so what happen uh they have a store zero because it is not a matrix so it is not an a square so this cell contained a dp state of zero uh and it said digital content also dp state of zero uh but this cell will contain a dp state of one so we have to check all the three side cell like i minus their cell i plus j cell and i minus one uh comma j minus one cell content or one okay or if not then we will take the minimum of all this three all this retail uh three cell and just simply add one with it like for this cell it will be zero a minimum of this three cell is zero so this shall contain the value of one okay now let's take an another example of like for this cell so you can better understand because it is has all three side as one so this will store one uh from this cell it will store one and from this cell it is also store one and it is already one okay so for this cell i can check that uh this cell can uh this is the salvage content one this is the also cell which contain one and this is the also with content one okay so one and so this is one we have to take a minimum every time it is not it doesn't matter on it if it is a zero or one because if i take zero 0 and 1 and its minimum so it always written as 0 and if there is a suppose there is a 1 it also returns it all it always written one okay so i will take i will uh so i will give you an example of like um something one two and one and it will always return one because why we need one why don't why uh do not we need to i will show you in just next example okay so here it is one and minimum of these three is one and this cell also contain one so it is one plus one it is two okay so i'll just write directly to here okay this is one so now if i remove all this then we have found a square uh let me draw it by green color this cell okay and all the value inside is here it contain one it contain also and then this minimum plus it is i explain it is two okay now uh if i take this cell so it is a nice example like for this part why we need minimum why will not take maximum or something like so let uh just see for this one this is 0 and here it is 1 or as it is 0 so in means whenever you come there is 0 just simply put a 0 in the dp state ok so it is the 0 1 and it is minimum is zero so and this part is one so zero plus one is one so i put here one now it is s similar like this two one order it doesn't matter here so what it is now if i take two and i add one for this one so it will be three but uh but it is of length two only because a square because uh it is this part it is 3 but from this area it is not 38 is only 2 because it is a 0 so it will be false that's why and we need a square not a rectangle um if we need a rectangle here then i can say that we can take it but um regardless we do not we don't need a rectangle so we just uh take the minimum so here it is one and it is two and the minimum is one so let me erase this sorry okay so yeah so it is one plus and this is one and it is two so what will be our uh like how it work is uh as i explained you of whenever you encounter with a zero in a cell just simply put a zero for the dp i have taken this as i just the number which i am writing in green it is our dp only i just mention it here to clarify it like for this uh it is one and so we just uh put here one it is the base case i will show you in the code and it is the zero if you oh if you familiar with uh dp and solve some questions like zero and abstract then it will very much familiar to you um okay so it is zero and zero so we starting you will feel like this then okay sorry where is the option yeah and this is one for one we can feel it like if i is equals to c equals to zero or j is equals to zero okay just fill dp of i j is equals to matrix of i j i can write it matte i and this is the base case i will show you in this code in the code in later part of the video and then now completely go through uh a dry run okay so i just remove all this mesh here nice uh yeah now for this cell i have uh this is the base case so it will automatically fill this and this cell okay now we can start from here so what will uh what i said you have to check the diagonal up uh the up and the left most cell okay this three cell so i can write as dp like uh let me type only okay so i can write it like something dp of i j is equals to and i have told you to we have to take the minimum of or these three cell so i can say that tp of i sorry mean of dp of i a j minus 1 for the left side left cell and dp of i minus 1 and j and d p off okay this is just an um logo please don't go with the syntax i've encoded in c plus j minus one nice and because it is uh it is zero so oh this is this condition if the cell is if matrix i will write a mathematic i j is sorry j is equals to 1 for 1 but here we can see that it is zero so for zero we have another uh another condition and if it is one so we can add as i say we have to add one here in the here example i can say i have said that oh one mini minimum is one and you have found a one so this one okay you have to because the answer here is two its length should be two so it is two and if the mat of i j is equal to equals to zero just do simple thing dp of ie and tp of j is equals to zero because if it is a zero for here and then we cannot consider a square from this side and means it will not form this four cell will not form a square it always it is zero so um that's why so it is a simple case okay the main cases can is this one there now let's dry run through it okay as i explain you uh for zero just directly put a zero then this will it and then this cell then one zero then we'll check this one zero and the minimum is zero so zero and four one we can add plus one like this so it is well one zero plus one for this cell also it is zero 1 0 so it is 0 plus 1 it is 1 oops ok 0 1 so it will be 0 plus 1 so 1 here 1 0 1 is minimum is 0 and 1 0 plus 1 is 1 here also same 1 0 1 minimum is 0 plus 1 is 1 now 1 minimum is 1 and 1 plus 1 is 2 one two uh so minimum is one and one plus one is two look here two one between this two means that your upper two cell and left two cell are of length two and it means this box is form a rectangle okay and for these two it means like uh this one and this box because two means length of left side two and upper also two okay ah just let me remove it and it is gonna we can zero just simply put a zero we in and one second control is zero we simply put a zero we encounter with one so two one zero minimum is zero plus one is one and it is zero so simply put a 0 okay now we also maintain a variable like suppose we can take a len variable and we can every time we go through these cells we can written like max of length comma dp of i j okay so what happen uh here the length value it will change to zero to two and here also it will change to two so when length is two we can know area is area of a square is nothing but length square so or i can say length into length and i can write it l into l so we can return length into then in our answer and it will give us 2 to 4 okay so let's get back to our oh so let's code it okay for this time i am using the tabulation method that it is a very quite simple to analyze a tabulation method for this problem uh so i can first find out what is the length of the row it will be matrix of zero dot sorry matrix dot size comma c equals to matrix of zero dot size oops oh and dppr i can initialize and dp array okay now i can iterate through the row and column and i equals to 0 is less than r i plus i and j equals to 0 is less than c plus j so first of all our base case if i is equal to equals to 0 or j is equal to equals to 0 that means this the first column or first row if we are in the first column first or just put accordingly like what i mean is that simply put dp of i j equals to whatever the value like if it is one so it will be always a square of one size only and because there is no in there is no squaring up and for similar here if it is one or zero so simply put it zero so i can write it okay this will absorb a character not integer so i can use it on the matrix of i j minus zero okay so it will be it will change the integer into the character into the integer so if it is one so one minus zero this will gives an integer i and if it is zero then it will be written an integer zero hope though you will know this kind of stuff okay so next condition else if matrix of i j is equals to let's say zero okay so then just simply do one thing dp of i j is equals to zero okay uh i have told you to take a length variable length and initialize it to zero because if there is no square then its length is zero and the area of also zero and whenever you uh you are putting some value in the dp so kindly check if it is length is max of length dp of i and j okay and here it doesn't require it because uh if lane is zero or so it will it is remain zero so i will not write it here now else means or if the matrix contain a value one okay so we just simply what i will do dp of i j equals to 1 plus min of okay you can write like this dp of i j minus 1 comma d p of i minus 1 j minus 1 okay and here also put the same thing okay so it will check the left most cell this one check the uppermost cell upper ones and operation and this will the diagonal upper okay this is cool this will and we will get a length not the area so we will return length into length because area is simply just side into central and until then okay i hope it will any typo let's check let's try okay it is accepting let's submit it okay 1699.31 1699.31 1699.31 percent faster nice okay so hope you guys will have enjoyed it and thank you for your watch bye have a nice day
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
5
boom what up Zayn here and we are going to be doing the longest palindromic substring I hope I'm pronouncing that right so basically we're given a string called s in this case and we just have to figure out the characters that are symmetrical the longest consecutive characters are symmetrical so it's much easier just to look at an example so Bab you can see that these are both the it's the same backwards and forwards like racecar or mom or dad and we have and there's you can look up tons of pulling rooms online by the way if you're interested and we also have this one that's backwards and forwards the same thing so this would be oh actually so just Bebe is repeating so Bibi would be the longest palindromic substring so okay first thing we want to do is we want to convert this string into a vector so that we can have access to the different characters by their index and just make it a little easier to work with I might go ahead and save that so we will say let huge s we'll just call it s I don't know equals so we need to convert this to characters convert collect that those characters into a vector and we'll have to explicitly declare the type to be a vector of characters so this should be a vector now and so now we can treat it just like a regular vector alright so how we want to do this is we're gonna have to iterate through each character of the string so there's not really a whole lot of speed-up we can do so basically we're of speed-up we can do so basically we're of speed-up we can do so basically we're just gonna start at the first character and look to the right look to the left see if there's any see if they're matching and then go outward but first we have to also plan for the case when there's two in a row like here there's two in a row so the a is not equal to s but this is still pool in dream because it's still symmetrical a is still symmetrical so this would still be a pool in Durham SaaS so we'll just as many characters as there are in a row that are the same we'll go ahead and skip those as well if that makes sense they'll make more sense when you see it probably sort of like the kalindra okay so we'll iterate I from 0 to the length of s and so that will just I will just give us the index of every character in s and so then we will we'll need to index in the indices will need a left and a right so left will be the index of the left character right Willie the index of the right character and we'll just go outwards making sure that it's all symmetrical and the left will equal I and then also right will equal I and that also needs to be mutable and so let's just go ahead and return an empty string just to shut up the compile the syntax highlighting and so that we can get rid of those thank you okay and so now we need to see all the characters in a row so basically for D that would be one but also if there's two A's in a row that would that could also be the center so we'll say while JIT while the right is less than the length of the string so let's just go ahead and set a variable length to the length of the string just so that we don't have to type that out all the time now I'm not sure there might be a performance increase by not having by assigning it to a variable rather than retrieving that from the memory in that string in the string struct so I'm not sure so we'll say wall right is less than length and actually write plus 1 because we're going to be testing the character to the right and the right eye plus oh I'm sorry the S at position right plus 1 is equal to left is equal to s at left and so that way we'll just skip all the sinner characters that are identical and then we'll and then that will be our center and then we'll iterate check the outward to see if those are symmetrical so we'll see if s is symmetrical to s then we'll check if d is symmetrical to s that Nexus and it's not so the longest Poland room would be SaaS ok oops and then while that is true we'll just increment right so we'll move the right window to the right one and then we'll also say while right plus 1 is less than length and while left is greater than 0 and while s right plus 1 is equal to s o s left minus 1 so then we're just comparing those outer so we if I is 2 and or if left is 2 and right is 3 we would check if 4 and 1 are identical which they are it's and so that's what that code is doing and then if they are then we will just increment the right one and we will also increment the that's a little light left one okay and so that will expand our window by the one because we've checked that they're symmetrical so we'll also need to track the start and the end so we'll say well said the end start is zero and the end is also zero so we'll start with an empty substring essentially oh well we'll get an empty subject so then we'll return the character so we'll collect the characters into a string from the start to the end and that will be our return value so we'll say s from start - return value so we'll say s from start - return value so we'll say s from start - and up including the end and we'll enter the leg and this will that should test that there should automatically make that a string then if this substring is longer than the current length which the start and end will change so start - end start and end will change so start - end start and end will change so start - end will be the length then we will set the new start in to the right and the left of the current iteration so we'll say if right - left is greater than and - start right - left is greater than and - start right - left is greater than and - start then the new end will be V right and the new start will be vu left and so that should work for us so we'll just run our test cases ok so a little logical error there we should actually be going backwards with the left so that was the problem so we'll try it now and we're passing all the tests this doesn't actually need to be mutable so we can just change that and now let's go ahead and paste it into the code so we'll paste that in and run it and check our scores last time I got four milliseconds let's see if I can beat it I'm the best so no I can't and that's because for an empty string this isn't going to work for an empty string because we go from zero to zero and this is inclusive of the end so we can just say if we'll say it when equals zero then return just an empty string and we'll copy that to our problem direct submission and that's fine this doesn't matter anyway so we'll see if that works and it does and we got a 2-0 and it does and we got a 2-0 and it does and we got a 2-0 milliseconds and two megabytes so I think is the this is the lowest theoretical amount of memory it could possibly take up so we're the best yet again should we even bother looking at anyone elses okay I guess we'll just we'll take a look at one other one okay dynamic programming so this is gonna use a lot of memory to do that because he's keeping track yet every single index not really necessary so this guy is doing a different one for even in a different one for odd which we kind of solved that with this one lot or this these three lines of code by go ahead and expanding the center so we kind of avoided that problem which is nice and let's see okay well we are the best and we've beaten everyone else again so I'm happy with that and in our next episode we're gonna be looking at zigzag conversion so join me in the next video please hit the thumbs up like subscribe whatever
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
1,775
hey what's up guys this is chung here so uh 1775 equal sum arrays with minimum number of operations so given like two arrays of integers numbers one and nums two and the only consisting the only possible numbers is from one to six and in one operations you can change any integers values in any of the arrays to any number between one to six and you need to return the minimum number of operations required to make the sum of values uh numbs 1 equals to the sum of num2 okay and return minus 1 if it's not possible to do it so for example right we have num1 num2 here so the answer for this one is 3 because um basically so the total for numbers 1 is what do we have 1 plus 6 times 6 divided by 2 and that's 21 right so numbs 2 is what it's 10. okay so which means that you know uh we either need to bring this uh nums one down where increases numb to up right and example two here right so this is a minus one because uh because the sum for not the sum for numbers one is seven right and the sums of num2 is six and there's no way you can bring the seven down or bring the six up right so none of this work works that's why the number the answer is minus one and so for this one it's also like uh it's al it's also three right so because we need to bring this bring the six down right to some numbers and then we can increase this one up to some numbers that's why we have three here i mean since this one asks us to find the minimum numbers here you know so for minimum numbers you know we can always try to use greedy you know because for this problem you know otherwise you know we can try to use binary search or even the bfs or dp but for this problem i think it's kind of clear obvious that you know this one is a greedy approach because you know um whenever let's say whenever we try to bring an announce nums one our nums down we're up right so let's say we try to bring this num one down you know we should always try to use the biggest number in this nums one here because you know because bring this num six down right it means that you know we can have we can decrease the numbers by five right and similarly when we try to bring a num a number another numbers are read up we should always try to bring use the numbers who is smart the smallest for example this one up because this one can also give us like a five uh difference so basically the logic is that you know we get the total one we get total one and total two right so that if we do a sub uh subtract between those two numbers we will have like a difference right and basically the that difference is the one that we are trying to accomplish right by either bringing some numbers up or some numbers down and we want to do it in a greedy way you know so that you know we can finish we can basically we can get this difference as soon as possible which means the minimum number of operations so which means that we need to sort we do we need to basically uh try to do a sorting right do a sortings like in such a way that you know by the uh by the difference that this number can come obtain for example if we're trying to bring this up you know so one will give us five difference two will give us uh four difference right so the difference will be six minus num that will be the difference if we try to bring this the current numbers up right so similarly when we try to bring up bring some numbers down the difference will be num minus one right so this is true this is the difference we can get if we try to bring uh make this uh bring this number down right because let's say for two you know it's one right so if we try to bring two down the because the minimum we can get is one that's why we do a minus one and we'll get the difference so if we do a transform of either numbs one or num2 based on the total numbers here right because either total if the for the total we who is bigger you know we'll basically will use this one right so the bigger numbers we need to bring them down that's the num minus one and for the nut for the totals who's smaller is we're gonna use this one to do the transform and after that you know uh we can just simply do it do a sort you know because well we can use a priority queue but for this problem you know the total time complexity will not change because even though we use a priority queue you know the worst case scenario we will need to store all the numbers into this priority queue right so which means it's also unlocked and in this case assuming n is the total length of the nums one plus num2 and basically by using the priority queue or simply sort the combined transformed array here the time complexity will be the same which is unlogan and then we just do it in a way that you know uh by always picking the biggest number right and then we try to decrease uh use the number to sub to decrease the difference until the difference either equals to zero or smaller than zero and that will be our final answer right cool so let's start coding here so like i said we need a total one here and then gonna be the sum of the nums times one right and total two gonna be the sum of the nums two here so and if total one is smaller than total two right it means that we need to increase nums one which means that you know for nums one the difference will be six minus num right for num in nums two and so for the other one it's going to be this one right so nums minus one for num in nums 2 right so on the other side right we just need to basically copy and paste this thing here and change that operator here so this one we're going to be nums minus 1 and this one gonna be the sixth minor snub right and after this one i just simply do a sort basically sort this one from the reverse order reverse equals to true right because i want to pick the numbers the difference right the difference from the biggest to the smallest and then we have difference right the difference will be abs of the total one minus total two so n equals the length of the nums right and then we have i equals to zero so basically i do this while difference is greater than zero right oh we also need the answer here equal to zero right if the difference and i smaller than n right uh i actually i can do this actually so for i in range of uh writing range of n right we loop through this one here difference right difference will be decreased by the numbers of i okay and every time we do this we increase the operations by one right and then if the difference is equal smaller than zero right we can simply uh break right and then we return the answer if difference uh is equal smaller than zero else minus one right because we need to do this check because it's possible that you know we cannot decrease that uh even after going through all the uh the transformed arrays here the differences are still uh not uh decreased enough to be to become zero that's when we need to return minus one all right so i think that's it if i run the code here yeah uh two three zero oh i see um if this one is zero okay yeah i can just do it yeah i guess i can just do a simple check here because i'm assuming right if different is not zero okay yeah so it passed right um yeah so as you guys can see here right so since we have this kind of sort here so it's going to be unlocked and right you can also use priority queue and whenever you finish one of the process here you can just add it right you can add it uh push it to the priority queue but like i said total time complexity will be the same and also here you know since we sort from the biggest to smallest right and then the basically if the numbers of i is equal to zero right so if this thing's zero we can also break that's a little bit of the early break uh the early termination here because you know if the current one zero it means that the remainings are all zero which means that there's no need to continue right but this will not like again this will not affect the total time complexity it's just like a little bit of early termination here but yeah anyway that's it uh yeah i think that's everything for this problem you know it's a it's kind of a very it's kind of obvious uh grady problem and you just need to do some little a little bit uh transformation and other than that i think there's nothing else i want to talk about okay i'll stop here okay thank you for watching this video guys and stay tuned see you guys soon bye
Equal Sum Arrays With Minimum Number of Operations
design-an-ordered-stream
You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive. In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive. Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1`​​​​​ if it is not possible to make the sum of the two arrays equal. **Example 1:** **Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\] **Output:** 3 **Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. - Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\]. - Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\]. - Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\]. **Example 2:** **Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\] **Output:** -1 **Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal. **Example 3:** **Input:** nums1 = \[6,6\], nums2 = \[1\] **Output:** 3 **Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. - Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\]. - Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\]. - Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\]. **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `1 <= nums1[i], nums2[i] <= 6`
Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break.
Array,Hash Table,Design,Data Stream
Easy
null
63
hey so welcome back and there's another daily code problem so today it's called unique pass2 it's basically a follow-up unique pass2 it's basically a follow-up unique pass2 it's basically a follow-up from yesterday's question which is called unique paths and so essentially what you're given here is a two-dimensional Matrix where here is a two-dimensional Matrix where here is a two-dimensional Matrix where you want to get this robot to this star and so the way you can do that is say you go down this path or you could bring him through this path so what's different from yesterday's question is you can see here what this is basically an obstacle that prevents you from kind of using this cell here and so basically if you hit that well you can't continue onwards so you can't consider any path say through there so there's only two a valid paths so basically what this question is asking you is just count the number of apostle paths to reach that star without hitting an obstacle and so like I just showed there's a two paths there and there's only one path here because well that's an obstacle because if you don't remember yesterday's question or you didn't do it the only other constraint here is that your robot can only go down one cell or to the right one cell and so he can't move upwards or the robot can't move to the left either so it can only go in these uh two directions here down into the right okay and so to do this essentially at every step you just have to be considering like two different paths so save your robot um is that cell zero then you can consider two possible paths here that's basically okay we can increment the number of rows by one like so or we can increment the column by one and then once again from these pass onwards as long as we didn't hit an obstacle or we didn't hit this uh Finish Line here we can once again increment them again so we could increment the rows so that would be at this point here or we could increment the column which means that it would then hop here but as you can see we hit an obstacle here so basically there's no more pass that we can go down now we can increment this um uh row count because while we ran out of rows here but we can actually increment the column counts that would look like two comma one and once again we can't increment the rows but we can increment the column count to reach the star and that would be to comma two and that's basically a one possible path so we'd basically propagate a plus one here up the chain to the max or to the kind of the initial call to this function so say if we kept going so we're currently on this side which is here and we can't go downwards because while that hits an obstacle but we can once again move to the right which looks like a zero comma two and then basically we can go down to one comma two and then down to two comma two and that once again is another Apostle path so we would kind of propagate up that we found one possible path up this chain to then return two which is the sum of one and one okay so let's go ahead and try implementing that so typically what you do for these kind of top-down do for these kind of top-down do for these kind of top-down memorization functions are algorithms is you define a function called DP that's what I usually use so we're just going to pass in the particular Row in the particular column that we're on and so once again we're going to start at 0 and 0. and so we want to fill out first our base cases so that's going to be well okay what if we hit that obstacle what that what is that going to look like and so that's going to be okay what if we step out of bounds and so to get those bounds we're going to have M and M to represent those and so that's basically the length of the grid and then the length of the Grid at zero and so essentially all that we have to do is say okay if the row is going out of bounds or the column is going out of bounds we expect to return 0 here right and so that's basically okay if we kind of go out of bounds this way or out bounds this way let's not consider that path but once again we also have to consider this obstacle here so let's go ahead and do that so these obstacles are represented by one in the graph while a0 represents an empty space so let's check for a one and so that's going to be a okay Grid at this particular Row in this particular column if it's equal to one oh it's also return zero in that case all right and so that's one base case but we also have to consider another which is essentially okay what if we hit this uh star here or this Finish Line so that's just going to be okay if the row and the column is equal to kind of that bottom right hand cell there so that's going to be basically n minus 1 because it's not inclusive and uh M minus one like so in that case we're going to return one like we did which kind of propagates that answer upwards where we just add up all the possible paths okay and so I see an error and that's just because I need a closing bracket all right and so those are our base cases and now we basically have to make those two possible decisions so let's explore all possible paths and so at every single point we kind of have two choices that we can go down or two different puzzle paths which is incrementing the column count or incrementing the row count which is essentially just two recursive calls of okay let's go down one row or we can um move to the right column and so we want to add these up because well we're trying to add up all the possible unique paths here so we just want to add an addition between these two recursive calls so the last thing that we want to do is just basically cache it so what that's going to allow us to do is okay say if we already called this function before with like the same parameters say like one comma two um then we won't have to kind of recompute all that and explore all those possible paths from that point onward so it just immediately Returns the result and oh one time it's basically a hash map or a dictionary underneath so let's try running that oh I think I have an error here so if the row is equal to n or C is equal to M oh I just need another or looks good and success so that's uh today's uh daily code problem so for time and space complexity it's basically o of n by m which is basically the size of the Matrix itself and then the space complexity is the same thing because while we're adding caching here in the worst cases we're going to have to cache all the possible uh unique combinations of this Matrix which is basically o of n times M so yeah I hope that helped a little bit and good luck with the rest your algorithms thanks for watching
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,968
hey coders welcome back to this channel so in today's video we will be solving the code 1968 which is array with elements not equal to average of neighbors so in simple terms we are given an array and we need to arrange rearrange that array in such a way that if there are three consecutive numbers then the average of the uh two neighboring two outside numbers right uh i mean two to two left and right boundaries right for example one two three four five and we consider one two three then two should not be the average of uh one and three should not be average of two and four right we need to rearrange in that uh in that way so in this way in this case you can see that this is rearranged in that way let us see how we can solve this uh problem right so let us say we have elements uh let's say 6 two six two zero nine seven right so first what we need to do is sort this sequence by episode i will tell you later so the sorted sequence would be zero 2 6 7 and 9. now we need to make sure of the condition that the middle element should not be uh mineral element should not be the average of the neighboring numbers a very simple logic i'm going to tell you very simple let's say there are two numbers uh there is one number a and there are two numbers p and c right now let's suppose that b and c both are greater than a then it is sure that b plus c by 2 would be greater than a because us it will lie somewhere between b and c this number let's call it d t will lie somewhere between a and c b and c right so indeed it will be greater than d so it cannot be equal to uh right it cannot be equal to a in any case right that we are pretty much sure so uh i mean but the main condition here is that we are given in the question that the numbers will be unique so we need not worry that a b and c are all equal the only condition where b plus c by 2 can be equal to a is that like equal if they are equal right so yeah that is one condition but we are using strictly greater than because we already have unique numbers in the array another case would be if a is greater than both b and c then b plus c by 2 will still be smaller than a uh right reason b that uh i mean again the same thing that we saw in the last example that let's say this is 5 and this is 3 and 4 then 3 plus 4 by 2 which is 3.5 and 4 then 3 plus 4 by 2 which is 3.5 and 4 then 3 plus 4 by 2 which is 3.5 will still be smaller than 5 right so what we can do that so our algorithm will look something like this sort number one sort the input second rearranging zigzag function what is this exact fashion exactly so we have a not a one and up to a n then we arrange the numbers in such a way that a zero a and a 1 a n minus 1 a 2 and so on right so the configuration for even numbers would be similar that we can look up and by two elements and then push a of i and a of n minus 1 minus i into our answer right uh to get this configuration but for all numbers we will need to make sure that we only push the odd element or the middle element only once so we can what we can basically do is go up till uh and by tooth index go up till n by two index and perform our insertion operations and then at the last we can just uh insert the odd element number so if you see in this example what i'm doing is i'm sorting the input going to n by two and then pushing into my answer num psi and nums of uh nums dot size minus one minus i which is the like a mirror image of that element and then if we have odd number of elements which is a we can do by doing and one or more two we just push the middle element and that's it so this satisfies the property that the middle element would be either greater than the average of both these two numbers or smaller than the average of this numbers yeah that is it guys if you like the video please hit the like button share with your friends and subscribe to the channel and keep giving your love thank you
Array With Elements Not Equal to Average of Neighbors
maximum-building-height
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`. Return _**any** rearrangement of_ `nums` _that meets the requirements_. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** \[1,2,4,5,3\] **Explanation:** When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. **Example 2:** **Input:** nums = \[6,2,0,9,7\] **Output:** \[9,7,6,2,0\] **Explanation:** When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 105`
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Array,Math
Hard
null
1,822
foreign problem and the problem's name is sign of the product of an array in this question we are given an integer array called nums and we need to find the product of all the values present inside the integer RN arms and using this product we have to determine the sign of the product if the sign of the product is a positive number then we have to return one if the sign of the product is a negative number we have to return -1 a negative number we have to return -1 a negative number we have to return -1 If the product is equal to 0 we have to return 0 as the output now let's take a look at few examples and see how this question can be solved I've taken the same example given to us this is the nums array this array might consists of three types of elements positive integers negative integers or zeros and now we have to find the sign of the product of the array so instead of finding the product of the entire array and then checking its sign you can use the mathematical principle where if you multiply two negative numbers you get a positive number so using this concept you can find out the number of negative numbers and then determine if the final output is going to be a positive value and negative value so here you can see if you multiply two negative number it gives you a positive value if you multiply three negative numbers you get a negative number so here you multiply two minus ones which will give you plus 1 and again you multiply plus one into plus 1 which will give you plus size output so using these two observations you can deduce a conclusion that so the first observation is that if the number of negative numbers is even then the output will also be a positive value and the second observation is that if the number of negative numbers is odd the output will be a negative product so now using this observation you can count the number of negative numbers in the input array arms and then conclude the sign of the product using the count of the negative numbers so let's start off by iterating the input array Norms from left to right from the starting index till the end of the array so we start from I equal to 0 I is pointing at 0 we check if it is a negative number yes it is a negative number as it is less than 0 so you increment the negative count variable which I have declared here 0 will become 1 now go for the next element I is pointing at one check if it is a negative number yes so increment the variable account go for the next element check if it is a negative number yes so increment the variable go for the next element check if it is a negative number yes so increment the count go for the next element check if it is a negative number no so keep moving forward check if it is negative number no so count will remain the same check if it is a negative number no so count will remain the same and now you reach the end of the array so you can end the iteration and now you have the value 4 for the number of negative numbers since this is an even number the output will be plus since the output will be positive you return 1 as the output according to the requirements so one will be the output now you have to handle one more case that if there is a zero inside the input array so for example instead of minus 2 here there was a 0 so here you can see there is a 0 inside the array so let's repeat the same process but you have to do one more check if it is a negative number yes so increment account go for the next element check if it is a negative number no but it is a zero so whenever you find 0 the entire product of the array is going to become 0 because anything multiplied by 0 will give you 0 so as soon as you find the element 0 inside the array you can return 0 as the output directly now let's Implement these steps in a Java program coming to the function given to us this is the function name and this is the input array norms and the return type is an integer because we have to return either 1 minus 1 or 0 as the output so as I've said let us find out the number of negative numbers inside the nums array so to find out the number of negative numbers I am using a counter called negative counter which will be initially 0. and now using a for Loop I'm going to iterate through the input array nums from starting index till the end of the namsari now if a element inside the array is equal to 0 it means the entire product will be equal to 0 right so the element pointing at I inside the nums array is equal to 0 so whenever you find a zero inside the nums array you can directly return 0 as the output because the overall product will be equal to 0 and if the product is 0 we have to return 0 as the output and now here using an if statement I'm checking if the current number we are accessing is a negative number negative numbers are less than zero so if you find a negative number inside the array increment the counter negative count each time you find a negative number so this for Loop will happen for all the elements inside the nums array and you find the number of negative numbers inside this variable net count and now using the math concept that if you multiply two negative numbers it leads to a positive number so if the negative count is a even number it means you always get a positive number as the output so there are four negative numbers you can form two pairs of negative numbers each of them will be multiplied and you get a positive number plus and when you multiply two positive numbers it's always positive so using an if statement you're checking if the number of negative numbers is an even number so using the modulus operator whenever you divide it by 2 the reminder should be 0. so if the number of negative numbers inside the nums array is an even number then you return one because the overall product will be a positive value since X is positive you return 1 as the output so if this condition fails it means that the number of negative numbers is an odd number so if there are odd number of negative numbers the product will always be a negative value so if the product is negative you return minus 1 as the output so you return minus 5 as the output now let's try to run the code the test cases are running let's submit the code and our solution has been accepted so the time complexity of this approach is of n because we are iterating through the input array nouns from left to right so n is the length of the nums array and the space complexity is constant of 1 because we are not using any extra space to find the output that's it guys that's the end of the video thank you for watching and I'll see you in the next one foreign
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
1,332
welcome to march's leeco challenge today's problem is remove palindromic subsequences given a string s consisting of only of letters a and b in a single step you can remove one palindromic subsequence from s return the minimum number of steps to make the given string empty okay and the string is called pound row if it reads the same backward as well as forward so say we're given a string like this a b a this is a palindrome right so we can remove the whole thing in one step so then we return an output of one now what about this a b well unfortunately this isn't a palindrome so we'd have to do this in two steps we can remove either bb or a first and then a or bb next that'd be two steps same thing here uh we have to remove first a sub a palindrome so here we'll remove b a b so we'll move this first and then we'll have to remove the b after now if you look carefully at how it's highlighted though you can see that you can skip um it doesn't need to be like right next to each other you can skip any of the letters so it can be b a skip that and it's a b that's the palindrome so we can remove that part and then remove the b here if it's empty there's nothing there so we return to zero so this at first kind of sounds like maybe we need to go recursive or maybe there's a greedy method but it's actually very simple and it's a trick question really if you think about it they give you a hint use the fact that the string only contains two characters and it's like what does that mean but this is the big one if a subsequence is composed of only one type of letter then is it a palindrome and obviously the answer to that is yes if it's all a's it reads the same forwards and backwards right now given that there's only two characters and we're allowed to skip sp likes like spaces here it doesn't need to be right next to each other since there's only two characters we can always do this in two steps we can just remove all the b's all in order and then remove all the a's so that's the thing there's only three cases that can happen either it's empty so we just have to return to zero it's already a palindrome so we can do it in one step or it doesn't matter how it's ordered we can remove all the b's and then all these and do it in two steps so that's kind of the trick here like everything else doesn't matter we just need to account for those three situations all right so let's true let's do that if not s we know we just return a zero at first right second we want to check to see if this is a palindrome you can do it multiple ways but i'm going to do it the class way where we're just going to start at the left and right and say all right length of s minus one you know you can obviously just do a reversed with the string as well but i'm going to do like this just because i'm used to it and what we'll do is if we'll say if string of l does not equal string of r which means it's not a palindrome immediately we turn two because we know that's the answer it's only when we figure out yes this is a palindrome okay well then we turn to one so let's see what happens here make sure it works this should return to one it does let's go and submit it and accepted so this is an old end time complexity very simple but it's could be very tricky to get here you know at first i was very confused that how we might do this i was thinking like greedy methods and recursive but as soon as you start realizing wait there's only two characters and we're allowed to remove however many as long as it's in order then we can always do it in two steps and once you realize that then this question is very easy alright thanks for watching my channel remember do not trust me i know nothing
Remove Palindromic Subsequences
count-vowels-permutation
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does **not** necessarily need to be contiguous. A string is called **palindrome** if is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "ababa " **Output:** 1 **Explanation:** s is already a palindrome, so its entirety can be removed in a single step. **Example 2:** **Input:** s = "abb " **Output:** 2 **Explanation:** "abb " -> "bb " -> " ". Remove palindromic subsequence "a " then "bb ". **Example 3:** **Input:** s = "baabb " **Output:** 2 **Explanation:** "baabb " -> "b " -> " ". Remove palindromic subsequence "baab " then "b ". **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'a'` or `'b'`.
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Dynamic Programming
Hard
null
672
hey everybody this is Larry it's December 29th of the 2022 yeah so today I'm just going to do a bonus extra question that I haven't done before um yeah so okay so I won't have a difficulty limiter so we'll see maybe it'll be hard maybe it'll be easy maybe it'll be a medium and today's plan is going to be a medium 672 a bob switch so I'm trying to do one that I haven't done before um at least I'll need code because you know not I've done a lot of problems I suppose got 99 problems but this ain't one or the other way maybe um what is going on in my Discord okay so 672 Bob switcher 2. so there's a room with N Bulbs they would run from n so one flips all the bulbs two flips out of twos three flips out to three four fifths or the fours maybe probably yeah four flips out of fours oh wait no that's not true I misread this I just saw the two and then the three but now it so two is even three is odd and four is this funky 3K plus one so one four seven ten okay so the only four buttons is not n buttons okay I was thinking of something else for some reason you must make exactly Press buttons in total um for each you can pick the number of possibilities of status after all four okay so the first thing I do is look at the constraints to be honest see if I can stimulate it but stimulate is simulated right uh meaning try all possibilities and of course given that they're forced to uh a thousand possibilities uh or like if you simulate it in a very naive you know recursive way it'll be 40 000 and that'll be too slow so okay but given the N is a thousand we'll see how that goes um okay hmm I don't really have any idea of my head but hmm this one is also very hmm I'm also trying to think uh let me I'm just trying to think about case analysis right so okay so we're given a thousand presses but they're not a thousand unique presses right because this fun one two four flips so that means that in the worst case um I have to do some maths around this because we have to press exactly press this time but what I mean is that it's not unique because each one of these can be you know it's binary right so there's only two to the four which is 16 possibilities um in the most um right yeah so I think that's pretty much it I guess that's the answer um well I mean the answer is not 16 but you can simulate up to 16. so the way I the reason why I say this and I think I kind of jumped ahead in my head sorry about that but because turning this if you flip the same button twice it turns it from Up it uh it reverses your action right so if you flip something twice the same button it does nothing that's basically uh what I'm trying to say here right and so um so if you think about so no matter how many times you're gonna only flip about this zero or one times right so okay so you have 16 possibilities because you have two to the four possibilities right each button can be pressed or not pressed in the end State and then the end result is just making it whether it is possible to get to those State um meaning that and this is going to be a case analysis where presses is going to be for example press this odd number you know you cannot only have one button flipped at the very end oh sorry the other way around but you get the idea right there's some parody um there's some idea about parody that we have to check and then there's also the other idea being that oppresses is less than like four then you or something like that right like we only have one plus you cannot have three presses on you know that is possible in theory right and then of course um some of these are equivalent classes for example in this case maybe only for small ends though I don't know that well for ends I mean you could even reduce it some more in that given a thousand you could take um I don't know maybe uh what is this four seven ten I don't know but like there's some like weird like gcd lcme thing that you can probably even further reduce this from a thousand but uh but I don't think that's necessary so um so that we don't let's not worry about that for now I mean we can maybe do it for uh extra credit but yeah it's okay so I think we have to the answer here except for that it's it is not gonna lie uh you have to be careful to get all the cases so I'm a little bit worried about that but I think we have the idea and we can when we can go for it right so okay so basically all right let's try you know hmm I'm gonna write this really dumb usually I uh just for teaching purposes the way that I would probably normally write this if I was just solving it for myself or in a competition or something like that um uh I would probably use a bid mask to be honest and then just Loop through the pit mask not gonna go over bid mask today so uh oh I don't really feel like it so we'll uh you know we'll uh just do this thing I guess right um and we can do it in a number of ways but should be okay so yeah for example for band One in um a true Force maybe I don't know it doesn't really matter I guess I don't know we'll write it this way for now and then maybe I will change it a little bit in a little in a rewrite or something right so this is basically just saying for you to blend that on and off okay fine uh let's just fine let's just make it true for us and maybe there's a queen of way to write this but like I said I'm just kind of writing this to illustrate what I mean um okay so then count is equal to um into B1 plus into B2 plus into B3 plus into B4 right um and this is of course just converting it from true and forced to one and zeros so then basically if count is less than or equal to prices and crisis Mark 2 is equal to camera two then we do the simulation you can actually optimize this in different ways I'm not going to for um I don't know there's no reason I don't want to prematurely optimize but I think these two are maybe sufficient I don't know if they're sufficient or I want to say they're probably sufficient but I don't know for sure that they're sufficient for um for now so we'll see give me uh so we'll see how that goes but yeah but otherwise you hmm I'm just thinking right now how to um well there's only 16 of them right like we said so we don't I was thinking about optimizing like a hash table or something like that but I think we don't have to because uh we could just use a regular like scene for example um because like I said there's only 16 of them I was thinking in my head that there might be more and you have a thousand elements and it's kind of awkward but now we don't have to worry about it I think was it just 16 times this right so yeah so then now what we're doing is just yeah like uh what's it lights that's what we're doing pops is to go to force times uh uh right and then we literally go if B1 then we Flipboard all the bulbs right um for X inbox right if B2 both equals um hmm uh not X for X in uh for egg um for i x maybe I've divided another way however um can I buy this in one I think yeah it's a little bit awkward but um next if maybe I should I probably shouldn't do this in 190 but anyway uh it goes even right so that was X right uh this is the same except for odds I'm just gonna copy paste um is that it's probably not great and then Bob's just the same except for it's 3K minus one right I'll put three K plus one so it's just my three I might three is equal to one right okay and then we just add it to uh yeah we just add this as a turbo the scene so because we make a table so that's hashable and then at the very end we return the length of scene um now it gets this one well so one first hmm that's weird I would imagine it oh it outputs three not four so one of these is one maybe uh well let's take a look I thought it was outputting one which is why I was like very confused um okay so it that confused on and off yeah I guess it doesn't matter it should be just you okay so hmm don't mess with this flips the switch no that's okay uh okay so basically this is the switch one this is switch two um this is switch three so we're definitely missing switch four did I miss the typo somewhere flipping so we definitely flip this let's see it may be that I have a typo it's fine I don't see it though Force oh I did have a typo so wait oh it's so in uh I actually messed it up um it just happens that I got lucky on the other one is that these are labeled from one to n and not from zero to n minus one huh that is actually annoying hmm okay so then now I mean we can fix this that means that in a zero index is a zero and this is one I think that's pretty much it really uh okay I was counting from zero to um I was counting from uh what you might call it um one index for one of these and not the other one that's why um yeah it's a little bit slow but we could have made it better because you can not gonna go over it um yeah as we said this is I don't know it's meant how you want to say it this is constant time or maybe of and if you want to say that but even then there's a cycle to this so you can probably can uh update this over one and not be bounded by n if you really want to um especially now that I because I was a little confused about um I was a little bit confused only from um yeah I think like either six or 12 items probably good um and you can maybe prove that I'm not going to um I was only a little confused because I looked at these numbers and I confused zero index in one indexed in my head but yeah but you can think about this as over one and if you do bound this then it'll be all of one as well so yeah uh maybe we could play around with this so n is equal to now because if n is 17 then what happens and there's a Cycle Plus so you have to do a little bit more complicated but um or something like that but yeah that's all I have for this one let me know what you think let me know if you find this interesting um I think sometimes you know I know that if you have done enough problems and this is actually not a premium question by the way so I never kept questions when why not you know but uh but yeah this is not even a premium question but uh but the thing is that you know constraints they give you is fine but sometimes you have to look at the constraints given by the prom itself and in this one the tricky part is the buttons and try to figure out how many different possible things there are really right so yeah um that's all I have with this one that's what I have for tonight let me know what you think stay good stay healthy take good mental health I'll see you later and take care bye
Bulb Switcher II
bulb-switcher-ii
There is a room with `n` bulbs labeled from `1` to `n` that all are turned on initially, and **four buttons** on the wall. Each of the four buttons has a different functionality where: * **Button 1:** Flips the status of all the bulbs. * **Button 2:** Flips the status of all the bulbs with even labels (i.e., `2, 4, ...`). * **Button 3:** Flips the status of all the bulbs with odd labels (i.e., `1, 3, ...`). * **Button 4:** Flips the status of all the bulbs with a label `j = 3k + 1` where `k = 0, 1, 2, ...` (i.e., `1, 4, 7, 10, ...`). You must make **exactly** `presses` button presses in total. For each press, you may pick **any** of the four buttons to press. Given the two integers `n` and `presses`, return _the number of **different possible statuses** after performing all_ `presses` _button presses_. **Example 1:** **Input:** n = 1, presses = 1 **Output:** 2 **Explanation:** Status can be: - \[off\] by pressing button 1 - \[on\] by pressing button 2 **Example 2:** **Input:** n = 2, presses = 1 **Output:** 3 **Explanation:** Status can be: - \[off, off\] by pressing button 1 - \[on, off\] by pressing button 2 - \[off, on\] by pressing button 3 **Example 3:** **Input:** n = 3, presses = 1 **Output:** 4 **Explanation:** Status can be: - \[off, off, off\] by pressing button 1 - \[off, on, off\] by pressing button 2 - \[on, off, on\] by pressing button 3 - \[off, on, on\] by pressing button 4 **Constraints:** * `1 <= n <= 1000` * `0 <= presses <= 1000`
null
Math,Bit Manipulation,Depth-First Search,Breadth-First Search
Medium
319,1491
953
hello everyone so in this video let us talk about a problem from lead code it is an easy problem name is verifying an alien dictionary okay so the problem statement goes like this that you're given an alien language surprisingly the aliens also use english lowercase alphabets but possibly in different order by order it means that we have the order of the english alphabets like a b c d e f but for the aliens it might be h l a b c d and so on okay so the order might be different now what you actually given is that you're given a sequence of words written in the alien language as you can see now and the order of the alphabets for the alien language that is also given to you return true if and only if the given words are sorted in the lecture graphical order for the alien language now the only thing is what is lexographical order many of you might know many of you might not know i will tell you in simple terms what you can simply understand from lexographic order is let's say that you are having these words and you want to place these words in a dictionary then which word should come first when which word should come next and so on so these words if they are placed in a dictionary should be in the same order in which these are here okay so let me take an example to how they are placed in a dictionary so let's take an example let's say you have two words that is a b c d this is one word and the next word is b c d e this is another word this is a complete string and this is one word another then obviously this word will come first in the dictionary then this word why because if you like match out this word they start with a and they start with b so obviously when you do like search in a dictionary the first all the words with a is st are there and then all the words would be so obviously this will come first similarly if you just have these words some characters matching so let's say that the word is a b a c and the next word is a b a f then obviously this word will again come first in this word so what you can observe is that this word is matching this what is matching the first word that is unmatched now whatever that character is whichever is smaller should become first and the next one should be converted and the other case can be let's say that they are complete matching c a and the next is a let's next is a b c this is the next one now what you can observe here is that if two words are there in which they both are completely matching until one of them exhaust like there is no more character to match then the word then the string which has lower characters is the one that is put first in the lexographical order that this will be placed before in lexical order in a dictionary okay why because the complete matching is there how you can now differentiate between them two so whichever larger should be placed later now whatever rules i've told you is according to the uh what you can say are uh order of alphabets that is abcdef okay but this might be different why because let's say in uh in alien dictionary b is before a like it might be like b c a d f like whatever their order is if b is before and obviously this word will come before i hope you get the point so the overall logic here is that whatever words you are given let's say word one word two word three and so on you just have to understand that they should be sorted by sorted if so this word should be the smallest they should be like this and so if you want to play them in a dictionary according to any language they should be placed in this order so what you can actually do is you can just match two consecutive words okay you can just match these two words then these two words and so on and this word should be lexographically larger than this previous word how you can just do that you can just take these two are letters let's say w1 is uh coding code okay and w1 is let's say again c-o-d-e c-o-d-e c-o-d-e let's see so you can just have these two words you can now compare them according to the order of the alien language and whichever comes smaller if this code is coming before like this code is let's say w1 and it is smaller so obviously this is fine if this is smaller than that is wrong let's do the logic you can't get on the code but now so that it will become more clear to you but that's all your logic here what i've done here is that let's move this so this is the ideal language like start function we will iterate over all the adjacent words and compare them and if the comparing function returns false that they are not in the correct order we will return false as it will true like else returns to if every two consecutive pairs are correct in the order okay how now this compare function works this compare functions will take a pointer like let's say a variable i that will keep on matching these two strings until they are having the same character okay so we will iterate over this i and i will go over the length of a and if a i and b i of the same position are same we will keep on entering like incrementing it now when this while loop will stop like what three cases it can stop the first question to stop is let's say i'm moving over the let's say the string a so there's some string a let's say a b a c and the next string is a b a okay now this is a string this is b string which is given to you like this a and b okay now i'm moving this i along the string they keep on matching that this is match this will match this and match now it will stop either in the two cases either there is some character left in the string a but nothing in string b the other case can be that there is some scatter left in b but nothing in string a or there is a mismatch my mismatch is that it is a b a and uh this is a b a e okay and so on so the three cases are there at which it will stop eventually doing this while loop and we'll handle those three cases one by one the first case is if a stops and b doesn't stop if a stops and all the characters before it are matching which means that a is smaller so if a is smaller and b is larger it is fine because i just want a to be smaller than b to be larger according to this function so return true if a doesn't stop like a still have more characters but b stops okay in that case it returns false because although matching a is not smaller b is smaller so it don't falls or else the other case can be that a and b do not stop but they stop at a point at which the characters are different now if the point at which the character different whatever character both of the strings have we just check out in the order of the alien language which character come first whichever atom come first that word will become smaller let's say smaller so i will just find the order of the ith word i am on in the a string as well as the b string if the a string word is having smaller order then obviously the current word a is smaller eventually in the lecture of order or sb is smaller so if a smaller answer is true as always answer is false so it's just a boolean expression to calculate which one is smaller and accordingly to that condition we will just compare two consecutive words and just print out answer eventually the rest of the logic and the good part for this problem if you still have it out you can mention in the comment box thank you for watching this video till the end i'll see you next time like coding and bye
Verifying an Alien Dictionary
reverse-only-letters
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Two Pointers,String
Easy
null
881
hey everybody this is Larry this is day three of the little April daily challenge uh hit the like button hit the Subscribe button drop me in this squad let me know what you think about today's Farm uh since I've done it recently apparently I'm out over to that reason but I'll try to do another premium problem right after this so definitely stay tuned and do it with me please um all right let's look at today's from 881 both to save people you're given an array of people where people are surprised the rate of the I've person and an infin Infinity number of boats uh infinite number of boats where each book can carry a maximum rate of limit each book carries at most two people at the same time providing the sum of the rates of those people uh is at most limited limit we turn the minimum number of boats to carry every given person okay um I mean the first thing that makes sense is to sort it right uh I think this is going to be a greedy in a sense that um I think there are a couple of alcohol algorithms to do this but I'm gonna think of I'm gonna you know but I think the key part of this is just try to figure out okay what are the constraints that we can do right and what I mean by that is that okay let's say we have a big person or okay yeah like a heavy person right and that person does not have a partner to part with right well then those people will have to just um have to both by themselves right I think that makes sense ideally um and for that I'm just trying to think whether I'm missing a case but for that then right and then to kind of check whether let's say we're going from the heaviest uh person to check whether the heaviest person can match with someone well if you're already dealing with the heaviest person you don't have to save the lightest person for anyone else because you're already dealing with the heaviest person so therefore you can just check the current heaviest person see if they match up the lightest person and if not then we just take the next heavy person that person get his own boat right and then we just keep going I think that should be good enough um there are a couple of ways you can do this uh implementationally wise uh let's just say we have count you know return count and then maybe something like uh um left as you go to zero and white is equal to n minus one where and as you go to length of people right so then wow left is uh less than right so we have two people uh yeah if people of Love plus people of right is less than or you go to limit then we increment by one right and then can't we use one bow otherwise and we I think in this problem you're supposed to assume that each person so yeah so then otherwise uh we can come in by one and count oh this is decrement obviously made a mistake here oops um and then at the very end yeah if left is equal to right then you have one person left and then we just increment by one I think this should be good maybe did I miss any case I mean I don't know you look at these quality of uh these things I'm not really confident but I am lazier than I am confident so I'm just gonna submit and looks good uh 1098 day streak uh and that's pretty much it hmm hope that I mean this is a pretty greedy uh explanation and hopefully that explanation is okay enough I don't do it before now I just I did the same thing I guess huh except I use better variables that time uh this time I just did a binary search maybe because I was in a binary search section though you don't need binary search for this um yeah but as you can see this is gonna be analog and dominated by the people and O of n because dominated by well also sorting because I count that as uh linear because you're manipulating the input so yeah uh that's what I have for this one foreign I hope that the argument is good enough for the greedy uh yeah let me know what you think I'm gonna do a uh an extra premium problem after this so definitely if you feel like this was too easy let's do another one together uh but yeah stay good stay healthy to good mental health have a great coming week I'll see you later and take care bye
Boats to Save People
loud-and-rich
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Array,Depth-First Search,Graph,Topological Sort
Medium
null
1,011
Hello everyone so today we will be discussing question number 101 of lead code which is capacity tu shiv package with in d country now this one which is part of question play list whatever I will discuss in this video is a moderate solution which I have made His playlist has been discussed in great detail in the first two videos. After that, I have also asked a lot of questions and now here is the question I am asking. Okay, in this you will understand very well that which is made in predicate. There was six in the template solution and if you have not seen that first then the video then it is suggested that first you watch those two videos and then come to this and if you are following the entire series then it is match butter ok, in that I discussed progressive. Now let's see how to make the predicate of is. Now let's see the question here, what to do in it. It's okay here. If I take an example, then sorry. If I take an example, this is my five. Now what is this is weight. And what is this, such packages are okay, this is a conveyor belt, you understand, it is located here in this direction, I will send it only by clubbing 123, that is, it is okay, he told them that look, does Shiva have any capacity or this much capacity? He can handle it, okay, so we have to tell the minimum capacity, he can handle it will seem a little confusing, so let me tell you this, come on mother, you have 5 days, okay, and what did you do by not doing 5 days, this is complete. The entire batch of packages ranging from P1 to P10, you gave profit in Shiv and sent it, if the weight is too much, then you have been given five days, you can load it with ease and peace by weight distribution, you cannot send it in a day sir. If I can, I have given 5 days, so I have to do it properly, so what do you have to do, how to distribute the weight, now understand that too, what is it, the less load will be there on Shiv, then come on Maa, first of all I took this batch. Okay, this is the best one this time, give me my total sum, what is its 3 plus 4 plus 5, what will become of 12 9, what is 17 and 15, I have sent the package, its 10, now see, send it with the package. I have sent all these, what is the maximum? Look, what is the maximum? 17, so according to this, it means that if I have sent it, then 17 is the minimum capacity, meaning it must be 17. It must be this capacity. Okay, now here I have answered like this, how? Now see what is in me, is it 17 or not, so what if I try another combination here which is the answer, in this I will tell you the answer, what is Aman's, let 's do 12345, okay in Devan, now 's do 12345, okay in Devan, now 's do 12345, okay in Devan, now I will give you what in De Tu. I did six and seven and in date 3 I did 84 I did 9 and in give five I did 10 I swear what came 15 13 8 9 and 10 Now you see what is the minimum capacity here see 15 so honey must have capacity this how in If you send 1 2 3 4 5, 15 17, have you found the combination, yes friend, we can send it even in less capacity, you have to find out the combinations, we will balance it and make predicates in it, how will we do it, okay, so let's do it with binary search. Okay, so here we had taken the example, now I am taking it back, I am here, now you tell me one thing, okay, what is the minimum capacity, that means it will have a range, isn't the range in the sense of a lot of minimum? Capacity is power, we just saw that what is N, one was 17, our answer was 15 and there are many other values, if power is there then there will be no range of minimum capacity. You don't think there is any and I will be found in this area. Range What is D What is Minimum Value of Minimum Capacity Understand What is D Minimum Value of Minimum Capacity You understand what I am talking about that even the minimum capacity is very limited, there is power, as we have seen in the example, there are many combinations. There can be 50 combinations, there will be a minimum capacity which will be the smallest and there will be a minimum capacity which will be the biggest which one is that one how will we come out which is the minimum value na which is the minimum value date it is the maximum of maximum maintainer like In this, maximum elements will go 10 at a time or even a single package, if such a package cannot be broken and sent, then this exit today will go to a single entry TV, then it will contribute 10 to the capacity, so the capacity must be 10, if it is no. If you go with 19 then even art will be reduced to 19. How much will it do? 27 Look, 27 capacity has been reached. 27 capacity is a lot, but what should be the minimum capacity? It should be 10 because if I send only 10 to NDTV then it will be the same. But its value will be equal to its weight, that is, the capacity will be 10, that is why I am saying maximum element in what is the max value of minimum capacity, what is the max value of the sum of all these, the whole of which is not even a conveyor belt but carrying weight. There are chances that Dub will go but now you will have to take Shiv, there is no option, if you have one day then you will have to take the entire consignment from one to 10 in one go. This date is the minimum capacity if you have If you have a day's tax then you can divide it but if there is one then you will have to send the entire assignment once, then what will happen to you there, that will be yours, it will be the sum of D's whole elements, that will be the maximum element of D' that will be the maximum element of D' that will be the maximum element of D' s, this thing. Now you see, here you have got a range, now you have to find it in this minimum capacity, okay, so like mother, let's go here, what was the minimum value, what is 10, do you understand and what is the maximum value, sum of holes. Elements of D Hey, so what will it become? What is the addition of one to 10? This becomes your 55. Look, what is there from 10 to 55? What is there from 10 to 55? This is the range that is Puri. Here your answer is story note show but how will the answer be given if my predicate is if I am giving input to it If that predicate is done then it will give me this value, this is the minimum wax, true date, predicate access route, what will be that predicate, what will he tell me in life days, if I send this combination, let's go to my mother, my minimum capacity, I am here, I am fine. My minimum capacity came here, if 14 comes here, I will check it by sending you in predicate. Is it possible to send consignment of 14 capacity within 5 days? If 14 is possible then 15 will also be possible. Just think. That brother, your answer has come in 14, it means that you have 14 capacity and you can take it in 5 days, you can even take it in 15 days, so 15 means you have no problem in finding that combination but in less than 14 combinations. I think it may be possible for you, then you are not sir, so look here, binary search will be done and my predicate is also giving the information that if one is yes, then all the subsequent ones will also be yes. If you understand, then if yes comes here then 15 will also give yes, 16 will also give yes, 17 will also give yes, 55 will also give yes, if 14 years is giving, but I am not sure sir, will 13 years give or not, so sorry here, the answer is actually 15, so I don't have 15. Then I hope you understand what I am saying is that if 14 is giving me yes here because 15 finding many combinations is not a problem, the capacity of 15 is right within 5 days you can increase the load. There is no problem but you have to find how you can send that consignment in minimum load, so you know if you have got it here yes then all the others will also be yes but you want this minimum value, you want first air, what do you think. If you want first air, then what are you, right half result dog, you will go in this direction, now if you want mother's permission, you come, you came here at three, sorry at 10, if not here, then come here at 11, then it is okay. Here you got it no now you know that if it is not for 10 then I can't do it for the elements before 10 also no I 10 is note D minimum capacity so sorry how will you distribute less load you no Why are you giving a note of 10, how dog, what will you do by rejecting your left off, dog and equal you m plus one, dog, so you are understanding how I have made equal you r and here how I have made that left half. And how am I rejecting the right half, I have come to you, I have explained it well, now you have to understand it, now you have to see how to make the predicate, I will make it in the court in the predicate, okay, you also try. Do it if you become a predicate, okay, now I have just explained that your predicate should return n today, your predicate should return like this is how you will become a predicate, you have to decide, so it is very simple, its predicate is not very difficult. All you need is an What is it, let's see how to implement the predicate, rest of the template solution is already with us, so let's do it quickly. I hope you have understood. If not, then watch this video again, listen carefully. Very clear, I have tried to understand in a clear way, so it is okay not to get confused at all and this is the minimum maximum, do not get confused like this, I have listened carefully to what I am saying, what is it, minimum value of minimum capacity, what is it D. I will implement maximum value of minimum capacity. You also try. If you can then it is very good. Otherwise, we are already doing it in the court, right? So what have I done here? First of all, I have written a little about the court. What I have done here is I have initialized L and R has been initialized as L, which as I said will be the max of the element and R will be the overall sum, so this is what I have done here, now the template solution is Ville L. &lt; R is the template solution is Ville L. &lt; R is the template solution is Ville L. &lt; R is the predicate to remove made is one of mine ok if you return this predicate then what will I do I will reject the right half and if not then I will reject the left half and return l This is my template which is very Now I am afraid that how should I implement this predicate, if I want to implement the predicate, then you guys also write, now it is there, so you guys will write like this, there is no problem, but if we are ready, we have to implement it. If you have implemented the predicate, then it is very good, so let's try it and see what we have to do, okay, I have said the cap here, it is okay for me, I have sent the value, which is one of the values ​​in the range of minimum capacity. one of the values ​​in the range of minimum capacity. one of the values ​​in the range of minimum capacity. I have taken out what I am, now I passed it to him, gave it D Minimum Capacity, okay, so to write it better, I write Minimum Capital, okay, this is my minimum, what do I know now, what should I do here? There is some thing that I will stitch here, so what will I do for it, I will give equal to one, first, total will also be required and minimum capacity, this is the value of mid and I will calculate the total, what will be the weight, meaning first weight, first package. I inserted it ok, first inserted the packet, now I will check friend story, is my total more than the minimum cap? If it is more than the minimum cap, then brother, today's day is over and assign a new weight to the total. I am doing this, I mean, what have I done till now, why did I do this, look brother, you are doing all this, but later on, my days are over, you have this minimum capacity, this is not possible, this is what I realized myself. If you have fulfilled the minimum capacity, then in the condition that you have done total days plus, run the loop like this and later if you run out of days, then this is not possible with minimum capacity, otherwise we will have to return something else. If you want any other minimum capacity, then what will happen if you burn it there? I will go to the Souls block and I will reject my left half, I will go a little further because my minimum capacity will have to increase a little, my country is finished. And if this is not happening brother, it means I have days, I have sufficient and total, there is no problem, I am not crossing this, on doing plus, it is true, no, there is no problem, I just have to return this water. Or true, this is my predicate, so I go here and submit it, I am accepted, how is the predicate implemented here and if you don't understand, then look again, see in 1.5x and what is the benefit to you from it was a see in 1.5x and what is the benefit to you from it was a see in 1.5x and what is the benefit to you from it was a simple question. But you should learn one thing that how to make a predicate. See, you have written this logic yourself. You will have to write it completely. People, if the questions become more difficult then maybe it will become a little more difficult. You will not have any tension about quality etc. You will just have this logic which is This is good logic, you have to think, ok thank you.
Capacity To Ship Packages Within D Days
flip-binary-tree-to-match-preorder-traversal
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Tree,Depth-First Search,Binary Tree
Medium
null
316
hello everyone welcome to our channel code with sunny and in this video we will be talking about the problem remove duplicate letters its index is 316 and it is the medium problem of the lead code okay so without wasting our time let's start like we would be involving the concepts of stack that is how the elements that is being pushed right now will be present at the top of the stack and how we will use the concept of the stack to solve this problem efficiently right in off and time like we can have some other solutions also i will discuss all those you can see if you look out my submissions i have four submissions and the very first submission is quite looking very hectic to implement but yes i have implemented that i will discuss all those in this video with the concept that is being uh we are going to cover over there okay so let's begin given a string s and we need to remove duplicate letters so that every letter appears once and only once that is the frequency would remain one for every letter like every distinct letter and you must make sure your result is the smallest in lexicographical order among all possible results okay if you are not getting this problem right now no need to worry about let's reframe this problem like you need to consider all the distinct characters right and you need to find a subsequence of like you need to find a subsequence among this given string that will contain all those distinct characters right okay so let me uh discuss this with examples also first of all let's look over the constraints uh max length of the string is 10 raised to the power 4 so you should be covering around open solution that would be better and the string consists of all lowercase english letters okay so let's begin with this sample bc abc okay so we have this string as b c a b c okay so first let's understand what this problem is going to tell us it's like we need to consider first of all the distinct characters that is character a character b character c okay so these are all distinct unique characters distinct characters okay and we need to find a sub sequence among this string such that uh like when you find a first of all subsequence then we need to uh find out the minimum like lexicographically smallest subsequence containing all these distinct characters okay so let's first of all find out all those sub sequences that is going to exist over here so you can see we have a b c a we can also have a b a c uh like b a c that is over here and also we can have c a b also and we can have abc also okay note that whatever the subsequences that i have chosen contains all those distinct characters that is present over in the input string okay this one now we need to report the smallest subsequence like lexico graphically smallest sub sequence so you can see the answer is this one this is the lexicographically smallest okay so you need to know the concept of lexicographically string also among all the given end strings okay so this will be our answer okay so let's take an another example over here like this one so let me just first change the color so you can see i have the string as c b a and then c d c and we have then bc okay so you need to choose electrical graphically smaller string so that it would contain all those distinct characters a b c d note that these are the distinct characters that is present in this string right so you can see the lexicographically smallest string that we can choose is a and we can have c and we can have d and we can have b like a c d b you can uh check it out this is the smallest lexicographically smallest sub sequence that we can choose that will contain all those distinct characters okay now how to do that efficiently okay so what we will do is like we will first reframe we will introduce some linear vector that would keep track of the occurrences of element okay so first let me erase this okay so i would need this example also so i would keep that okay so what i will do is like i will first make this linear vector of size 26 that would map the character to the index you can see i have named it at last it means that i need to store the last index of that character that is present in the string why i'm going to choose this last index why i'm trying to work up on this last index i will tell you later on because also you can understand it in simple ways that whenever we will try to choose a character we need to check it out whether the remaining characters that we can choose after that or not so that would be helpful in determine that can be easily determined with the help of this last index of that character all those characters okay so you can see we need to choose the lexicographically smallest uh subsequence so we will start with the character a okay so when we look out for the character a uh wait a minute let me fill out this last vector because i need to explain with the help of that also so last of a will be you can say 0 1 2. note that i am using a 0 based indexing last of b will be 0 1 2 3 and last of c's four okay so let me uh write down the indexes also zero one two three four and i will be explaining this one also okay so yeah so we will try to choose starting from the a because we need to find lexicographical smallest subsequence right so when we will try to choose from a i will first choose the first occurrence of that index starting from the beginning of the string you can see from the beginning index a occurs at this position okay so i will try to check if i will choose to take out this character a i will be able to choose all those remaining characters that we have still not chosen that is b and c that is if i will try to choose a i must be able to choose the characters b and c just after that index okay so last vector is going to help us in determining whether we can choose this character a provided that all the remaining characters we are able to choose after that index and that is the index 2 okay so if i will choose a at this position 2 you can see the last occurrences of b as well as c is strictly greater than 2 it signifies that yet yes we can choose the character a okay so what i will do is look like i will append this character a to our answer now this is discarded i have like i'm done choosing with this one okay so next character that i need to work up on is the character b so can i able to choose b so what i will do is i will look out for the last character index that i have chosen which is at position 2 so i will iterate after the position 2 and find the first occurrence of this character b so it is present at the index 3 so can i q able to choose this index 3 or not so what i will do is i will check it out whatever the remaining characters except b that are present and we are yet not chosen and we can choose that character after the current index that we are working upon that is the index three so you can see the character c has last occurrences as 4 present that's present at 4 which is strictly greater than 3 so we can able to choose this character c later on also okay so it means that yes we can choose the character b right now so this b is chosen so i will append b to our answer and i will discard it okay so last position is this one so i will uh starting from the last position three that is greater than three i will first find out the first occurrences of the character c which is present at index four and all the remaining characters except c i need to check it out whether we are able to choose that characters after the index 4 or not you can see when this when discarding c there is none of the distinct character that is present over there so we can choose c okay so this is the lexicographically smallest subsequences that we are going to form note that why it is lexicographically smallest subsequences because we are starting from the smallest character right so this will give us the smallest subsequences okay now we need to check it out for this uh this index so i need to first fill up the last values of all those positions so where i can do that so let me write down over here last stop this a you can see is present over here which is 2 so last of b which is present over here which is 6 so last of c which is present over here i will write down seven and last of d which is present over this position four okay so let's try to fill out the answers okay so i need to start from the character e right so for the character a i will start from the position zero and find out the first occurrence of this a you can see first occurrence of this a occurs at index two okay so i will append this character a to our answer only and only when whatever the characters except a we can choose after the index two uh what how we are going to check that like all the characters last indexes must be greater than two strictly greater than two you can see six is greater than two seven is greater than two four is greater than two so yes i can choose this character a so i will discard this a yes it is chosen okay now let me look out for the character b okay so starting from the index three uh because we have chosen this index like we have chosen the character a at the position two so i will start from this three i need to find out the first occurrences of the b starting from this three okay so you can see b occurs over here that is at the position six okay so b occurs at the position six so i will be able to choose b only and only when all the characters except b that is the c and d must have their last checklist it's greater than 6 so you can see 7 is greater than 6 but 4 is not greater than 6 so we are not able to choose b so i will not choose b ok so b cannot be chosen over this position ok so can i able to choose the next smallest character that is the character c so let's check it out starting from the index three find out the first occurrence of the character see you can see c is present over this position three okay so all the characters except c that is the b and d must have this uh their last indexes greater than this three so you can see the six is greater than three four is greater than three it means that yes we can choose the character c so c will be discarded and yes i am able to choose c okay so in the next step again we will start from the smallest character but we will start from the character b because we have chosen the c so can i able to choose b right now or not so b occurs at this position six okay so i will i need to check it out whether we are able to choose the character d or not but the uh you can see d has the occurrence as four and uh like this should be greater than six so it is not possible so b cannot be chosen so the next smallest character i need to check is d so i should pick up this d and similarly you can check out all those you will get the answer as a c d b i think yes if i will look at this one you can see ac db is the correct one okay so this is the sequence of step that we are going to do if you look at my submissions i have one of the submissions being accepted over here that is quite hectic to implement because yes i need like i have taken some time to do that so what i've done is like taken anna string's length and previous as minus one and this will store the last occurrences of every unique character okay so i've taken this answer and i have implemented a while loop that is an infinite loop and we need to stop when this boolean variable is remains true at the final each time i will try to pick up start with the smallest character if that character is int max it means that yes it is chosen it means that your this distinct character is chosen otherwise you will start from previous plus one index and i will find out the first occurrences and this will be stored in the index okay so i will mark this boolean variable done as true and start with the smallest a and goes to z and if all the remaining characters which is not chosen uh like the remaining distinct character if the last recurrence is smaller than the current index we can we are not able to choose the current character which is the character ch okay so if done becomes full and we need to break so if done remains true it means that yes we are able to choose the smallest character ch so we will make a stop as false that is we need to move out to the next condition the next step to choose the smallest character and we need to also push back the character c change the previous index and also this last occurrence make it to int max because it is chosen right now and we need to break so if stop remains true we need to stop this while loop so this will give you all test cases fast but you know the complexity is not good so we need to do something better so we are going to move on to the stack based solution okay so how we are going to use the concept of stack to solve this problem efficiently so let's try to understand that so let me just erase all this one okay so that would be better if i will keep something some information that would be quite helpful uh okay so let's try to understand how stack is going to help us to solve this problem efficiently okay so what i am going to do is like i need to write down the characters uh like push out the characters efficiently and we will try to find out the lexicographically smallest uh by iterating it directly okay so how let's try to understand how we are going to do that suppose we have the this string bc abc okay so the first occurrence is b okay so i will push out this into my answer and next smallest next character is c now you can see b is greater than c okay so still the lexicographically smallest criteria is valid because you know b is smaller than c suppose so we have the character ba so there might be possibility that we should choose a then we should choose this b later on right so but we have this b and c right now so we will push out this directly into our answer now comes the character a now here is the tricky point so when a comes what you will do is if you will compare the characters at the top of the stack of your answer which is the character c and the character a now you need to pop this out let me write down pop out character present at the top of stack present at top of stack when we are going to pop this character out when this character can be taken like we can take this character later on when this character can be taken later after the current index then we are going to pop this character out because you know a is graphically smaller than c so putting a earlier is quite a good option right so what i will do is like i will check it out the last occurrence of this c you can see last stuckness of c is four and is still a is at this position which is at the position 2 if you consider 0 best indexing so it means that yes we can choose this character c later on so what i will do is like i will pop up this character c okay and put a over here again we will compare this b and a so you can see b has the last occurrence uh greater than the position 2 which is the current position of a so we will pop this br out as well so my stack would contain only the character a at the top now comes the character b so you will insert it push it directly and the character c now this is the lexicographically smallest okay so let's consider the example case for this one okay so let me just uh okay so we are talking about this one right now so we have this character it's okay so we will start from the character c okay we have the c now comes the smaller character than c which is b so we will compare the you can see whether we can cover this character see later on uh that is the after index one so we will look out for the last index of c last index of c7 so yes we can cover up this one later on so we will pop this c out okay so my stack would become the character b now comes the character a so we will check it out the comparison between b and a okay so uh when we are comparing this bna you can see that b can be covered later on which is 6 and the current position is 2. so we can pop this b out so my stack is only a now we will look out for c and d so you can see both c and d are like this one both are like greater like you graphically larger than their previous character present at the top of the stack of your answer so a c and d will be pushed directly now again comes the character c so you're not going to compare it because you know c is already present in the stack and this is already lexicographically smallest okay so we are not going to compare c with this one okay so we will look out for the b again you can see when we look out for the b you will pop out this character d only and only when d can be covered later on after this index b now index b is six and the last occurrence of d is four it means that all the ds had been exhausted so you cannot pop this d out so what you will do is you will push out this b directly now comes the character c now c is already present in the stack so you're not going to uh do any uh any operations over there so this is your answer acdb so if you look at the answer acdb is the correct answer so let's look at the implementation how we can implement that efficiently so we will be having of end time and of n space code uh yeah okay so we will be having the answer and nf strings length and last and visited will check it out the last occurrences and whether we have visited this character or not while implementing the stack solution so you can see i have iterated for the end times and when the any character any unique character is already present in the stack we are not going to move further otherwise mark its occurrence in the stack because we will push out the character last like at the last of this operation okay so while answer is not empty while we have a non-empty stack of your answer we have a non-empty stack of your answer we have a non-empty stack of your answer and we will compare the current character with the stacked stop character which is answer back and you can see if we need to like we need to pop this character at the present at the top of the stack only and only when its last occurrence is going to be greater than the current index that is we can cover this character later on okay we can cover this unique character later on right so if that we can if we are able to do that we will mark its occurrence as false in the visited vector because we are going to pop it out and we need to cover it later so which we should make it as false right so that later on we should we are able to process that character and we are also going to push back the character uh the current character s of i at last when this operation has been done push out in the stack of your answer and finally return the answer this will give you all test cases passed so if you guys have still any doubts you can reach out to us through the comment section of the video and thank you for watching this video
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
1,046
whereas a last stone wait we have a collection of stones each stone has a positive integer weight each turn or doing some kind of simulation we choose to choose the two heaviest the stones and the smash them together so for every iteration we get the two heaviest them so we're looking at some kind of maximum priority queue suppose the stones have weight x and y with y be the heavier one thus the result of smashing them together will be if they are the same weight they just destroyed each other if Y is a strictly heavier than X then X will be destroyed and the Y's weight would be decremented by the weight of X so I guess we push this back to the priority queue push the remainder back to the Friday queue in the end there is at most of one stone left we need to return the weight of this stone so here is the example two seven four one eight one so in the first iteration we grab seven to eight the difference is one so we push up one to the end we end up with a new collection of stones with two for 101 and we smash two and four together the remainder is 2 so we push it back on to the party queue the next generation we grab two at one and push the you know the difference back to the priority queue then the two of the 101 cancel each other we push nothing back to the barbecue and in the end we left with one stone with weight one so that's the whatever version return yeah so the this did this question is really straightforward we're just going to use a priority queue to simulate the process the time complexity would be a log and mal Ganis T is time complexity for the you know for the pop and push operation this part acute and is that for each iteration we extract two stones and we at the most pushback one so we the lens the size of the problem is decremented by at least one in each iteration so since we start with n stones it's a linear in terms of number of iterations a guaranteed so it's a and multiplied by the time for the end is the for the loop and just for the logins for the operations so it's n log N and space it's a linear as well so I guess we wouldn't really do this in place with this us because that would just destroy the values if you will be potentially used in somewhere else you know so yeah we were passing we won the big a copy of the stalls and push that a copy onto the priority queue so let's cut this thing up we have a priority queue of the integers which we initialize by copying the by copying and making the values into the heap ordering there we were just simulate the process until we left with less than or equal to one stone in the prior to cure if we have more than one stall we can always do a smash we extract that to heaviest stones weight one its peak you back top I forgot and after we extracted the value we should pop it off as well we do the same thing for a stone of the second largest weight if the stones weights are not equal that's the only case when we need to push back a smaller stone since as well as w1 is extracted before w2 its guarantee that for this maximum a priority of w1 this guarantee to be larger than or equal to w2 so we can just push the difference back to the product here and once we terminated with the criterion that it's less than or equal to one if it's zero if it's empty we just return zero otherwise it would just be the only number that's left on there Park you so the condition would be PQ door everything yep so yeah so this is so cool that's pretty straightforward let's see it works yeah it's working okay all right so this is a question decoding question for today
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
1,668
Hello, in this video we will see Maximum Repeating Substring, so this is an easy level question of lead code and let us understand from the example, so the first word is opened in sequence, the second word is called word itself, right, so we have to find this thing in it, so if Now it is right, how many times is it repeating now, so you can see that now it is repeating twice consecutively, so what is its output, if I have modified this a little and now I have added one more layer here. You can see that ABAB is doing the shape and now again doing it but it is not consecutively so what is the highest consecutive two times then the answer will remain the same from Remain to two right but here and if I modify by modified And now so if you can see, here now what is this our 3 should be if the word itself changes and becomes the word ABC ABCD so ABC DI is not shaping even once right then what will be the output of our The question is friends and now we understand how we can approach this, so I have taken the first example and through this we will try to build an approach, so what will we do? Now we will try to find this. Right in the string, we will take two-three this. Right in the string, we will take two-three this. Right in the string, we will take two-three variables, the first one will be count and initially it will be zero and second one, we will take the word, you find this word, we have to find it and we will keep the initial word, whatever we find, this will be the first word. Now what will happen for 'right' and if we Now what will happen for 'right' and if we Now what will happen for 'right' and if we search for this word then 1234, I have done this indexing, so we will do it in Index of Java, to get its index, what does index of do? It will search for this word in the string and if it is found then it will be indexed. Will return zero starting index so IDEX what can we get if found if it is not found then idex or could be -1 if not found then we will check here -1 if not found then we will check here -1 if not found then we will check here if idex is -1 then which is our If if idex is -1 then which is our If if idex is -1 then which is our If account is there, we will return double equal to -1 then we will return count, whatever is the count, just -1 then we will return count, whatever is the count, just -1 then we will return count, whatever is the count, just like now if account is zero then if it is not found in such a string then we would have returned zero but now we are getting right now so we If you will not return then first of all we are getting some value like we are getting zero, now it means this is the word, so first of all we will increase the account, write and change, you are trying, okay now again we are doing the same. If you do less again then this thing will be found in it again. Now the mines found are not in van so they will come in it again the value of the account will increase. In the first time it was van and what will happen this time, van will become you and you will become and Again what will happen in the word 'tu find' will and you will become and Again what will happen in the word 'tu find' will and you will become and Again what will happen in the word 'tu find' will also change and again who will be catenated in this, meaning look, we have got two repeating words and we are getting a little greedy and we are asking whether these are three consecutive words. Okay, then again if we try to find three consecutive words then we will not find such a word here right and if we do not find it then what will be the IDEX -1 -1 then IDEX -1 -1 then IDEX -1 -1 then what will be the time and the account will be returned right Let's go to the account return friends and code it. Let's see whether our solution is acceptable or not. I have expanded the coding panel and here we do 25, so the initial will be equal to the word right and will be zero and we had to repeat that process until the index is If it is not -1 then we will until the index is If it is not -1 then we will until the index is If it is not -1 then we will take a loop here and set it to true, it will continue to run, the right computer will be there, when our world you find will no longer be found, then here we write IDEX index IDEX equal, you take a little more us here. So this time again we will get it and this time what is the index of return? Again the index of return will be zero, then again the value of account will be from van, then this word will be modified, word will be found and this time three will be returned. So the three that will come on this now will come from here right so what will be the return here 01234 so the index is matching from here so the return on this will be 5 index so we can reduce one more and here we will take the whole string na By considering, like now we start getting from here, so if we consider only the string after this, then we will have a smaller string for index off, so we can do one less and that, in this, here one less and which we What we can do is that we can reduce the sequence a little, we take the sequence sub-string and the beginning from a plate in it and what will we find in it, index of word, you find the word we are looking for, if it is not found then we We will return the account, if that word is found, then we will try to increase the value of the count, so count plus and word you find, we will contact you, we will add another word and then everyone repeat this less. We will do this and will also update the beginning, like in the second exam we were taking, it would be 'submit' and take only one millisecond and the it would be 'submit' and take only one millisecond and the nation which is beating the 93% solution has taken some time, so we will replace it, our time will be reduced. No, so what will you do, here you will write the word, you will find it and we will write it as word and we will comment on it and submit it to you in the next video.
Maximum Repeating Substring
find-longest-awesome-substring
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`. Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_. **Example 1:** **Input:** sequence = "ababc ", word = "ab " **Output:** 2 **Explanation: ** "abab " is a substring in "ababc ". **Example 2:** **Input:** sequence = "ababc ", word = "ba " **Output:** 1 **Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ". **Example 3:** **Input:** sequence = "ababc ", word = "ac " **Output:** 0 **Explanation: ** "ac " is not a substring in "ababc ". **Constraints:** * `1 <= sequence.length <= 100` * `1 <= word.length <= 100` * `sequence` and `word` contains only lowercase English letters.
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
Hash Table,String,Bit Manipulation
Hard
null
1,980
hello hi guys welcome back to the new video uh sub Changi I hope that you guys are doing good so in this video the problem find unique binary strings we'll see all the variations as in from the very basic Brute Force to actually optimal more optimal like we will see four optimality for it cool uh let's see let's start begin with the question what the problem says we are having an array and of strings nums containing any unique binding again it contains in unique binary strings each of length n okay we have n strings and each of length n that's also a plus point which is for us to remember each of length n and n binary strings which we have cool we have to return a b binary string of length n which does not appear in the nums so which is not in the nums itself you have to return that particular string for us uh if there are multiple answers because for sure it can have multiple answers we can return any of them uh for example if you just take this case so you will see that 101 as a binary string is not appearing in this 111 0 1 0 and 0 1 so for sure that can be an answer again answer can be also 0 because it's also not appearing answer can be anything which is not in my nums so the first very Brute Force thing which comes in mind is okay it's just a binary string right I have to check if it is okay I have these input as n strings and I have to make a binary string of length n and then check if it is there in the input not so rather what I can do is I can make my all binary strings which is having that one zero which means I know the length is n so how many such binary strings I can make 2 power n binary strings out of it now what I'll do I'll just consume that and I'll say okay this is my input right now this is my new input now I'll just hash these strings these n strings out right now uh when I have to say n of nums so I'll just say as in the number of strings are n the length of strings also n so I just say number of strings and length of strings so I want to Hash all these in the number of strings so I'll just hash all these strings out and say okay 111 is present 011 is present 0 01 is present now when I am making all these to power n strings because ultimately it can be how to power n at every place there are two options 0 or one place a z or a one place a 0 or a one place a z or a one so two options for it and again two options for every of the characters how many number of characters n characters I can have because the string this string itself is of length n so for sure the options are 2 power n so what I can do is simply make all the strings out and check okay uh I can just next when I have made all these strings out I can just simply iterate on all of these strings which is to for n strings and while I'm trating I can check okay is that in my hash set or not is that my hash set or not so with that I can simply achieve my result but you will see that n is oh like for sure it can work because n is just 16 it's pretty small so for sure this approach can also work which in which you find out all the strings possible of that particular length n and then just check okay was that in my haset was that my haset or not so you will see that it's it will be nothing but a to power n now just to check a hashut it just takes o of one operation so that will be nothing much so with this and it's a simple recursion which you can apply as in what you will do is you know that okay it's your um now one way is just simply make all the strings first and then ultimately check after making all these strings or other ways while making the strings itself meanwhile check which means in your hash set firstly hash things out okay not that hash but simple hash uh so firstly hash things out which means 1 0 like these are three so I just simply hash it out and say okay it is there in my hash set now when I'm doing my recursion and just I'm just iterating and being and building all my those uh strings 2N strings so while I'm just checking which means you can have a base case we'll go to Bas case later but simp ultimately at every uh current string I just try to push in a zero and I at every currency I'll try to push in a one at any point of time if I can get any of these strings and ultimately in my base case I'm just checking okay as soon as the length reaches N I can just check if that was in my hash set or not if that was not in my hashset then simply return that because I have found a string which is not my haset else simply return an empty string just to have a check that if the empty string is being returned it's not a valid string so please don't consume that only consume the string which is non empty so just a condition that to know that the string which is being returned is valid or not so with this you will see that in worst case it can actually go to 2 power n chances now that is simple point which we put out that okay we'll just try on like first thing we saw that we can just try on all the possibilities which is a 2 N and then we can just check hasard but then we thought of okay meanwhile while making the like strings itself which is these strings meanwhile we can check if that was present if that string is not present in our hash or not so we saw that okay it can have a complexity of 2 power n but I'm asking you is it actually the case that the complexity is exponential to power n no so if you have ever heard of pigeon hon principle so it's not exactly pigeon whole principle like pigeon whole principle just says that if I have five pigeons and four objects for sure in one box two pigeons will come for sure that's a pigon principle but similar to that is this like is just a similar kind of principle you can just classify this as a pigon hold principle type that if I have let's say three pigeons named as a b and c now if I have let's say five other pigeons in this case I had n pigeons and two power n pigeons like when I say five other pigeons I'm saying okay I have five other pigeons which is let's say question mark now out of these five pigeons I have to figure out one pigeon which is not in these three pigeons right so a BC I have to figure out any of these which means I have to figure out in this particular input of five pigeons just one pigeon which is not in my above three pigeons so what I can do like is it actually required to go on to all the five pigeons to just get one pigeon out which is not in the above I'll say no just go if you know that you have X number of pigeons which is a b and c so just try for x + one pigeons and c so just try for x + one pigeons and c so just try for x + one pigeons out of those five pigeons so that you can just get one pigeon out and why are in this X+ one will work because in this X+ one will work because in this X+ one will work because in worst case it can happen is that all the X pigeons which is these all starting three pigeons are exactly a BC a b and c then when I will check for the fourth pigeon for sure I'll get a pigeon which is not in a b or c so it is just that uh you have an input of three pigeons so just try for four pigeons at Max you don't have to try for all the five pigeons or let's say it would have a 500 pigeons so you don't have to try for all the 500 pigeons for sure at Max in the worst to worst case if you just go and sequentially try for the starting five pigeons you will or basically any five pigeons you will try sorry any four pigeons which is x + One X + one if you pigeons which is x + One X + one if you pigeons which is x + One X + one if you try for any of the x + 1 different try for any of the x + 1 different try for any of the x + 1 different number of pigeons for sure in that itself you will find a pigeon which is not inside your these X pigeons because it's plus one right you're just trying for one more pigeons in worst case you can match X pigeons but not X plus one because you only have input of expence that's the reason what we can do is in this above example was that we know that we only have n strings as an input but we are actually building a two power n strings so while we are building it and we also know while we were building it we are also checking it out so in the worst case this can actually go to Just n + 1 and this can actually go to Just n + 1 and this can actually go to Just n + 1 and that is it after that it will not go because in this n + 1 chances itself it because in this n + 1 chances itself it because in this n + 1 chances itself it can find the string which it wanted and then it can simply return that string so this function which we wrot which we wrote so as it's a recursive function so for sure it will go and try for building one string at a time so it will just go and try depth for search build one string and check if it's there in hashad then come back and then try to make other string come back try to make other string it is how a DFS or recursion works so it will go in depth and try to make that string okay one chance done other chance done so as soon as the N plus1 chances are done for sure it will be returning something which is value valuable for us which is the actual answer which is not in those end strings and that's how this thing which we saw earlier here which was which we were thinking that would go to 2 N * is will thinking that would go to 2 N * is will thinking that would go to 2 N * is will actually go to n + 1 * itself now just actually go to n + 1 * itself now just actually go to n + 1 * itself now just one thing although in C++ world you can do a string. push in C++ world you can do a string. push in C++ world you can do a string. push back of a character which is that a mutable string which can actually make this operation a o of one operation but if you don't have a mutable string as in other languages so this operation will also cost the O of n operation because you have a string of length n if you just add a character so again that will be of length n so basically you are just having an operation on a string length n so that's the reason this can which means this addition operation of a character inside a string can act as a extra o of n character so this will have a complexity of O of n for sure just simple recursion will go just end times but this string like modification operation can also be overend so please make sure that it can have a complexity of O of n square space will also be o of n Square why because for sure you will in a has said you are hashing out all these strings n strings hashing out all the strings every string is of length n so for sure hashing itself will take a size of n square and for sure the recursion itself recursion is nothing but a DFS so it will also have the internal stack space which it will take let's see the code quickly again it's not the most optimal code it's still uh space and time of what is we are thinking okay it's not much because RN is pretty small it's 16 but still we actually will optimize it more further but let's go see the code it's simply as what we saw above we have a base case in which we'll have a num set this num set we'll just say that all the strings in nums just hash them out and insert in your num set and then go and quickly call the solve function will go and firstly it will try to add a zero it will try to add a one when it will try to add a zero it will just check whatsoever is return if it is actually uh not empty which means um this is not empty which means it has not being in the num set then for sure return that answer else uh you can just simply go and solve for current plus one and for sure this will return the answer because we are actually bound to return the answer because the question says that you will return the answer so with this fact you can easily solve it but is it optimal no can we try it better yeah we can so what we saw above we can just use the same thing earlier we using strings and we know that we can convert the binary strings to numbers so rather using string because you saw now that because of this thing of modification of a string you were actually consuming uh much more time and space so rather being going in the string format can't we go in the number format because we can convert B strings to numbers very easily so what we will do is we know that we use exact same kind of same binary uh the pigeon Hood principle but we'll just convert those strings to numbers what will happen now is we have these three strings as an input is this example three of our question we just convert those two numbers itself we'll convert this to numbers it will become like this and just simply if you don't know how to convert a string to numbers in C++ is just a string to numbers in C++ is just a string to numbers in C++ is just a string to integer if you just pass a integer which means if you just pass a string let's say if I pass a 1 so if I just do a string to integer of this one1 it will just make a one1 as a number but I want I know that this number is in base two so I'll pass a starting index okay starting from this index you have to do in a base two as a number so I'll just pass string to integer that particular nums of I and then starting positions and then the base okay it's a base to number so with this I can simply convert my string to an integer now when this is done again the same concept try for the starting X+ one I know these are for the starting X+ one I know these are for the starting X+ one I know these are x number of basically n number of strings so I'll just try for n + one strings so I'll just try for n + one strings so I'll just try for n + one starting n plus one I have three strings as input I'll try for the four strings or four numbers starting four numbers I'll try for 1 2 3 and 4 or I should say 0 1 2 and 3 anything again I said try for any of the N plus1 numb still you will get the answer so I'll just try for the four numbers any four numbers and for sure I'm bound to get answer in that now but try to try that number I have hashed as a number so I can try okay let's say um I know that one is not okay one is there so that could not be answer two okay two is not there so two is the answer but I have to return the answer as a binary string not as a number so now when I have got the answer I know that two is the answer but now convert this two to a binary string so what I will do is I simply convert this two to a binary string but of size and itself so as you know that the string maximum length is actually 16 so what I can do is one way is just manually converted by using a function other ways you can use a bit set so bit set is nothing but you can represent a number as a bits so what I'll do is I'll convert this number to as a bit set of length 16 okay this bit set 16 this number we actually convert this number to a bit set of length 16 and then I'll convert this bit set to actually a string now this bit set is which is actually 0 1 0 has become a string but now you know that I have to only take the last n characters so what I will do is whatever string I have got let's say s in this case I'll just convert and I just take the last n characters of this string by using a s do substring of 16us because I know the length is 16 because I have made a bit set of L of length 16 so I just convert this 16 length bit set or basically string now ultimately to a last in is I'll take and convert that to a string and I'll ultim imately get this particular string right here so it's just simple string to integer just hash the integers out and just check for the n plus one integers and then ultimately convert that integer which you have got the got as the answer back to a string by making it a length 16 converting that to a string and then converting that 16 length string back to a three length string which is last like last figure does and then giving that as an answer so again that will be off we'll see why the time is this but that will be time of O of n square and space of O of n now how this is done exactly same as what we saw firstly we'll just have unordered set again we will just have iterate on all the strings every string I'll convert that to a integer of base 2 and then insert that in my set now when this is done I will again go to all the n + one numbers will again go to all the n + one numbers will again go to all the n + one numbers see I'm going on to 0 to n I'm going on to n + one number I'll go to n plus1 to n + one number I'll go to n plus1 to n + one number I'll go to n plus1 numbers and say okay if that is inside that is not inside my set so that's my answer if that is my answer bro convert that to a bit set convert that to a string and then take the last end characters of that string and return that as an answer so with that I can just simply get it solved now converting which means iterating on all the end strings okay itating on all the N strings o of n operations converting a string to an integer of length n is again o of n operation because string is of length n itself so that will be o of N squ and this ating on all the n+ 1's like this ating on all the n+ 1's like this ating on all the n+ 1's like numbers it's O of n + 1 plus o of n to numbers it's O of n + 1 plus o of n to numbers it's O of n + 1 plus o of n to convert that number to a string so that will be o of n itself you can say so that's the reason that the time comp will be actually o of N squ and space is O of n because I have I'm consuming a hash set of n integers is just an integer itself so that would be just o of n itself now again we have optimized quite a lot in space but can we optimize it much more further yeah we can let's see how so now what we're going to use is a simple trick you don't need to know a can's diagonal argument or anything like that it's just a algo or the kind of a concept but you don't need to know anything about that don't even remember the name but the only concept is what you wanted was something which is not inside those n inputs so now you know that you have these n inputs so how about I just try to make a string out which is considering okay I will not consider the first string second string third string which means I want an input of size three right so what I will do is I'll just say okay bro I want a string which is which should not be same as this right so if I just modify one character of this string just one character the first string if I modify one character for sure it will not be same so what I will do is I know that I can modify one character so I will just modify one character and I can modify any character for Simplicity modifying the first character of the first string I modify this character and make it Opposite now I don't know whatsoever the remaining part is but as I modified the first character for sure it will not be same as the with that of the first string that's good for this second string I should not modify the first character itself because for sure I have already modified it and if I just modify it back to other number it might actually become same as the first string so what I'll do is for the second string to not make the string output string same as the second string I'll modify this second character okay I'll just modify that characters oh for sure now this string which is being built okay it's a 0 which is being built right now it is for sure not same as these two strings now again for the third character I again say just modify the third character for it okay I just modify the Third and I'll get again a zero so with this you will see that what I'm trying to build is I'm trying to say okay for the first string just take a character which is the first character and I'll just make opposite for sure the output which I'm which the output which is which I'm forming right now I'm making it bound to not match of that of input and I'm doing it for every character thus the string which I have formed ultimately will satisfy that it never matches third second or first string and that's the reason our this can be our answer ultimately what we did was just going onto these indexes flipping them out and returning a opposite value and adding in your string that's it you are doing nothing else and that's the reason this can be solved now R in what if I had other string also of like of length n for sure you could not have done this why let's say I had other string 1 Z so you need one more space you cannot modify these ex existing three space so it was possible only because it was n strings of length n that's the reason cool let's quickly see it's pretty simple we go on to all of our n strings right for every string I'll go on to that specific II character as I showed you II I right I characters I went on and I just said okay if it's a zero take a one if it's a one take a zero so just take opposite so I'll just take this I keep on adding in my answer and I'll simply return that as an answer you'll see I'm just going on to all the N strings so that's the reason the complexity of N and nothing extra space is being used so it's overun again uh it's just one thing that this operation of answer plus of that particular character it's a costly operation so rather use answer do push back of that particular character because that will actually increase your time complexity so make sure that you actually modify and use answer to push back rather than just adding your character in your answer or basically a string in your answer because adding a string or character in your answer actually increases time elocity cool I hope that you guys got all the four methods from exponential to why exponential was not exponential to converting that to a number so as to reduce the space and then ultimately to a most OP solution that just considering that all the uh strings I'm just trying to make a new string output string different from all the strings bye-bye
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
1,562
hey everybody this is larry this is me going over q3 find latest group of size m uh so this is actually a tricky problem uh i think the easiest way to do is by simulation um so the first thing to notice with simulation uh is that notice the n so n is going to be 10 to the fifth which is a hundred thousand so you so really naive some simulation is probably going to be n squared uh so we have to figure out how to do better than n square with simulation right so the way that i solve this problem and i think so i think i knew how to do this immediately uh so i don't really have insight into how to think about it but i think my the way that i thought about it was okay i need to seminate uh the best way to do this is just by simulation uh and we need a way to kind of merge these groups together like all these i'm looking at step two here uh and then when you put this one here you merge two groups of ones right uh in step four and then keep it's just a lot of bookkeeping a lot of things to track all right and from that i know that if we want to sim like if you do a naive simulation and this merging step takes over n then it's gonna be n squared but we could get it down to o one or you know acumen's constant or reverse arguments constant or inverse reverse ekman's constant something like that uh effectively constant then we can have a good time uh or even log n then it would just be n log n but that's fine we didn't find in different uh implementation you can't do that um so i end up doing union find because i look at these ones such as um merging to the left and merging to the right and then whatever that they're connected to and then just kind of keep track of a lot of things i know that i'm hand-wavy a little bit i know that i'm hand-wavy a little bit i know that i'm hand-wavy a little bit on keeping track a lot of things we'll go through the code together so that you can understand what we're keeping track of so first these are my union fine operations um usually i only implement the union and define but in this case it seemed to make sense that i also keep track of the size because well we have to keep track of the size um so then we i just implemented the size tracker i actually don't do the merge by rank or by size because i was a little bit lazy and usually it's not super necessary uh as long as you have path compression uh don't take my word on it do your own research play with it and also just return the size of a node by getting you know the size of the parent so that uh yeah that's kind of how i add a helper function um and then the simulation is just okay so for each index and index is just a time step right of the array uh so we now simulate from left to right one step at a time we look to the left uh and if we already used left then we want to merge it with we want to get the size uh if we only use the right meaning that you know let's say we're here you know look at the left look at the right if it's already taken then you know you get the size of the left and the size of the right and then the current size is always going to be one because you're just putting it in right current size being the uh the size at x i know that i did this weird thing here uh because i just wanted for symmetry reasons but yeah so the left is equal to the size of the left um so now we merge them together so what's the new size is just the size of the left plus the size of the right plus one which is the current size uh and then now we know that we keep track of all the counting uh first of all we you know there's no numbers in the list but when you put in uh one number then it'll be plus one right um because by itself it's just one element and then you remove it because well that's what you remove and also the left sides we subtract by one on the right side we also subtract by one that's the number of um components and then from this we increment a new size right so basically for example if you have one element to the left one element to the right and you insert one then you now you went from two single elements to one three element right it's a new element so that's kind of the simulation that i have and also just keeping track of what we used uh and then after that we just have to do a union on the left and a union to the right um and then at the end of each simulation step we just see hey uh is still um a group of size m right and if that's true then we set the you know now is the latest time you could actually probably just set latest as you go to index one but i like writing like this just in case sometimes in different problems you may change certain orders and then you know this might bite you but that's how i like to do it and i know it's a little bit more efficient it's not just you know it's you don't need to be that efficient um but that's pretty much it so simulation plus union fine and keeping track of stuff um so you may ask i think a common question that i might get asked is well okay let me finish the complexity first uh but because for each element we do have at most two union operations and two size operations and let's just say it's log n because whatever then it'll be n log n uh but actually we even do path compression so the actual compressor will be shorter than that um so roughly between end to end log n say so that's the running time complexity uh the space complexity is off and we have a number of arrays that we use to kind of uh keep track of stuff but um but yeah so roughly linear time linear space is the complexity of this form and then the question you may ask is because i get this a lot um in problem solving in general is how much of the union fine do i remember and actually one is we see me salvage live next uh none of this is copy and paste i just remember it from my head and i just kind of do it uh so i do remember that you did fine and the union and then because i have an understanding and i don't me if it sounds braggy i'm sorry but it's just that like i remember how you know what these code means to me uh and from that i could just add to size really easily um because you know i think about these as trees and nodes and stuff like that right you know that's what these parents do um so i urge that if you have trouble implementing it just practice more um you know it's not impossible i believe in you and try to get the understanding uh as much as you can uh but yeah but for me i actually implement this from my head so i don't have any templates or anything which may be not great for contest timings but you know um for me i don't worry about contest timings i don't care about rank that much i know i've come right around a bit uh at least for you know because i want everything in my head right um cool uh yeah that's why for this problem watch me stop this live next um okay oh okay so exists okay people are pretty fast you okay so oh i need to do the size i want this um um you um hmm oh this is not mine this is just hmm all right oh i don't union either but that's fine i have a lot of bugs why is x negative one okay this hmm oh this is hmm this is not used yet there must be an easier solution to this but i'm choking a little bit okay hmm what let's count this in the white iron two so this is just not right okay do this not confident about this at all hey everybody thanks for watching me self just uh explain these problems uh i have a video for before the con for this contest for the screencast let me know what you think hit the like button hit the subscribe button and join me on discord ask questions have fun and i will see y'all next contest bye
Find Latest Group of Size M
people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an integer `m`. Find the latest step at which there exists a group of ones of length `m`. A group of ones is a contiguous substring of `1`'s such that it cannot be extended in either direction. Return _the latest step at which there exists a group of ones of length **exactly**_ `m`. _If no such group exists, return_ `-1`. **Example 1:** **Input:** arr = \[3,5,1,2,4\], m = 1 **Output:** 4 **Explanation:** Step 1: "00100 ", groups: \[ "1 "\] Step 2: "00101 ", groups: \[ "1 ", "1 "\] Step 3: "10101 ", groups: \[ "1 ", "1 ", "1 "\] Step 4: "11101 ", groups: \[ "111 ", "1 "\] Step 5: "11111 ", groups: \[ "11111 "\] The latest step at which there exists a group of size 1 is step 4. **Example 2:** **Input:** arr = \[3,1,5,4,2\], m = 2 **Output:** -1 **Explanation:** Step 1: "00100 ", groups: \[ "1 "\] Step 2: "10100 ", groups: \[ "1 ", "1 "\] Step 3: "10101 ", groups: \[ "1 ", "1 ", "1 "\] Step 4: "10111 ", groups: \[ "1 ", "111 "\] Step 5: "11111 ", groups: \[ "11111 "\] No group of size 2 exists during any step. **Constraints:** * `n == arr.length` * `1 <= m <= n <= 105` * `1 <= arr[i] <= n` * All integers in `arr` are **distinct**.
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is the maximum number of elements in a list.
Array,Hash Table,String
Medium
null
1,010
hi everyone welcome back for another video we are going to do another little question the question is pairs of suns with total durations divisible by 60. you are given a list of sounds where the iv song has a duration of time i seconds return the number of pairs of suns for which their total duration in seconds is divisible by 60. formally we want the number of indices i j such that i is less than j with time i plus time j mod 60 is equal to zero let's work for the code we know that requirements are based on module operation properties a pair of elements satisfy the requirements if both elements are divisible by 60 or else the element a mod 60 plus the element b mod 60 is equal to 60. we initialize the array with the size of 60 to store the frequencies of remainders since the remainders are from 0 to 59 we iterate fully array time to find the pairs of elements that meet the requirements for each element we set t equal to the element mod 60 if t is equal to 0 we add the array element at index 0 to n which is the number of elements that can pair with t else we add the array element at index 60 minus t to n we also need to increment the array element at index t by one finally return in thanks for watching if this video is helpful please like and subscribe to the channel thank you very much for your support
Pairs of Songs With Total Durations Divisible by 60
powerful-integers
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Hash Table,Math
Medium
null
1,071
hi everyone so let's talk about greatest common divisor of string so you're given s and t so we said that t can divide by s only is equal to t plus t right so uh you're given two uh two string and you have to return a larger string x such that x can divide by both rooms both are in fact so uh here's a quickly solution so if the stream 1 and string 2 if you plus together does not equal uh if that is equal to shin two plus uh string two plus string one then you can continue uh doing the work if they are not the same you are going to return a return empty string so this is basically the first solution so i mean first step of the solution so you have to compare if they are actually equal so which means this one and this one actually equal right so we have to find out the greatest form of divisors based on the uh based on this right so uh if you don't know what experience for multiplication so you can actually go to this website and then uh the explanation is pretty good so you just have to find out the land of the bridges from a divisor for both strings so you are giving a passing two input and then you just keep uh dividing i mean body right uh just keep them all and then if they are actually equal to their name just return uh a y right so i'm going to just copy and paste just in case i don't know what happened so again when we find out the length right then we can actually uh return the length of the gcd in string2 because shinto is always shorter than stream one right and if they are not equal definitely with an empty string so uh here is it so public gcd right so this is pcb so i'm going to pass in gcp function right and then this is some digital right so again so let's just compare so if there are an icon for string one plus string two that's not equal to string two personal one right you will return empty string right and if you do uh if they are the same right you can't find out kind of length so some 50 based on the string one dot lens and then string two down right and then now we know the length of the gcd so we can actually find out so here is it so gcd six and three so uh gcp calculation so i'm going to pass in passing the six and three and then you actually what six and three and then you'll get three right so okay if you do not believe in so this is six this is four right six and four this is two right exactly so you will just return what string two the substring based on from zero to gcp and this is pretty much a solution so um just use a little bit uh strategy to stop this question so this is gonna be pretty much a solution so the time in space for this one you have to add a tuition together to create another string inside the library so i would say this one is going to be although stream 1 plus 32 for the time and then gcd uh specialty uh time implementation is going to be shorter than this so let's not worry about this so unrepresent the length of the string one and string two how about a space so for space it actually looks like constant but this is creating another space so it's still going to be all of um and represent the stream one plus string two so this is the four timing space and this is the solution and i'll see you next time
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
1,675
Hello Guys Welcome to Your Dreams Video subscribe and subscribe the Video then subscribe to The Amazing Difference Between There Operations Subscribe Now To Subscribe Maulik Chintak V Dhund Problem Will Help Us Understand Subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Of The Day Pendant Problem By The Intuition And Lose A Video Difference Between Media And Subscribe The Amazing Entry Loot-Loot Reduce Reddy Idi Hai Loot-Loot Reduce Reddy Idi Hai Loot-Loot Reduce Reddy Idi Hai To Navodaya Jaware Victims In Different 1998 subscribe Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe Loot Subscribe Now A Reminder Elements of Twenty-Five A Reminder Elements of Twenty-Five A Reminder Elements of Twenty-Five News Differences in Three Idiots Idiot Wo n't Give Me This Is the Difference Between the Thing Quite Difficult Problems in the World Which Want to values ​​painting World Which Want to values ​​painting World Which Want to values ​​painting appointed subscribe dude e have differences arise subscribe to okay right now add values ​​into his priority okay right now add values ​​into his priority okay right now add values ​​into his priority cu super-rich values ​​in not cu super-rich values ​​in not cu super-rich values ​​in not interview with multiple subscribe to nine bihar values ​​in the present you when they've nine bihar values ​​in the present you when they've nine bihar values ​​in the present you when they've converted To Avoid Subscribe Now To Receive The Nobel Price Subscribe Computer Will Help In Making subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe Reminded When Top 10 Why Widgets And Up Normally Different The Difference Between The Mission Subscribe Under Your Normal delivery for which means the top 10 value undhiyu billu the current subscribe my channel subscribe if you subscribe to that arvind change culprit why into three fatty acids with oo hai but every 10 minutes email and fax love you all subscribe Loot Will Ooo Will Love You All Subscribe Nodi Check The Value Of Mudda Value Is 90 Even When You Not Effective Victory And You Will Not Refuge In The Lord Subscribe
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
326
welcome to april's lego challenge today's problem is power of three given an integer n return true if it is a power of three otherwise we turn false an integer n is a power of three if there exists an integer such that n equals three to the x power now you can see that 27 is going to be true because that's 3 times 3 while 9 is going to be true because that's 3 times 3 but 45 is not going to be a power of 3. now there's a follow-up could we solve it there's a follow-up could we solve it there's a follow-up could we solve it without loops or recursion but let's start with just using a loop um if we could use a loop it's pretty trivial right all we need to do is first check if the n is less or equal to zero if it is we can return the false immediately now otherwise we're going to iterate here with an x and an i the i representing an integer for from one to have a number and x every number that's going to be a power of three so we'll start with x being one and i being 0. so we'll say while x is less than or equal to n if x equals n then we want to return a true otherwise we could increase our i and recalculate our x to be three to the i power now if we're gonna follow this group and that's gonna be false so this is pretty trivial uh it's probably the typical answer most people give and it will get submitted but uh we'll get accepted but um is there a better way to do this like this would take o to the log three power um can we do this in o of n time now one way we can do that is there's actually a lot of methods we can use like mathematical formulas and logarithms but the easiest way i think is to first figure out what's the maximum number that we can have given these constraints for the nth power so how we can do that is we know that it's going to be within right here 2 to the 31 so we'll say okay let's have n equal 2 to the 31 first power minus 1 and say while x equals 0 while x is less or equal to n let's print out the x and we'll say uh we also need i here then i equals uh zero i think x sections one here um we'll print not x but i will first recalculate our um i plus 1 and x to equal i to the from sorry 3 to the eighth power right and this is going to give us the maximum i that we can have given our constraints so let's just see what that is first um and this should end up being not 19 i'm sorry that works here yeah so we can see that 19 is going to be the biggest high that we can have okay so that's going to be our max number we'll say 3 to the 19th and really all we need to do then is to say well okay if check to see if n is less or equal it's actually greater than zero it's gotta be greater than zero and um max modular n is equal to zero because if this number is to a power of three we should expect that it's divisible all right let's see if this works and this also works and it's going to be of one time as well as one space now i didn't come up with this i did see this in the solutions um i found it pretty interesting i wouldn't have come up with it on my own so i guess it's one of those things that i'm not completely sure how one would come up with this but it works so we'll just leave that at that okay thanks for watching my channel remember do not trust me i know nothing
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
501
Hi friends, our problem today is Find Mode in Binary Search Tree is a daily problem for the lead, it is easy level and I think it is not so tough, it is easy to understand, the problem statement is also there, so what is given to us in this, a binary search tree is given to us in which If duplicate elements are allowed, then let's see a small example. They have given 2 binary search trees with duplicates, so what do we have to return in this? We have to return the value of the node which comes maximum number of times. Either here pay two. If our 2 times is coming then we will return 2 by putting it in the answer. If this H case is ours then the number of notes will be from 1 to 10 power f and the value of node will be from 10 power 5 to 10 power 5. So this is fine, once again I have taken an example 5 3 31 55 So it is a binary tree, I have taken a slightly bigger example so that there is clarity, so in this we have to figure out which is the node which is the maximum number of times. It is coming and it is possible that we have more than one node, so we have to return it in the form of an array, so what comes to our mind first of all, we will think that okay, we have given a binary search tree, we will do the tree two. And if we store it in hash map then we will use hash map in it and the extra space will be taken by us so that is not an efficient approach so even once we will still do a dry run and see if by chance we get these orders. Traversal also has to be done, so if one is put in the hash, then the frequency of one, three is visited here, after that comes three, the frequency of three becomes one, okay, after that comes this three. The frequency of three becomes two. When this five comes, the frequency of five becomes one. After that, this five becomes two. The value of five becomes frequency. The value of three becomes one. Then the frequency of seven becomes one. Okay, so the frequency of one is three, two is five, three is one, then what is the maximum frequency, which is five and if there is more than one element, then we make a list array and give it, then we will give it as an array, but what are the elements in the array ? There will be only one five elements, so ? There will be only one five elements, so ? There will be only one five elements, so our answer is five, but what we did in this is that we added an extra hash map and in the hash map we figured out which key has the highest value in the hash map and which key has the highest value, then return that. If we have to do this then what can be the other better way? The better way can be that we have done the inner journey but what has been given to us is the binary search tree. So this is the meaning of the binary search tree which is on the left side of the quality. When we translate the binary tree in this order, it comes in sorted form because what is the meaning of bye inner tree? First left subtree then root then right subtree then left sub tree all are smaller or equal right sub tree. Bigger or equal then ultimately it comes in a sorted form and in the sorted form if we are capturing three on any movement let's see three on any it which is our traversal right now in traversal if we are capturing three then three When it comes, all the threes will come one after the other, only then at that moment, it will not happen that the three comes at the beginning, it comes later, not later, the three comes again at some point, then when all the equal numbers come together. So why not process them in one iteration, then if you try to write like in the order tra, then what will come is 5, first this one, then three, then five, then this five, then This one of ours will become five, then this one will become sen, ours is okay, so this iteration is done, our sorry, this one was three, 13 1 33 557, so just in this order traversal, we are always on the route, what do we have to track? We will have to keep track of the previous element and on any movement, what will we do? We will just directly call inorder traversal and whenever we are on that node, we will capture its previous element and keep it at that moment and compare it with the previous one. Write a little pseudo code once. Let me show you the solution, ours is fine, we have found the tree node, we have ordered it, we have sent it to the root, so what will happen in this fear, the left subtree will be seen first and then the right subtree will be seen and what will be seen in between. Will process that node, what will it see to process that node, what is the value of the node, the value of the root, we will put a condition on the value of the root, if the value of the root is equal to the previous, then it is okay, we have our Whatever temporal frequency we are capturing, we will increase it at that moment, else we will not increase it, if the current element is the previous element, there are two scenarios, either the current element will be equal to our previous one, like this one becomes ours and the other one becomes three. The second case will be this one, so the first case is this. The second case is this. If in this case, if P is equal to the previous one, then what we will do is we will keep increasing the temporal frequency that we are capturing, but when those elements like this Which is not equal to the previous one, in that case we will reset the frequency and we can continue our coding. Okay guys, once we code it, if we code it will be clear to us the route given. What we have to return is an integer array but we will just track it in the list. We don't know what is the size of the integer array. Let's take the answer and treat it as an answer. Answer is equal to new array. List is fine. After that, we call the recive function in these orders and pass it to the route. After that, whatever answer comes, we will return the answer by making it an integer array. Let's write the code for this: Let's write the code for this: Let's write the code for this: Inger New E Answer Dot Size E 0 answer data size i plus ps is ok result aa e answer after that we will return the result ok private word in order node root ok what do we call the function first of all terminating case so this is ours go to all What do we do after that on the left? We do processing on the root. After that, something is called. On the right, okay, so now we have to do the processing on Y. We have to take some variables int previous. Let's take this. Inj. dat mean value. Let's take the maximum frequency. And temporary frequency of any movement is also taken as one because that element will be added to itself and will be inside the list because the maximum number of times it is coming, okay in this we do if root dot value equal to previous if root. The value of is equal to the previous one, as we saw in the example here, if it is on this element, then the value of the root is three, if the previous one is il, then what we will do is increase our temporary frequency in it, then our What is tom plus else? What does it mean that the root is not equal? ​​This is the case of five. not equal? ​​This is the case of five. not equal? ​​This is the case of five. What will we do in the case of five? We will reset the tom and we will start calculating our frequency again and also the previous one. If we set then the value of tom is made one, the previous equal to root dot value is okay, we just had to do this processing and at every moment we will see that our a which is our temporary frequency is not going out of the maximum frequency ba if temp is Greater than maximum frequency: frequency: frequency: If the temp is greater than our maximum frequency, then what to do in that case? First of all, we will clear the answer because we have got the element with higher frequency, so the earlier multiple elements with smaller frequency which we had got are not needed. The answer is cleared, the answer is dot value, the value of the root is added to the answer, and if the temporary frequency is greater than the maximum frequency, then we are ok, the answer is cleared, the value of the root is added to the answer, what can happen after that? Case can be a case, our maximum frequency is equal to tom. If our maximum frequency is equal to tom, what will we do in that case we just have to add d in the answer which is the value of the root because a new element was found which The frequency was becoming equal to the previous element. Okay, so let's run it and see. Submit, but the color is done. Answer is okay. The output is our one and it is getting zero and neither. Let's see once the temporary frequency increases. One is happening, okay, everything is going well, if the temporary frequency becomes more than the maximum frequency, then we will update the maximum frequency, tell Tom that you are making a mistake, okay, let's run all the meetings, okay, successfully submitted, okay, hope. It must be clear to all of you, if not then please comment. Thank you.
Find Mode in Binary Search Tree
find-mode-in-binary-search-tree
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. * The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,null,2,2\] **Output:** \[2\] **Example 2:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` **Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
98
1,732
hi everyone in today challenge we are going to solve this problem the problem name is find the highest altitude and the problem number is 1732 only case so as usual first of all we are going to clearly understand this problem statement after that we are going to move to the logic part we are going to see how we can solve this problem and after that we are going to move to the implementation part we are going to implement our loads you can see plus Java and Python programming language fine guys now let's see what this problem say right so problem says there is a biker going on a rotary fine the road trip consisting of n plus Point N plus 1 points at a different altitude and the biker start his trip 1.0 with and the biker start his trip 1.0 with and the biker start his trip 1.0 with altitude equal to zero so guys they are always going to be n plus one point in a tree if that makes sense right and zero point is given that zero point you're going to have nothing but zero altitude right this is a point and this is altitude right but zero point is always going to have a zero lt2 and it is also show that 0 is going to be always fine initial point for the bike right now you're given an integer error gain of length n where gain of I is a net gain in altitude between points I and I plus one so guys now what we are given an array of uh array of size n and the name of that is nothing but we can say again right so let's move this one and let's write again right now what this gain array do what is gain error tell us right so gain of 0 is tell us that the altitude changes the change in altitude is nothing but we can say gain of zero lets again of 0 is 4 so we can see the altitude change from 0 to 1 in nothing but four right if gain of uh zero is minus two so altitude change between 0 to 1 is next one minus two that means altitude decrease by minus two or because L2 degrees by 2 if it is 4 so attitude increase by 4 right now simple logic isn't it and don't worry we are going to understand with example one but try to understand the problem here not a logic part but problem right now what we have to return the highest altitude of a point or let's say we have to written the highest altitude of a point right now let's understand this problem everything with example one line so remove everything so guys they are given uh nothing but you can see gain arrays one two three four five so there are five elements in this gain arrays that means there are going to be six point right five plus one so let's make a point zero one two three four five right so these are another six point right and we can say the same point this is going to be attitude right now and one more thing which is given nothing but gain right so let me write a game and again I'm going to write in different color gain is given nothing but we can say minus five one five zero minus seven right so this is right so we can say guys now uh let's uh remove this thing and let's write in this Index right minus 5 1 5 0 minus n now guys we have to find the altitude so we all know that at point zero LTD always going to be zero they have mentioned in the first line right in the second line all right so now the bike has started on the point zero with lq equal to zero right now what we are doing we have to find the altitude at this point then we have to return the maximum right highest altitude right so how we can find the uh later at point one we know that point at attitude 0.1 the we know that point at attitude 0.1 the we know that point at attitude 0.1 the changes is nothing minus five right means altitude decrease by minus five so earlier it was Zero if we decrease uh we can say altitude by minus five then what we are going to get my five only right so let me use the hair as a different color right now on this point second the altitude increase by one so we are going to increase by one so minus five plus one is four minus four plus five is nothing but equal to one right after that at four the altitude neither increase no decrease it remains same right so we are not going to do any changes in this right after that at 0.5 right after that at 0.5 right after that at 0.5 altitude decrease by 7 so 1 minus 7 is what equal to minus six right so we got this altitude array and you can see the maximum altitude we are getting 1 isn't it I hope it makes sense right so we are going to get an answer one simple thing now example two also you can see same thing is going to happen minus four or should we do it as well either okay let's do it this one as well right so we are having let's do it quickly right so we are having um uh just consider from this example one we are having minus four minus three minus two minus one four three two right so our Point uh L U initially is going to minus equal to zero is that make sense right after that altitude decrease by minus four so we are going to say decrease one minus 4 is equal to minus four minus three so minus seven then also decrease by minus one then minus ten then increase by 4 so minus six then increase by three so minus 3 then increase at 2 so minus one so this is Altitude our array so what is the maximum value here you are getting zero only right so you can say we are going to return our answer zero so answer you can see also in output we have G2 so this was the basically problem understanding part I hope you understood the problem with the logic but I don't and we can say Zoom here from view that you have in this photology but you must understood the logic part right so all right so now let's move to the logic part but before that getting summarize this thing we are given first of all gain array we also uh given that we are going to start from zero point we have the altitude also is nothing but equal to zero right okay now let's move to the logic part and let's see how we can solve this problem right and logic is not going to take more than two or three minutes or it may take but the logic is really very easy even it's not going to use any concept as well so let me know hello and what logic is going to do let's take only first example we have this gain at right minus five so let's do nothing but like this okay minus 5 1 5 that's at a comma five comma 0 minus seven and we are given a point as well right so quite design initially zero so don't write there we all know that now we are given altitude right we have to find an altitude but our main motive is to find altitude right so initially l22 is going to be 0 right the next altitude will be what 0 Plus or we can say what is the value over here at 0 index 0 minus 5 is 1 minus five then next altitude is nothing we're going to be equal to Minus 5 plus 1 which is nothing but equal to 4 minus 4 plus 5 is nothing but equal to we can say one plus zero is one minus seven is nothing but minus six so we can say this is our altitude now we have to just find the maximum value and we can return one right simple logic guys nothing else we just need to uh make our altitude with the gain right so because the previous attitude plus the gain on that index is nothing but equal to the current altitude right now so let's move to the implementation part and let's see how we can implement this particle right so let's first of all go to browser and here guys I am first of all with the python right so let's Implement with python so what I'm going to do with uh first of all let me find the length Here length of K which tell us that how many points we are going to have and how many gains we are given right so points is going to be always n plus one so let's make our altitude array let's say 0 and we can say 4 underscore let me write here this range of n plus 1 9 so we have make an altitude array of n plus one size and by default I have you the value nothing but equal to zero because it also going to help me at the initial index and now guys we are going to say uh four I in range of 10. right now I'm going to calculate the altitude of next element we can say next point which is going to be equal to the altitude of let me write altitude what is going to over here attribute of I plus gain of I write now let's understand this if you are not getting this particular bar see guys this one nothing but if we can say uh at point zero we were having this particular thing right at point zero we arriving at 0.0 right but at point one arriving at 0.0 right but at point one arriving at 0.0 right but at point one what is going to be altitude of 0 plus gain of 0 isn't it so I'm going into the same I'm doing the same thing altitude of one I'm at 0 and that's why one is equal to altitude of 0 plus again of 0 right after that we are going to say our results should be equal to the maximum of highest comma altitude of I plus 1 9 I hope this makes sense now after that we are going to need a number nothing but our highest so this is nothing but you're gonna do the uh we can say it's here what we are doing we are first calculating the altitude then we are finding the maximum right but here what we are doing after calculating the DD of that particular point we'll keep checking that whether it is the highest one if it is the highest one stored in our highest variable so that we don't need to check again that what is the highest after calculating that video right after that we can simply run this particular code right so let's see whether test case are getting passed or not and I hope so it should get passed right so you can see guys both the desk is passed so let's try to submit this code as well let's see whether it is submitted or not here we go guys right so it's successfully got submitted now let's move to the next programming language which is nothing but we would say C plus so quickly what I'm going to do I'm going to say vector before that let's calculate the size and then is equal to gain code size and then make a vector and here the name I'm gonna give altitude size is going to put n plus one by default value 0 because it's going to help us to make uh we can say zero value at the point zero as well like after that we can say four now four before that we have to make the highest y plus K Note 5 right once the second we are going to say highest also should be equal to maximum of highest and altitude of I Plus 1. after that we can say simply written our highest right it makes sense right easy problem right and what we are doing actually is we are just using a loop only nothing else right and here I'll say we've got an error because we haven't used the semicolon fine now let's run this code and see whether we are getting any more error or not and I don't think so we should get right you can see both the risk is postulated to submit this code as well and let's see and it also got submitted guys right so now let's move to the last programming language which is nothing but Java and here first of all calculate the size length then you are going to calculate the you are going to create an array of altitude with the size n plus 1 so we can say altitude of n plus 1 node here Nu in N plus 1 and here we are going to see uh altitude of 0 is going to be equal to zero right we know that at point zero LTD is always equal to zero right and here into Phi is equal to zero I less than n i plus here we can say altitude of I plus 1 is going to be mathematical to ltq I plus k no PI right and here also we are going to say hi is let me at highest is going to be nothing but equal to math about Max we can say highest and here we can use our altitude of I plus 1 like altitude of I plus one after that we can simply return our highest right now let's run this code and see whether it's working final node and see whether it's working fine or not you can see guys both the desk is passed so let's try to submit this code as well right so let's see and here we go guys that is successfully got submitted as well so guys we have successfully implemented our logic and C plus Javan and Python and also we have seen the logic part we have understood the problem statement with the examples if you have any kind of doubt in three sections you can write in the comment section I'm always there to help you and if you learn something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
228
Jai Hind This Video Will Solve Problem Chord Summary Ranges Surya Problems Is The Winner List Of Units In Tears In Your Eyes Are Like 12345 7th August Subscribe Aaj Date Jump Hai Amazon Hai To Yeh Tu Shoes Mauj Numbers In 2124 Is This Is 7219 Ki And It's Just Told Oo That Suthar Dhvani Just Lal Inter College Will Have Enough To Values ​​Standard And Half Inch Have Enough To Values ​​Standard And Half Inch Have Enough To Values ​​Standard And Half Inch And Not Mean That Are Not Present At A Suitable Will Appear Separately And Not Been Quite 09 In 2012 Shift Same You Don't Like It This Next Improve It's A that repeat same TDS return mt the effects one number that return just one number a sweet potatoes vector and list of these teachers union leaders of this again play list and inter district news channel subscribe to that in all the elements of the center will present there 210 Where Everything Breaks in Two Interviews President and Person's Nature and Subscribe 2012's Vote 57 Tomorrow Morning to Start from Fog A &amp; B Straight to Restaurant in Illegal Flats A &amp; B Straight to Restaurant in Illegal Flats A &amp; B Straight to Restaurant in Illegal Flats Quality is 10 Scorpio What is the Value Added One More Than Current Busy Schedule Thursday Subscribe Like this is the meaning of the word vyatit no a sweet will win more dhamtari suno vinod arth veerval start busy that in different also been started 021 inter result which alarm show with 02 oct 08 current value e will depend on porn with now Ise Exams Current and Equipped 2457 You Did You Too Main MG Road You Complete Next Vyati Sauveer Va Subscribe Pati Phir Not Subscribe To A Foot By 20 Foot By Its Quality Namaskar Om Namah Shivay Om Ki Sudhir Akhilesh Ma'am Om Namah Shivai Ki Is Note SMS On this occasion, messages from this that Zabiuddin shirt notice letter in statement from industry for oo and happy life sweater in trouble and national games next flight this repeat same day one more thing will subscribe The Channel Vinod 232 hai here is such a decade enrollment printer and Just your own language and to improve to cash aaj phir bhi reserve bank of interwoven is vansh value that is more than current plus one and second year result date the current is and letters were present at least for example of 12345 and who is vansh value one More Than Others Vikram Hair Next Satire Mode Switch Serious Global Growth List That Sued In Not Valid Condition And Huge Number Of More Than One But Still They Thursday Morning Subscribe To Accept Kohli Dessert In The Same Example And Gift Constipation Cases I Call It 10 A Return result is latest MP result by e-mail Initial I.S.A.P do that Swift High Court One Minus One Ladies Last Airbender List few days and firm end author interview with simple and share and improve by one second Om Namah Shivai Hu Is Not Equal To Phone Number Sa Plus One Switch Last Is Difficult-2 Lost In Thoughts Will Return From This Difficult-2 Lost In Thoughts Will Return From This Difficult-2 Lost In Thoughts Will Return From This Is Will Restrain From This Country Will Not Reduce Video Subscribe To Switch Important Brightness Condition First And You Can Separate Them Into Different Boxes Sudhir Va hai hua hai em getting into each one element and two elements of central excise that is not equal to hell that denim shirt completing the kar do the hills justice at the Hague that and need to update jaaye sudhir va subscribe this is not equal to Hai - 1m not equal to Hai - 1m not equal to Hai - 1m day update in a key and finally returned result according to match is oil did not match sukhbir and hai and join hai om namah shivai a plus one so due main is stitch plus one ki and now its message liquid answer facility and Solution inside submit for accepted ones can get notice on tuesday a clearer and in fact every month people will get in return because subscribe button more subscribe to ka sutta image open ki face ki that top using a few hours ago flash lights riders in java In Python hua hai do hua hai aap in Disha Solution Class Six Chapter and Positivity in Python hua hai do ajay ko do hua hai do Do Kar Do The Independence Solution Also Accepted
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
863
hey everyone welcome back today we are going to solve problem number 863 all notes distance K in binary tree first we will see the explanation of the problem statement then the logic on the code now let's dive into the solution so in this problem we have a binary tree with Target and variable K right so we need to find node values that are at K distance from the target Phi right so here the target node is 5 and we need to find nodes that are at a distance of K that is nodes that are at a distance 2 right so from Target 5 3 is at a distance 1 but if we go further one is at a distance of 2 right from 5 1 is at a distance of 2. so 1 will be the first node we don't have to check further because these are distance 3 right we can just break from here so then we need to check this side so here 6 is at a distance of 1 from Phi and from 6 there are no nodes so we can just return then we need to check the right side of 5 so from 5 we can reach 2 with a distance 1 then we can go further from 2 we can reach 7 with a distance 2 right from 5 we reach 7 with a distance 2 so 7 will be a valid node then from 2 we can reach 4 which is also a distance 2 from 5 so 4 is also valid node so after reaching the K distance notes we don't have to go further right so we are going to solve this problem using BFS approach so now we will see how we are going to do this so in this problem we are going to consider binary tree as an undirected graph so basically we can see that right binary tree is an undirected graph so we are going to create adjacency list graph where we are going to represent this binary tree in a dictionary right so here the neighbors of 3 or 5 and 1. similarly neighbors of 5 are 3 6 and 2 right that is what represented here and neighbors of 1 are 3 0 and 8 right and similarly neighbor of 6 is only 5 right 6 is connected with 5 only and so on you can check for further notes as well so initially we will be having a queue where we will append the target value and we will initialize the distance as 0 at the start then we will append the node 5 and the visited set so initially we will pop the top element in the queue so in this case we have Phi 1 0 we will pop 5 and 0. so here 5 represents the node and 0 represents distance right then we need to check whether we have reached the K distance or not here we haven't reached the K distance it is still 0 so we can proceed further so now we are going to visit the neighbors of Phi so we can use the graph that we created at the start to get neighbors that is 3 6 and 2. so first we pick the node 3. so now we need to check whether 3 is in my visited or not if it is not visited we can append the three to the queue and we increase the Distance by one that is we have reached 3 with a distance of 1 right from 5 we have reached 3 with a distance of 1 then we append the 3 to the visitor similarly we need to do it for the other two nodes that is six and two since six and two is also not in my visited set we will append 6 and 2 to the visit set and we will append 6 and 2 to the Q as well that is we will add 6 and 2 with a distance of 1 right which is we can reach 3 6 and 2 from 5 with the distance of 1 right so this one we got it by increasing the distance that is the current Distance by one right so now we have done with all the neighbors of I we need to pop the next element from the queue that is three and one so now the node will be 3 and distance will be 1. so now we need to check whether the distance is equal to K whether we have reached the K distance or not here we haven't reached the distance 2 so we need to proceed further so we pick the neighbors of 3 which is nothing but 5 and 1. since 5 is already is in my visited set we don't have to visit Phi so we visit one so we need to append one to the visited set so then we need to append one to the Q and we will increase the Distance by 1 which becomes 2. here the distance is 1 and we need to increase it by 1. so now we have done with all the neighbors of 3 we pick the next value from the Q which is nothing but 6 and 1. so node becomes 6 and distance is 1. now we need to check whether we have reached the K distance no we haven't reached yet so we proceed further to get the neighbors of 6. so the neighbors of 6 is nothing but 5 since 5 is already visited we don't have to proceed further we pick the next value from the queue that is 2 and 1 right so again we need to check whether we have reached the K distance we haven't reached yet so we pick the neighbors of 2 that is 5 7 and 4 since 5 is already visited we don't have to visit five we pick 7 and 4 right then we append 7 and 4 to the visited set then we need to append 7 to the queue and we will append a distance of 2 that is distance plus 1 right similarly we need to append 4 the distance is 2. now we have done with all the neighbors of 2 we need to pick the next value from the queue that is Node 1 and distance 2. so now we need to check whether we have reached the K distance or not yes we have reached to right so we need to append one to the result so we need to keep on doing in this process until we get all the nodes that have a distance of 2. so in this case 1 7 and 4 will be the answer for this particular input so whenever we reach a distance that is greater than K we break right we don't have to go further that's all the logic is now we will see the code so initially we will be having a graph dictionary so in order to create the adjacency list we will be writing a separate function to Traverse through the binary tree and we will append the parent and the node values at the same time right since we are treating the binary tree as a undirected graph right so then we need to create a queue where we will append the target node and the distance 0 at the start then we will append the target node to the visited set then we will be having an empty list result to get our node values right then we will run the loop until the queue is empty then we pop the top values from the queue so we will get the node and the distance then we need to check whether the distance is equal to K or not if we have reached the K distance we have to append the node value to the result list else we just proceed further then we need to check whether the distance is greater than K if it is greater than K we just need to break from the loop right then if the both the condition fails we need to get the neighbors of the current node then if the neighbor is not in my visited set we need to append the neighbor to the visited set and we need to append enable to the queue along with the distance increased by 1 right then finally we need to return the result list that's all the chorus now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos and keep supporting guys
All Nodes Distance K in Binary Tree
sum-of-distances-in-tree
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **Output:** \[7,4,1\] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. **Example 2:** **Input:** root = \[1\], target = 1, k = 3 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 500]`. * `0 <= Node.val <= 500` * All the values `Node.val` are **unique**. * `target` is the value of one of the nodes in the tree. * `0 <= k <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
1021,2175
700
hey guys welcome back to the coordinate our it's a day 15 from the June lick code challenge and to this problem is a search in a binary search tree so in this problem we will go through the problem description we'll understand the examples and also we will write the code and understand the time complexity of this problem before we proceed if you are new to the channel please subscribe to the channel we solves a lot of competitive problems which can be helpful in your upcoming interviews so let's get started with the problem in the problem it says given a root node of a binary search tree and a value so these are the two parameters we have given in the input you need to find a node in a be a street that the Nords value equals to the given value return the subtree rooted with that node if such node does not exist we need to return a null so now let's understand with the example here the binary search tree BST tree is given to us and the value we would like to search is a2 so we the to value the node itself is present so we have to return this subtree all right from 2 1 3 this is what the output we would like to return in the example above if we need to search value 5 since there is no value as a 5 we need to return null out of it all right so one thing we know in the binary search tree it has a properties like from the given node let's say if we are at a root node it has all the numbers on our left hand side will be a lesser than the what you have current node and the same way on the right side all the nodes having a value higher than what your current node has and this to rule will apply at each node so if you are at a root all the sub tree nodes from the left hand side should be lesser than the what you have at root and same before right all right and same applies at 2 also on a left hand side it will have a lesser value as compared to your root node and on right side it will have a higher value is compared to the your rule to not okay so if you see here we would like to search this nor all so we know that our given tree is a binary search tree okay so we can apply a binary search logic to this tree and we can iterate over from the root node so what logic we will apply here is let's say when you are at a root alright so we will check with the current node with a given value okay let's say if that value is match with the current node let's say we are looking for two and you are at a four okay we start with a root now let's say if it is match then we will return that nor itself because in that case we would like to return that node itself when we found it all right now let's say if we haven't found that node it is not matching so in that case we will see whether that current node value is higher or lesser with respect to the current node then only we can search whether we need to traverse to the right the left subtree or a right subtree so now let's say here the root node having a higher value that means whatever the odd we are searching for that lies on a left subtree we do not need to go to the right subtree because right subtree having always a higher value with respect as compared to what we have root know so we will move to the left subtree only now let's say we move to the left subtree now we are at a here so again it checks for the whether when you having the same or no now in this case it's having the same value so in that case we will return this nourriture that gives the your this subtree in the result all right let's say if that is also not the case let's say we are searching for five here so in that case we will go through for five we will start from the root all right and we will search with a root node so Phi is a greater than the what you have in the root so we will try to sort on the right hand side all right and we will keep going until we found it let's say if we haven't found anything then we will return a null from that tree itself now let's write a core for this so here the one base condition let's first write it down so let's say if our route is equal to null that means we reach to the leaf nod or nor do not have any other notes out of it so we'll return null from there all right next if we will first check whether what we are looking for we found or not root dot well is equal to given value then return wrote nor else if let's say else if we will check whether we need to go to the left side or right side so if your root is higher than nor given current when you then do a recursive call on a left subtree so go to the root dot left and pass a value and here we would like to return the whatever the result that recurs in call returns we would like to return the same value now else in the else case we would like to return we would like to explore right subtree okay row dot right and well so this way we will get the correct result which we are looking for all right now let's compile it okay what compiled so we have a we are looking for - and this is what the looking for - and this is what the looking for - and this is what the subtree of - and that is what I expected subtree of - and that is what I expected subtree of - and that is what I expected one now let's submit it all right it got submitted so here a time complexity of this problem is as we are applying binary search so it is going to be log of n and the space we are utilizing constant space so it is going to be constant space complexity so that's it in this video hope you like it if you have a different solution please write it down in the comment if you are looking for a solution for a different problem I would suggest to write it down in the comment box see you soon till the time bye
Search in a Binary Search Tree
search-in-a-binary-search-tree
You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 2 **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `1 <= Node.val <= 107` * `root` is a binary search tree. * `1 <= val <= 107`
null
null
Easy
null
344
all right back at leak code again today this is the reverse string problem it's also known as leak code 344 and i found this underneath the top interview questions easy section so this algorithm wants you to write a function that reverses a string but the catch on this one is that you have to do it in place so how i'd normally approach this with an input like hello would be to just simply initialize an empty string answer here then i would loop through the input string with the for loop and then i would build up the answer string here slowly with the for loop iterating through uh each section so how that would work is the first time through right i would have h every i would set this to h here the answer to h because that would be i would equal h so the second time around we'd have h set to string and the second time around we'd have i equal to e right and then because we're doing i plus string so we're building it up in reverse like this and then the next time around i would be equal to l and then i would be equal to l again and then i would be equal to o again and then we simply just return it right here but we can't do that because we're supposed to do this in place so i'll show you how to do that here and let's initialize these so i'm initializing a start of the string and an end of the string in this case start can just be zero because that's the that will be the first place in the string and then using a while loop we're going to do a swap of all the letters so swap is done like this usually set a temp like this let temp so that's the swap there and then from there you have to increment going up from the beginning of the string and going down from the end of the string just like that so to walk through this here start here is zero and end here is the length of the string so the end of this so start would be basically h end is supposed to be o here or also four and you can see here what we want to do is we want to make temp h and we want to make the first letter equal to the last letter well right now what is sn end right here so string end is 4 1 2 3 4 right here which would be o and because we already have this temp here set to start which is h we would just make the last letter equal to h and then increment through so the next time around start would be 1 and n would be end would be three right and you could imagine how this would slowly go through and swap all of these well start as less than end and just hit submit and we're done that's it that's how to do this in javascript hope you enjoyed
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
1,624
what's up guys so let's solve this one six two four largest substring between two evil characters so given a string s return length of longest substring between two evil characters excluding the two character characters if there is a no substring from a return minus one so a you get zero and one right so it's one minus zero minus one because zero okay and for this one you get zero one two three so three minus zero minus one is two for this one you get you don't get anything right because there's no characters okay so the first boundary case what we can do is that if you trap that where every character is unique if every character is unique they're immediately written minus one because it's like this case okay and now you can since there's only 26 characters right so you can initialize the dictionary i initialize at least with 26 and each like i use minus one so this is the index list they initialize the answer to zero and then you enumerate s and then for each so this is the change alphabets change it to the number right so if every if any time you already see something in this is greater than minus one that means that there is a some the same alphabets already happened in the previous and the previous way so you can update your uh update your lens okay otherwise that uh that means this is the first time you see these characters so you add it okay then it returns okay so let's see you guys next videos
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
30
okay thirdly at task of lit code substring and concatenation of all words okay pretty interesting task i would say so we have an initial string of length up to 10 to the power of four and we have a word array with which is extremely important with equal length of words and we pretty much have to find all the substrings here that if we're taken are somewhat permutation and concatenation of all of the strings in here so this uh bar food whatever and here we have one bar so from this concatenations and permutations we can obtain fubar or barfu and we have both of them we have both a bar fill here and we have a full bar here and that's why we have zero nine that's like the starting indices of this strings okay so a solution comes to mind which is dangerously close to having exceeding the time limit but nevertheless might work unless we try is to follow this logic okay so first of all the constraints very important constraints so word length 30 and the number of those can be up to five thousand okay so let's say that we kind of check for each possible substring from the initial array so that gives us 10 to the power of four potential starting points so for each location we just stay there substring starting from that location can be obtained by permutation concatenation of the words or not okay the way we do it is this so all the words have equal length so we can kind of like store them somewhere and store the counts because we can see that they can be repeating so let's store them somewhere how many from for each word how many we have and when we start a lookup first we take the slice that we are going to look which is gonna have the length equal to the sum of the lengths of the words and then try to go word by the length equal to each of the length of these words so kind of like start from the beginning and then take every word like in this case the first word would be word the second one would be good the third one good for doing good by according to the length from the array of the words and kind of see whether we got a perfect match or not so the perfect match would be this the same words appear exactly the same times as the words in the word array there is no word that doesn't exist here and there are no words that have more duplicates here than we'll have here the quickest way to be to use the unordered maps for this which is the hash table for known c plus guys so kind of like the estimate before we type the code would be 10 to the power of 4 multiplied by each length is going to be 50 000 multiplied by three so each like substring collecting and checking and also multiply that with the complexity of looking again up in the hash table if we are lucky enough it would be one so we have 10 to the power of 4 multiplied by 15 times 10 to the power of 3 which is dangerously close so if the standard hasher for string implemented in c plus is actually good enough to give a nice distribution of the strings we might get this done okay so what is this going to look so as always we write the easy part first result less than okay i think i would need some parameters here but maybe not now okay so s dot size minus no i think we do yeah so initially we might want to get so until at which point we're going to go so we're going to worst that size multiplied by words zero that size so this is as far as we can go as a starting indices concern so if check i result that pushback i'll fill this check parameters later okay so what is this check gonna look like so let's write this big check function so the first thing that it is going to obviously receive is the target string the second one is going to be the index from which we are going to start checking it the third one is going to be the already hash map of the words array which i would call words so const std unordered map this string to int reference words okay fourth it's gonna receive i should have one parameter at least i can maybe give the length of the words length of which words okay this looks fair enough okay so initially we need to build the unordered before we pass it to the function so it's going to look something like this so let's call it unordered map stringent m okay so for each word i'll put a reference here we're going to save as much time complexity as we can by even saving on a trivial operations so it should be m w plus and i hope they are initialized to zero i hope okay so for the check we are giving the source string we are giving the index we are giving m and we are giving the length which is size okay i think i might also i'm not sure how much does it takes to get the size of this length i'll also go word count just in case don't want to be greedy on the parameters so this and the words that size okay so first things first what we want to do is to get a copy of this hash map words so it would be let's say m let's go it again equals the words okay so now we are gonna try to take our sub strings each with the length word count times so it's gonna be this four i would start from the index i is less than word count plus i okay so our string let's call it uh temporary is the substring which is going to start at the position i multiplied by length and which is going to have is it linked yeah and which is going to have length okay so now this is our string so it's not checking so if initially let's find it so f equals our temporary map find temp okay so if we manage to not find this one equals two and the answer is definitely false this word doesn't exist so if this word does exist we need to make sure that it's it is still valid so which means that if f equals i can actually put this in one so or if a second element equals zero which means there is no more left of this then return false otherwise we can decrease the second element the count by one so i want to save as many lookups as possible here minus f second okay and if none of the checks fail return true okay so this will make sure that if something that doesn't exist the false it'll get over the count okay looks okay for now let's see how this goes oops okay so initial string index map size oh there's one extra here okay oops oh well yeah the output said that all of these checks would be valid oh yeah there's an index mismatching so if i'm going to do it like this i should go from zero to word count and have here starting from index plus i multiply by length with length let's see the first fixing okay seems fine now the moment of truth okay we have a wrong answer that gives more than was no it is actually less so 8 i think this might be like close to the end oh it's like it's the last one i should have one more checking here run code okay well let's see i'm surprised this even passed memory usage less than okay fair enough okay we're done
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**. A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated. * For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abefcd "`, `"cdabef "`, `"cdefab "`, `"efabcd "`, and `"efcdab "` are all concatenated strings. `"acdbef "` is not a concatenated substring because it is not the concatenation of any permutation of `words`. Return _the starting indices of all the concatenated substrings in_ `s`. You can return the answer in **any order**. **Example 1:** **Input:** s = "barfoothefoobarman ", words = \[ "foo ", "bar "\] **Output:** \[0,9\] **Explanation:** Since words.length == 2 and words\[i\].length == 3, the concatenated substring has to be of length 6. The substring starting at 0 is "barfoo ". It is the concatenation of \[ "bar ", "foo "\] which is a permutation of words. The substring starting at 9 is "foobar ". It is the concatenation of \[ "foo ", "bar "\] which is a permutation of words. The output order does not matter. Returning \[9,0\] is fine too. **Example 2:** **Input:** s = "wordgoodgoodgoodbestword ", words = \[ "word ", "good ", "best ", "word "\] **Output:** \[\] **Explanation:** Since words.length == 4 and words\[i\].length == 4, the concatenated substring has to be of length 16. There is no substring of length 16 is s that is equal to the concatenation of any permutation of words. We return an empty array. **Example 3:** **Input:** s = "barfoofoobarthefoobarman ", words = \[ "bar ", "foo ", "the "\] **Output:** \[6,9,12\] **Explanation:** Since words.length == 3 and words\[i\].length == 3, the concatenated substring has to be of length 9. The substring starting at 6 is "foobarthe ". It is the concatenation of \[ "foo ", "bar ", "the "\] which is a permutation of words. The substring starting at 9 is "barthefoo ". It is the concatenation of \[ "bar ", "the ", "foo "\] which is a permutation of words. The substring starting at 12 is "thefoobar ". It is the concatenation of \[ "the ", "foo ", "bar "\] which is a permutation of words. **Constraints:** * `1 <= s.length <= 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 30` * `s` and `words[i]` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Hard
76
18
hello everybody so in this video we will be looking at the lead code problem 18 that is foursome so the problem statement states that we are given an array numbers of an integer so we have to return an array of all unique quadruples so we have a num of a number of b number c and m of d such that their sum is equal to a target and all these index a b c d will be between 0 to n so what we are given so if we see the example so for example if this is our array so our possible answers will be one zero minus one and if the target is zero then our another possible answer will be uh minus two zero and two and another possible answer will be minus 2 1 and minus 1 and we can return this answer in any order so how we can do this question is suppose this is our array we are given so we can do something like this is my index one two three and five so what we can do this is my i uh we will first sort the array so we will sort the array so when i sort this area i'll get something like minus two minus 1 0 1 and 2 so this is my i this is my j and this is my k now what i'll do this will give me a sum of minus 3 so for the this rest of the array i'll run a binary search and search for the value that is target minus this sum so that is 0 so i'll search in the rest of the array that can i have a value 3 so it will be 0 minus and minus of 3 which will be 3 so can i get a value 3 in this remaining array so i can't so i'll move my k so again i have something like this my i is here my j is here and now my k is here so now the sum is again minus uh the sum is again minus 3 so we will again check that can it can i find a 3 here so i can't so my k will move here then my k will move uh here so when my k will move here i will have something like minus 2 minus 1 and the sum will be plus 1 and the sum will be something like minus 2 and then i have to find in the remaining array that can i find a 2 so i can find a 2 so this is one of my possible answers so i'll put numbers of i numbers of j numbers of k and numbers of this mid value into my vector 2d vector this way we will do this so the time complexity if we do it this way will be something like there is a loop for i there is a loop for j and there is another loop for k so it will be n cube directly and then we are doing a binary search on the rest of the array so that will be a log n so the time complexity will be n cube log n and the space complexity will be o of 1 that is the constant space so now can we do it in a better way so for the example i was having uh 1 0 minus 1 0 and minus so i was having 1 0 minus 1 0 2 and minus 2 so can we do it better yes we can reduce that log n in the end how we will do that so first of all we again sort this so for sorting it will be taking a n log n if we do it using the still sort and if we use another sort so there might be some changes for example if i use a counting sort i can do this in a o of n space or n time but of n space as well so if i sort this it will take n log n so what i will get after sorting it is minus 2 minus 1 0 1 and 2. so this is my array at the moment this is what i have right so now we know that our array is sorted so we can think of something so i will have my i here i will have my j here so my left will i will have two pointers left and right so i will apply two pointers approach on the remaining array so my left will start from here always from j plus 1 and my right will always be n minus 1 where n is the size of the array and the sum of these 2 is something like minus 3 right and my target is 0 so now what i have to find is 0 minus 3 which is equal to 3 now i have to find like can i get so now i have to do something like that can i get a sum of three in this array so i'll start from my left and i'll do my nums of left plus numbers off right so i'll add this and this so is it 3 no it is not 3 it is 2 now 2 is less than 3 so if it is less i will move left one step ahead right i will move left one step ahead so this comes into being because we have sorted this so we can do this because the values on the left side will be smaller and the value on the right side will be greater so if the sum is less so i can move from the smaller side to the bigger side and if the sum is greater i can move from the greater side to the smaller side so now again i see okay it is again two so my left again goes here now i am pointing my left is here my right is there now i see okay my sum is equal to the target i was looking that is three uh that is three so i can insert all these values that is i j k and i j left and right into my answer another vector and then i can insert it into a 2d vector or i can just use four variables for this so this is one way i can do this so for the first time it will be done so now if i do it for the another step it will it was minus 1 0 1 and 2 now my j is here my i is still here and my left is here and my right is here okay so this is what i have at the moment so now my target is again 0 my sum is minus 2 plus 0 that is minus 2 and my target is 0 and so what i have to find is 0 minus of 2 that is 2 so i'll start from left is left number of left plus numbers of write less than or greater than no it is equal so i found my answer and then i'll go ahead and check is it no then i'll go ahead is it no the moment my left crosses my right i'll stop right the moment my left crosses the right i'll stop this is what i will do or it becomes equal now uh there is something we can observe like we are doing some extra work here what is that extra work so in the previous example when my j was somewhere around so if i discuss so in the previous example when my i was here my j was there and my left was here and my right was here right we checked that for two and zero we are not getting a sum of three so we have to move my left ahead but when we moved our left hand we again have a zero there so isn't it like an extra work that we are again checking for the same number and instead of checking here we should directly go to the number which is not equal to this so this is the extra work we have been doing so we have we can omit this right we can omit this i will show you in the code how we will omit this but what we will do is we will increment our left till the value is same and it is less than right okay so we will do this now the time complexity for this will be o of o and cube because this will be i will be running n times this j will be running n times and this left is less than right will be running n times in the worst case okay so the time complexity will be o of n and the space complexity will be a constant space that is o of one right so this is what we will do so this is a pretty easy question if you know how to do this so int n equals to i have num dot num star size now my target is given to me and i'll just sort the array so sort i'll sort it i'll use do the stl using the still sort function so nums dot and so i've sorted the array here now i'll run two loops for i will be starting from zero and it will go till n now the another loop j will be starting always be starting from i plus 1 and it will always be less than n and i'll do a j plus now i will have my sum which will be equal to target plus sorry which will be equal to target minus that was my mistake so nums of i plus num of j this will be my target now my end will always be left will always be j plus 1 and my in right will always be n minus 1 now till my left is lesser than the right i'll check if nums off so instead of doing this if nums off all the time i'll just store and sum 2 equals to nums of left plus numbers off right why i'm calculating is it here is for the drive principle in the programming that is do not repeat itself so if i would have not used this i would have write it multiple times like if it is greater if this value sum is less so i have used this multiple times now i all i have to do is use this sum too so if my sum 2 is less than sum right i'll do a left plus now else if my sum 2 is greater than sum i'll do a right minus and else if this is not the case also i have to take a vector of vector in answer it will store my answer so answer now in there what i can do i can take a vector of in temp of size 4 with 0 initialized with 0 so now my temp of 0 will be the value of numbers of i so it will be numbers of i and same for temp of 1 will be the value add numbers of j now the next one will be the value add number of left and the last one will be the value at nums of right now is off right and now comes the part where we will be skipping the values which comes in repetition so what we will do is while my left is less than right and numbers of left equals to temp of 2 and in here i have to do something else that is answer that also dot push back 10 so we have stored the answer now if this is the case i'll do a left plus now i have also have to check for the right so while my left is less than right and numbers of right is equal to equals to temp of three if this is the case i'll do a right minus this is what i'm doing now when i come back i'll check again for my for so while my j plus 1 is less than n and my numbers of j plus 1 is equal to nums of j if this is the case i'll do j plus so why we are doing a j plus 1 here because uh we are having a j plus here right now if you will dry run this you will get to know why we are doing a j plus 1 here and we will do the same for an i right so here we will do while my i plus 1 is less than n and then numbers of i plus 1 equals to numbers of i'll do i plus okay so we've done this now in the end we have to what do you turn the answer now in the end now if i run this okay we are having a error like temp2 is not defined okay so this will be inside this else block only this will be inside this else block because when we find the value are same now when we find the answer then we will skip so now if we submit it should be working fine okay we get a runtime error signed integer overflow so the problem was there was an integer overflow so i converted all this to a long end the where i am calculating the sum and then i submit it so it is submitted so i will submit it again so you can see it is working fine so thank you for watching the video and make sure to hit that subscribe and like button if you enjoyed the video and see you all in the next video
4Sum
4sum
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that: * `0 <= a, b, c, d < n` * `a`, `b`, `c`, and `d` are **distinct**. * `nums[a] + nums[b] + nums[c] + nums[d] == target` You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,0,-1,0,-2,2\], target = 0 **Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\] **Example 2:** **Input:** nums = \[2,2,2,2,2\], target = 8 **Output:** \[\[2,2,2,2\]\] **Constraints:** * `1 <= nums.length <= 200` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109`
null
Array,Two Pointers,Sorting
Medium
1,15,454,2122
973
Hello Hi Guys Welcome to Volumes and I will go through 3030 problem from the middle challenge is that Bihar will stop point on the play and win to find the cost point during the distance between two points on plane UP and distance it is the answer is NO The answer is the example of distance point Must subscribe this point Like and subscribe video This will influence in the distance of length equal to the length of point All day will read over input points and beauty and destroy points to reduce The distance from each point will produce no subscribe and subscribe will take a distance from side massage size appointment all in this question will start getting over points here and calculate the up and distance vacancy pathri ko mantri the distances eight software update Inter District All Attack Hero Movie Next Element The Distance From This One Is Creature 600 B Id Gold Medal Last Element The Distance Between To You Will Not Doing The So Without 10 Top Distance Giving Equal To Me Two Point To Project Points Show The Match Distance between lap 220 it is the second element in addition there will use this is the conditioner check not behave like a fist specialized result are of science for ets2 robbers once more and calculate distance course element distances is the distance 2008 this point result next point When Skin Distance Tomorrow Morning Add This Time Distances 20 Wicket Off Distance Subhedari Arzoo From The Mid Point This Is Final Result Of Written Test And Interview Shopping Time Complexity Of All Link Description On That Thank You For Watching My Video Like Video Please Like Share And Subscribe My Channel For More Videos In Short Let Me Know And Comment Section What You Think About Video All Should Be Given To Make A Video On One Of Your Problem Statement To Comment
K Closest Points to Origin
stamping-the-sequence
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). **Example 1:** **Input:** points = \[\[1,3\],\[-2,2\]\], k = 1 **Output:** \[\[-2,2\]\] **Explanation:** The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\]. **Example 2:** **Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2 **Output:** \[\[3,3\],\[-2,4\]\] **Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted. **Constraints:** * `1 <= k <= points.length <= 104` * `-104 < xi, yi < 104`
null
String,Stack,Greedy,Queue
Hard
null
103
hey guys welcome back to another video and in today's video we're going to be solving the lead code question binary tree zigzag level order traversal all right so in this question we're going to be given a binary tree and we need to return the zigzag level order traversal of its node's values so what this means is we go left to right then right to left and left to right so this has an is going to be 3 20 9 and then 15 7. so how are we actually going to solve this so we're going to implement a stack so our stack is going to start off with having the value of the head so in this case it's going to have a value of 3. then we're going to pop out all of the elements inside of our stack and we're going to get its left and right children for each of the elements we pop out so in this case we're going to get 9 and 20. but we can't just add 9 and 20 to our answers so first we're going to add 9 and 20 to our stack and instead of adding 9 and 20 to our answers we're going to add 20 and 9 because over here we went from left to right so on the next level we need to go from right to left but on the level after that so after we uh did 9 and 20 we're going to remove them from our stack so first we're going to remove 9 and it doesn't have any children nodes so we're going to leave it as it is then we're going to remove the 20 and it has a left child and a right child and in this case we're going to add 15 and then 7 to our answers list because we need to go from left to right since we went from right to left on this uh second level okay i think it's a lot easier to understand once we write the code all right so to start off we're first going to check if our root actually exists so if the root equals to none then in that case we're just going to return an empty list and then we're going to initialize a few variables so we're going to have our results which is an empty list and we're going to have our stack which is going to start off by having the value of the root uh then we're going to have a direction and i'm going to just equate it to 1. so what i'm going to do is if whatever the direction value is mod 2 is equal to 0 then in that case i'm going to go from right to left else i'm going to go from left to right so i'll show you what that exactly means inside of our while loop so while stack so that means we're going to keep going as long as there's a value for the stack and we're going to initialize our temporary variable over here so that's just going to be an empty list for now okay so then now we're going to iterate through everything inside of our stack so for x in range and then the length of stack okay so now that we do that we're gonna have our node which is gonna just be whatever we pop out of our stack then we're going to add that value to our temporary variable so temp dot append and then we're going to add the values node.val node.val node.val and now we're going to check if it has any children nodes so if node.left is not equal to node.left is not equal to node.left is not equal to none then in that case we're gonna append so stack dot append and then we're gonna add the net left node to the stack so no dot left and similarly now we're gonna do the same for the right node so if node dot right is not equal to none then in that case we're gonna stack dot append no dot right so we're gonna add the right note to our stack okay so after we do that we're gonna go outside of our for loop one second okay so after we do that we're gonna go outside of our for loop and now we need to add whatever we have inside of our temporary variable and we need to add that to our results so like i said before if direction mod 2 is equal to 0 then in that case we're going to add our we're going to add the nodes from right to left so result dot append so we're going to add everything instead of our temporary variable from right to left so negative 1. similarly if a direction mod 2 is not equal to 0 then we're going to add everything from left to right so it's going to be the same thing it's just going to be result dot append but we're adding from left to right so which is going to be 1 instead of negative 1. and finally each time we iterate through this loop we need to increase the value of our direction so direction plus equals one and then after we do that uh we go outside of our while loop and we're just going to return our result so now let's submit this and as you can see our submission did get accepted and finally do let me know if you have a better solution to this or if you have any questions regarding this and finally thanks a lot for watching and don't forget to like and subscribe if this video helped you thank you
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
21
another day another problem so let's Solve IT hello guys I hope you are all doing well so before I start explaining how we're gonna solve the merge to sorted list problem support me with the Subscribe a like to the video so let's get started so the problem is that they give us a tool linked list and they ask us to merge them into one sorted list so let's say we have this two linked list to merge them in a source of blanket list we'll make a dummy node that will serve as a placeholder for the head of the merged list allowing us to add nodes to the merged list by updating the current node's next pointer and by the end we're gonna discard this dummy node and we'll return the merge it list then we're gonna initialize a variable called pointer that's going to help us add nodes to the merged list and it's going to be pointing to the same list not object as a dummy then we're gonna start at operating over the two linked lists and compare each node of the first link at list to the node of the second list for example here we have the first node value of list one is one and the first node value of the S2 R1 with the help of the pointer variables that are pointing to the head of the merged list we add the first note to the merged list and we move to the next node and the last one and then we'll move the pointer variable to be the current node added to the merged list so we can add another value to the merged list when the next iteration happens so here we check for the second node value and the first node value on list two so we add the smaller one to the merged list and move to the next node in the list two so here we have the node of the first list one smaller than the node of the first second layer so add it to an immersed list and so on so the process is going to be repeated until there is no more nodes inside the tool list and finally we return the merged list excluding the Domino but there is a case when they give us a two linked list that are different from each other so to avoid that we can only set we can set another condition when Wireless is terminated we keep adding node from the list that have more nodes to the merged list and will be the same process so let's jump at coding solution first let's set a condition if one or both the lists are empty then we initialize the mean old and pointer then start at the racing troll boldness until one of them is empty and add the smaller of the two current nulls to the merged list and move to the pointer to the current value added then add the Romanian node from the non-mtls and finally return the merged list by excluding the Domino the solution has a linear time complexity where n is the total number of nodes in the two input list is due to the fact that while loop Traverse each node into two input lists and since the merged list is created by appended notes from the two input list the space complexity of the solution is also offhand thanks for watching see you in the next video
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. Return _the head of the merged linked list_. **Example 1:** **Input:** list1 = \[1,2,4\], list2 = \[1,3,4\] **Output:** \[1,1,2,3,4,4\] **Example 2:** **Input:** list1 = \[\], list2 = \[\] **Output:** \[\] **Example 3:** **Input:** list1 = \[\], list2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in both lists is in the range `[0, 50]`. * `-100 <= Node.val <= 100` * Both `list1` and `list2` are sorted in **non-decreasing** order.
null
Linked List,Recursion
Easy
23,88,148,244,1774,2071
976
hey guys welcome back to helper function in this video we will discuss another popular question largest perimeter triangle so the problem says that we are given with array of possible lengths we need to return the largest perimeter of a triangle with non-zero area now this nonzero area means that basically the triangle should be formed with those three lengths that we will pick so for example let's say we have an array with lengths as three two three four so these elements represent the lengths of the triangle and we need to pick any three of them such that the perimeter of the triangle is maximum and also the triangle should be formed that is its area should be non-zero its area should be non-zero its area should be non-zero so here we can pick 3 and 4 making the total perimeter as 10. so this is the maximum perimeter which we can get thus we will return 10 here now what do we mean by non-zero area we mean by non-zero area we mean by non-zero area non-zero area means that there must be a non-zero area means that there must be a non-zero area means that there must be a triangle formed first then we need to calculate the perimeter so let's say we have this triangle with sides a b and c so the minimum requirement for this triangle to have a non-zero area triangle to have a non-zero area triangle to have a non-zero area is that sum of any two sides should be greater than the third side thus a plus b should be greater than c and b plus c should be greater than a and also a plus c should be greater than b so if all of these three conditions are satisfied this means that we have a triangle which has a non-zero we have a triangle which has a non-zero we have a triangle which has a non-zero area thus now we can calculate the perimeter and update our answer so let's see how we are going to solve it let's say we have the array with elements as 3 2 3 4 so for brute force what we can do is we can have three for loops let's say i j and k j starting from i plus 1 and k starting from j plus 1 and now we have our three sides as a of i a of j and a of k now first we will check the condition of the triangle is satisfied or not that is if sum of 82 sides is greater than the third one or not and if this is satisfied then we will update our answer let's say answer is equals to max of answer or the perimeter formed by these three sides but this approach requires order of n cube time complexity as we are using three for loops now another thing that we can do is we can short this array let's say we shot this array and thus the new array we get is this now we will be comparing the largest three sides that is we will going from this side and every time we will be comparing three largest elements if this satisfies the condition of a triangle then this will be my maximum perimeter triangle and i will return the perimeter of this otherwise i will shift one side and then i will compare these three elements now why we are doing this let's try and understand by another example let's say we have a array with elements as 5 4 2 3 and 10. so at first we shot this array so the new elements we get is 2 3 4 5 and 10. now we will check for the last three elements that is the largest three elements so we pick these three elements and we will check that whether these three satisfy the condition for a non-zero satisfy the condition for a non-zero satisfy the condition for a non-zero triangle or not but we see that they don't satisfy as four plus five is lesser than 10 thus now it can be noticed that if these three sides doesn't satisfy then if i combine 10 with any other sides they will also not satisfy because these will definitely be lesser than four and five and if four and five does not satisfy then obviously these will also not satisfy so what we do is we just shift to one more side that is now we will check for 3 4 and 5 and here we can see that these 3 satisfies the condition that is 3 plus 4 is greater than 5 4 plus 5 is greater than 3 and 5 plus 3 is greater than 4 thus these three sides make a triangle and this triangle will have the largest perimeter that we can get among all these array elements why i am saying this because we are going from the right hand side that is we are going from the largest elements so if we go by this side the perimeter will decrease and because we have found a triangle here this will be my largest perimeter triangle and i will return 12 as the perimeter now the time complexity for this approach is order of n log n because we are using a short and shorting requires n log in time so this is how we can solve this problem in order of n log n complexity and the space complexity is order of 1 because we are not using any extra space now let's quickly look at the code we are given with the vector a representing the lengths of the sides of the triangle first we shot this vector and now we are starting from the last element and going till third element that is let's say we have this array 2 3 4 5 and 10 thus we are starting from this index and we are going to this index because we are taking this two numbers as our comparison so the loop will run from this to this if condition checks whether the triangle is formed or not let's say the sides are 4 5 and 10 then this checks that whether these two that is the sum of these two is greater than 10 or not now if this condition is satisfied then the sum of this will always be greater than 4 and some of this will always be greater than 5 thus we need to only check for this condition if it is satisfied then we have got our triangle and we will return its perimeter that is sum of all the three sides as our answer otherwise we will come out of this loop let's say for example with case this for this example the if condition will not be satisfied and we will come out of this loop and we'll return 0 as our answer so this was all about the problem i put the problem link in the description so you can go and solve it if any doubts or suggestion please write in the comment and if not subscribed to the channel yet then please do that thank you so much for watching
Largest Perimeter Triangle
minimum-area-rectangle
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three side lengths: 1, 2, and 2. **Example 2:** **Input:** nums = \[1,2,1,10\] **Output:** 0 **Explanation:** You cannot use the side lengths 1, 1, and 2 to form a triangle. You cannot use the side lengths 1, 1, and 10 to form a triangle. You cannot use the side lengths 1, 2, and 10 to form a triangle. As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. **Constraints:** * `3 <= nums.length <= 104` * `1 <= nums[i] <= 106`
null
Array,Hash Table,Math,Geometry,Sorting
Medium
null
316
to remove duplicate letters so given a string s we have to remove duplicate letter so that every letter appears only one and one is only once so you must make sure that your result is in the smallest lexicographical order among all the possible results suppose we have a string this is equal to BC ABC after doing ABC because B comes to Y so over here but we have only just written one b and here as well we have four C's and we have only one C over here and it should be in the increasing order and that is in that string right if uh if C comes after B then it should be just in the same way and the output should be in the same order as pressing this in the string right here is an AC DB it's a subsequence so what we are actually doing is we are just creating a subsequence from the input string and that's the subsequence shouldn't be like you know it shouldn't be interchanged all the letters shouldn't just be mixed and matched but rather it should be in the same order as it was present in the string so uh we can generate all possible unique subsequences so from this question we can see how do we separate um how do we even generate all the possible subsequences unique subsequences so it could be any subsequence right it can be okay let it be fine we find that ABC is the that is actually found in this string so ABC is a unique let us it's made up of the collection of ABCs and um this can be written as BAC or cab or ACB but and there are many unique I mean subsequences or you know um these also can be interchanged so uh we have to take care of thought and we have to but we have to turn the like psychographically smallest string and um that means it should be in the same order as the in present in the initial string so for this we can use standard data structure wherein we can store our increasing stack so uh if we'll just take this example we see ABC and when we push B uh then we are pushing C inside the start see now C is at the top of the stack now we are going to push a at the top of the stack and we see that a is lesser than C and B so a is a smaller number right and uh so C is a greater than uh um sorry number meaning this a character so a is a smaller character than b or c because it comes earlier than we can see in the uh in the alphabet alphabetical order so what we're going to do is um we have to pop out C all right and then uh we have B okay we want to question B and after that we will just push and C so uh then what happens is C and B are popped out and final result is ABC so now uh that is that will be our answer but uh only using stat is not I'm going to give you the correct answer and all the test cases so for that we can have another example where that Fields so we have this example b c a b so now we are pushing B into the stack right and then we'll push C also into a stack and finally when we have a chance to push a into a stack we want to check we see that a is smaller than b and c and uh we are going to pop out C but then okay we are going to pop out C okay suppose we pop out C and then we are going to push B here and then we will also pop out B so I mean we borrowed c and b and then finally we push A and B into the stack so our final result is a b but uh it shouldn't be a b right because there's also C present itself in the input string so the question is that we have to remove deep duplicate letters and then uh every letter should be present in our output but here every little is not present in our output that c is missing right she is definitely missing so we have to do something about it and um uh how do we uh so BAC should be the actual answer but we are getting a b so we have to make some modification we cannot just use the stack and then solve our problem we have to add a certain other data structures to completely uh make all the test cases true so we shouldn't exclude RC right C is very important because it's already there in the string and if we exclude C our answer we're on so it actually should be BAC um so um we have to track the frequency of each element now so how do you track the frequency of each element so we take this uh this example that is our previous example and we see that uh we are making a stack we see a b we are pushing b c a b double stack then we are going to calculate the frequency it's actually a vector or an array so frequency of a will be one right and B will be 2 and c will be 1. then whenever okay we are checking B right B uh then uh when we push in B we will just decrement it to one then after we position C we'll decrement that c to zero we will just decrement one uh one time and then when we encounter it when you push an a uh we have portion A and B so uh similarly we have to calculate the frequency of each element that's occurring inside the array then we have to track included letters using a visited array because uh we don't know whether an element or uh characters were already visited or not for example we'll just take bcav so we are having B over here then um the approaching in B then a frequency is as same as before right a is one B is 2 and C is one then um okay so we have to have a scenery there is a visited area we're tracking included letters in the array so after that we will just initialize all the unique characters uh to be false in the first place and then uh whenever we come across an element we will just change it to true that's what we want to do here and then frequency it keeps decrementing whenever um we push we encounter a pushed inside an element so we will keep discreasing our frequency as well so after pushing B we'll just decrement our frequency to one right two becomes one so after we take C uh then one will become zero after we pushing C inside our uh stack so similarly it works like that so there are three data substances here there is a stack this is a stack right and this one is a frequency array like vector this is a scene array to test whether the elements are already included before or not so I think whether the elements are already included previously in the stack and check the alphabet is included or not so um so that's what these are basically happening so B then after we it was initially false right then we have to um make it true right because it now it is included after we push it inside the stack then we see that b is already included in the stack then we change it to true and then we will decrement our frequency so these are the two operations we have to do when we find an element that is not present in a stack so we will change it to true and it will decrement the frequency so this is step one and this is step two that we have to do for each element that is not already present inside the array so as I said these are the three uh data structures we have used stack frequency array and visited array and the stack will be in increasing order time complexity for this will be order of n so coming to the code we see that um that's a string okay so we have a vector two vectors and a stack and uh we have a string over here string remove duplicate letter string so we are passing a string and our string will be a consisting lowercase English letters so that's why we want to keep a vector frequency Vector right frequency array 26 because the 26 letters in English alphabet and we have to store the frequency of each element initially the frequency of each element will be zero and then finally uh passing into the forward to for Loop we can just keep updating our frequency for each element that we encounter so for example if you encounter a right then at the index 0 we will just increment that frequency by one because we have encountered it uh once only once a so similarly for b c d until Z so that's what we're doing here and we'll go until let's dot size of that is to the end of the string starting from zero it goes to the end of the string that is starting from the starting of the string to the end of the string then we are going to create a stack there is a it is a um it's a start with grading consisting of characters so each stack um each uh personal stack will be translating of a character right what's the character it can be ABC or anything then uh we'll name it as St then the vector this is another array that will contains Boolean values right this is initially it all contain false we've seen we are having it again for 26 because when we have to check uh whether the element is included or not um and uh those all elements are 26 right there are 26 elements so we have to see for all the elements whether it is included or not that's why we have uh initializers uh scene array size as 26 and we have given it as false for each um for each 26 uh positions so for INT I is equal to 0 I is less than Natural Science off so we are going to uh loop a loop through our string right we're going to write it through a string and then we have the checking which is already seen right if seen then we are going to um that is if it is already included in the stack right if it has already been included in the stack previously or earlier we see we know that it is seen and thus it is true so this one becomes true and thus when we have seen it we have we just decrease its frequency and keep on uh we just um you know quit that operation and we'll continue to the next iteration we will just pass it you know go to the next um a character so we will decrement its frequency and go to the next character we won't do anything other than that then this while loop what it does is uh we are the number of elements to be removed from the top of the stack so we have to see what is the number of elements that should be removed from the top of the stack right so when the stack is not empty and the top of the stack is greater than the current element for example as I as seen here right um there is a vcabc and we see that when we push B and C and we end up when we're trying to push a we check that we checked that this previous element C is actually greater than a so that's what this means St dot top of is greater than the current element that is a is the current element right now so and frequency uh is greater than zero so this one also needs to be checked because if it is not greater than 0 if it is greater than 0 then that means um it is actually going to come after um the C is actually going to come after this one occurrence if it is the frequency is 0 right then uh that means it will not occur anymore that means we have to include it we have to make a we have find a way to include it we shouldn't just leave it so only if the if it is greater than 0 if it is one or two or more than that then we can just uh enter into a while loop and then we will make that uh scene as false right because now it is same you have to we have to ISO Phi is actually the current item so we will make it as I and we'll pop it we'll pop that previous element out then we will push our current element right s of I that will push it into a stock St then after pushing what we have to do we need to change um and we need to change it to true we will change our scene uh into true and then we have a we have to reduce our frequency as well then after that asking our string this is our actual answer that is an output answer and while the stack is not empty so until this type comes empty we're going to push it right back onto the we're going to push everything back onto that answer variable so and then we will uh we will pop out and after that we have to reverse it because the stack it connects elements from the in the decreasing order of characters from the back to the first so we have to reverse it so that we get the original um you know the original order so that's what we're trying here okay see it has worked and fan complexity is order of one thank you
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
1,464
Hello everyone welcome to my channel code story with mike so today I am going to share the video number of my lead code easy playlist lead code number 1464 maximum product of two elements in n Hey look problem before starting I want to tell you a very important thing. I want to tell you, look, I know this is an easy question, okay, but what do you think, why am I making a video, then it is an easy question, yet the most important reason for this is that we can maintain consistency, we are okay so that our brain So that we can get such a feeling that we have not missed even a single day, okay so to get the same feeling I make this video, neither consistency is the only key, if you are consistent, whether it is easy, medium or hard, if every day you solve If you are doing this then definitely you will see change over period of time. Okay, so for the sake of consistency let's do today's question also. The question is quite simple. It says that one integer is given different names. You will have to choose two different integers. If i nj of that are return the max maximum value of numbers i -1 in numbers j -1 Okay, it is quite a simple -1 in numbers j -1 Okay, it is quite a simple -1 in numbers j -1 Okay, it is quite a simple question like let's assume look here a if let's assume 0 1 2 3 any two numbers have to be selected and The maximum product has to be found but it has to be found by dividing the numbers by -1 -1. Okay, let's say -1 -1. Okay, let's say -1 -1. Okay, let's say I chose 3 more, this and this, okay then did 3 - 1 and then did 4 - 1, see how much has come, then did 3 - 1 and then did 4 - 1, see how much has come, then did 3 - 1 and then did 4 - 1, see how much has come, then 2 * then 2 * then 2 * 3 6 has come, okay let's choose this and this 4 my in 5 my 3 fo 12 this is the maximum, you will not get a bigger answer than this, try any other number, okay then think for yourself what should you do ultimately. We have to find the two largest numbers, their product will be the highest, like the biggest number F is visible, the second big number is visible, four is visible, 5 is mine in 4 mine, that is where our answer came, it is 12 and that is simple, I have given two by simple approach. It has also been told in this video, watch carefully, the first approach is very simple, I assumed that brother, my current maximum number is what I said, I just have to keep track of the maximum and second maximum number, okay, so I have written one here. Current maximum is assumed to be this one, ok for now, let's go with this value and the index number has come which is starting from one, ok and let's go by the result value, now mine is zero, ok, so now one task. Let's do this, which is currently my maximum number, I am taking it as three. I multiplied three by this income element, so 3 - 1 into rectangle, who is there on income index, then there so 3 - 1 into rectangle, who is there on income index, then there so 3 - 1 into rectangle, who is there on income index, then there is fur on income index. 4 - 1. Look what has come, then six has come. So is fur on income index. 4 - 1. Look what has come, then six has come. So is fur on income index. 4 - 1. Look what has come, then six has come. So is this more than my result? Yes, I have updated it in the result. Six is ​​fine and the current number Six is ​​fine and the current number Six is ​​fine and the current number is bigger than my current maximum. Yes, then we will update the current maximum also. Four is a big number of mine. Yes, it is bigger. The number is ok now come here mine is ok so let's do the same again by multiplying and let's see 4 is the current maximum 4 is 4 mive into i element which is f neither is it 5 mive is ok how much has come 12 is ok which That is greater than my current result so I updated it with 12 and the current i element is greater than the current max yes then update the current max also with f ok now my i will move forward again ok Now look again, we will multiply it by 2 - 1 * What is the current maximum? 5 2 - 1 * What is the current maximum? 5 2 - 1 * What is the current maximum? 5 -1 OK, what has come? 4 has come, is this -1 OK, what has come? 4 has come, is this -1 OK, what has come? 4 has come, is this greater than the result? No, if it is not greater then will we leave it. Is this element greater than the current max? It is not there, it is big, so we will leave it as it is, it has moved ahead, it has gone out of bounds, look at our answer, it has come in the result, the code is also very simple, you will do it immediately, okay, now let's come to our approach, remember what I said in the beginning. Was n't I told that if you find the largest and second largest number, multiply it and that will give your answer, then what should you do? Find out the largest and second largest number, find out what is fur and f, then multiply it like it is said in the question - By - By - By doing 1, your answer is 12. Okay, so how to find the largest and second largest number. There are many ways to do this. I took the largest one variable and the second largest variable. Let's keep both of them at zero in the beginning. Current index aa mine is here. Here I saw, is it bigger than the largest? Yes, if it is bigger than the largest, then the value that would have been in the largest will become the second largest, so I will put it in the second largest, so since now it is zero, then the value of zero remains zero. And I have updated the largest, okay, now look, when it comes here, is it bigger than the largest? Yes, it is bigger than the largest, so it will become the largest, but the already largest value which was three will become the second largest, okay. So I made the second largest three and the largest became four. Okay now when I come here, is it bigger than the largest? Yes then this large will become five and the one which was already large four will become second large then second large. I made it four and the current largest is my five. Now come here, is it bigger than the largest? No, is it bigger than the second largest? Otherwise, these two are mine. Look, five and four are my largest, second largest, both. Multiply 5 - 1 * 4-1 both. Multiply 5 - 1 * 4-1 both. Multiply 5 - 1 * 4-1 Our answer is here datchi and let's take a variable named result ok now see result is equal to maximum of result let's take comma product names of a given sorry numbers of a given multiply Whatever the current max is, it is fine. We are assuming that the current number is Namsai and the current max is the product of these two. Let us see whether it gives more than the max. It is okay if it is not so. So current max will be updated, current max or names of aa, whichever is bigger, okay, we will return the result in the last, let's run and see the example test cases first, indeed yes, after submitting, let's see, we should be able to pass. All the test cases will then come to our second approach in which we simply have to find out the largest and second largest number. Okay, so here I write, inter largest is equal to zero, we take int second largest and we take it as zero. For int and num in nums, if we select all the numbers one by one, then what will happen if it is the current number and if it turns out to be bigger than the largest, then what will I do, I will put the largest in the second largest and the largest is my num. Else, if it is not so, then I will check whether that number can come in second largest, if that number is not comma current, then it is okay, otherwise in the last, what we have to do is to return the largest my into second largest my. Okay, N has no use here, let's run, yes, submit and see, it is an easy question, so it is obvious, you will get some extra time in the day, so you must study something else during the same time, I will also try to study after office. I will take out time and make videos of some good questions also. See you guy in the next video. Thank you.
Maximum Product of Two Elements in an Array
reduce-array-size-to-the-half
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12. **Example 2:** **Input:** nums = \[1,5,4,5\] **Output:** 16 **Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16. **Example 3:** **Input:** nums = \[3,7\] **Output:** 12 **Constraints:** * `2 <= nums.length <= 500` * `1 <= nums[i] <= 10^3`
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue)
Medium
null
1,268
hey guys how's it going in this video i'm gonna walk through this legal problem search saturation system um i'm gonna solve this problem using two methods uh one is the binary search another one is uh a try i will use try first because that's more intuitive uh binary search is a little bit it's a more creative way i would be maybe a little bit faster uh so um that's why i'm gonna go through the try uh method first and then secondly will be the final research so this question was asked by mostly amazon so in the past six months it was question was asked by 28 times so it was fairly popular so let's walk through it uh the example in here um we are given a list of products uh mobile house money parts monitor uh house pad and the word that we are searching for was mouse and notice that we have one two so one two three four five characters in the in this mouse keyword search word so that's why in the return list we will have five output one two three four five and so the first output corresponds to the first uh the prefix of the first i so let me try again it's a prefix that consists of the only the first character and also we have to return a answer that is only containing um three products with a common prefix and they have to be sorted by lexicographically sorted um for this answer in here they correspond to the three product that comes from the products list and they all of them have the same prefix also they are sorted and then for the second answer um they have the same prefix once again but that prefix will compare the first prefix which is only have a single character which is m now the second prefix we have two characters which is mo and as you can see all of them has the same prefix as mo and also they have they are sorted and once again maximum three okay and for the third output will be mou for the prefix so both of this answer has a mou and um once again sorted and the next one will be mous sam mous and mom mousi right so both of them have the same prefix of ammo and ml usb and uh once again sorted so yeah that explanation just basically explains what i um just explained anyway so uh let's solve it by using a try because that's to me that was my um the first solution come to my mind i think that's the most intuitive so uh for a try we first have a try note as a class so that's a class within the solution class uh doesn't matter we can put outside but it's up to you um so the way that we build it uh there are multiple ways to preview a try one is using a list another one is usa set uh here i'm using a nested dictionary uh for example uh for the first guy over here uh first for the product which is mobile and we will have a nes nested dictionary uh the key in the character that we're looking at and the value being another dictionary that's why we call it a nested dictionary so for example mobile so the first key will be m and then the value will be another dictionary which looks like this and then the and then within that second dictionary the key will be o which is the second character for mobile and the value will be another dictionary so it goes on right so first m o second o uh third one is b and next one is i etc go all the way so this is an again nesting dictionary i couldn't say no couldn't say enough about this because that's the key how we built a tri node in this example and also we have a another attribute for this class which is the subjections so basically i say suggestions that come for each of the notes for example uh for m we will have a suggestion the word maximum three for m and the next one with mo and then we will have a suggested word for mo and also mob same thing i will walk through all i mean by that later on but this is something that we have built for this tri node and also uh to serve these instructions we can add suggestion to it right so maximum three that's why for this condition here and then we append the suggested word to the list okay so let's dive into the main content how we after we uh build this uh class architect architecture and then now we uh dive into how to implement it so first we have a root i think a good diagram is in the solution uh in a virtual solution here um we can see a root and for example the words is him her his team and high as you can see root as a very top and then you can dissect different characters right and for example uh on the right hand side here is the team so corresponding this word and uh he sorry not he should be her on the left-hand side over here and then he is left-hand side over here and then he is left-hand side over here and then he is and then him so basically um again we will implement this using a dictionary i think this is a good illustration on how we build the integration behind the tri node so first we have the root which correspond to this guy over here at the top which is the root of everything and uh secondly we will shorten the product uh list because we have to when we turn it we have to return a lexical graphical order that's why we need to sort it and uh first thing comes to my mind will be after we sort it will be the time complexity will be over n uh equals to n log n right because we're sorting it so for all the product in the products um list and um the current node that we're looking at the first column will be the root node that we're pointing to for all the characters in the product for example the first product will be mobile and then we loop through uh all the character and then build the try for example uh first current node will be pointing to the root second current node will be pointing to the m third one will be pointing to the o uh the next one we can point it to the b so we keep look through the character and then build up a try so this is how we uh build up our nested dictionary and then we add the suggestion the session will be the product keyword so let me show you uh i think it's more straightforward to look it up so uh for example mo y right here right so this is our try each one has this the nesting dictionary this is the first level or first level will be the root or we can call it the root will be the level number zero so it's exact first level with m second level of uh o third there will be b i next one l and e and then all the suggestion will be correspond to each of the character and then when we look at the next product which is a money part right and then again we loop through all the character i mean the m notes will be the same m notes that we had before and then because of for the example for that reason we will have the two different suggestions maximum suggestion will be three right and then the next one will be the n no the o comes after the m which is the same for the mobile and that's why we have the same we append to the same suggestion list the next one is different okay so this is the another branch different from the mob now it's mon so that's why we have a brand new suggestion this is money pod originally we have a mobile so we keep doing it until we build up on the in the entire tree and try three so i'm gonna comment this out because we don't need it no more and after that oh so before we go in further we uh i would like to analyze the time complexity right away so uh it will be the big o of uh the time complexity will be oh total number of characters in the products list right because we first look through the product secondly look through all the characters between all the products each for the product so after that let's um look at the search word and we need to bring back ourselves to the um the root note which is at the top uh which over here how should we do that is just pointing to the current node back to the root which is we define over here and then we have the result list for all the search character in the search word the current node equal to current node.child so this is basically how we node.child so this is basically how we node.child so this is basically how we it's the same thing over here it's how we access to the try to see each of the prefix and then we look at the subjection for the prefix by appending to the result okay let's run that works and for the time complexity for this part will be on the big o of the length of the search word is depending on how many characters that we're looking at so um in total uh the time complexity of b o n log n plus this part and then plus this part and depend on which one is dominating but this is my analysis for the time complexity for the space complexity will be the number of a unique um character because we have to build a try tree that's why we need to know how many unique characters in the products list okay so that's one method which is used uh the try method the next one i'm gonna use i'm gonna solve this problem by using the binary search which is a bit more creative and honestly this method didn't come to me until i look at the solution uh because the first method came to my mind again it was the try method this is slightly faster so same as the pi method we have to sort the products again time complexity and we look at prefix which we initiated as an empty list md string and then we also have a result list same setting as before for all the search character in the search word so we look through each of the character and immediately that comes to me that this will be um well uh this we use this is where we use the binary search and uh the time complexity for binaural research will be log n and then we do that k times so the entire time complexity will be k times log n and k being the length of the keyword so hot depending on how many characters that we have for the search word and um we have to add it together first because we have to sort it first and then do the this photo these two follow-ups here this is not very time follow-ups here this is not very time follow-ups here this is not very time consuming which i will walk through with you uh later so uh this it feels a bit strange that i analyze the time complexity first because i think that's easier for me uh to keep track of uh the time complexity but it's up to you can analyze at the end um anyway so let's dive into the algorithm to see how it works so uh first we append uh the search word to the prefix that we universe initiated as an empty string at the beginning so basically let me go back to here so the first prefix will be m second one will be mo mou et cetera and then now where this is where we apply the binary research so basically we insert uh the prefix from the left and this is text we are logged in so i think it's a bit easier to just print it off and i'm printing off the sorted list for product also i'm printing off the prefix also the inserting precision um which is the output of the binary search so let's let me output that um so this is the way it confuses me at the first time um so the sorted list is looked like uh so this is the input right after we saw it looks like this so mobile money parts monitor mouse mousepad okay and the first prefix again will be m and mo m-o-u-m-o-u-s-m-o-u-s-e mo m-o-u-m-o-u-s-m-o-u-s-e mo m-o-u-m-o-u-s-m-o-u-s-e and this is the index which at which we will insert from the left so we have a prefix m so we will insert to the serious index mo also at the series index mou will be at the third index which is the fourth place zero one two three right mmou will insert here and then this one will go to the left so uh we will shift to the left so b and after we're shifting it will be um well the bias the research won't do the shifting just you will figure out the index and will not do it in place by the way so mou will be in here mouse will be in here mo you as you also will be here in here which is the same as issuer and uh because we insert from the left that's why we have a higher priority than the word that is already in the list and then because we are only look at the three um product that matches up with the prefix so that's why we only look at uh again this one has been sorted this is to our advantage look at the insert position also the insert position plus three because we only look at the three product and then we do some comparison right if that matches up with the so we apply the method the string method of the stars with is the prefix that we're looking at which will increase one character at the time and then we append it to the tam list which it is empty for each of the prefix and then we append maximum three products to it and then at the end we append the temp to the result and then at the end we just reach in the result so the most confusing part and most creative part was the injured possession by using binding research i was very amazed when i was uh come across this solution so anyway let's run that see looks uh a bit more efficient than the pi method that we had before uh for the try so this there you have it uh this is my solution to this problem i hope this is helpful if it is please like and subscribe that would be a huge support and thank you so much for watching i will see you in the next video thank you bye
Search Suggestions System
market-analysis-i
You are given an array of strings `products` and a string `searchWord`. Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products. Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_. **Example 1:** **Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse " **Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\] **Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\]. After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\]. After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\]. **Example 2:** **Input:** products = \[ "havana "\], searchWord = "havana " **Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\] **Explanation:** The only word "havana " will be always suggested while typing the search word. **Constraints:** * `1 <= products.length <= 1000` * `1 <= products[i].length <= 3000` * `1 <= sum(products[i].length) <= 2 * 104` * All the strings of `products` are **unique**. * `products[i]` consists of lowercase English letters. * `1 <= searchWord.length <= 1000` * `searchWord` consists of lowercase English letters.
null
Database
Medium
null
11
Hi guys I am Nishant Chahar welcome back to the channel Aago Prep in today's video we are going to talk about this question its name is container with most water what is given in this question friend we are given a histogram we are not making containers in it Pass na like have different heights first let's read the question you are given n integer ger are heights of length n there are n vertical lines drawn true that the two end points of eight lines are aa 0 and aa height earn aa means e find Two lines that together with This type can fill some water so we ca n't calculate basically so it's not allowed okay so what is we tell etli we have to tell how much water we can fill in this container now multiple what type This can be made into a container. Okay, this can be made into a container. It will hold one unit of water. Then this can be made into a container. Okay. It will hold six units of water. This can also be made into a container. Right, this can also be made into a container, so tell us the maximum volume in which container is being stored. Let us tell you in which container the maximum volume is being stored. Okay, so how can we tell? Now let's discuss it. The brute force solution that comes to my mind is, what do we do, we take out all the containers, what do we do, we took out this container, then along with this, we took out this one, basically, we did everything first with this index. Removed all then removed all with this index and returned the maximum from them. Out of that we returned the maximum. Okay basic root force order of n squared and each time area We will calculate the area, what will be our area, right minus left into now, which minimum will we take or will we take the maximum? We will take the minimum because water can flow from above the minimum, so what will we do into the minimum of height, basically do length in breath. Okay, we are taking the length, we are taking the minimum, we are taking the breath from its index, so basically the area which will be ours will be mine coming into our mim of what minimum of heights will be taking the minimum of heights, whatever will be on our i and jth element because see if If we take a bigger one then we cannot fill the bigger one with water, hence we cannot fill it with water, we will have the right to come in it only till here, then whatever is smaller will overflow over it, so basically we need minimum here. In this, height of ama, height of h will be our area and we have to find its maximum. This is our bluet force solution, but we have done this type of question earlier in which we have just the root four solution. So, that means, how will we do it in order of n? Let us quickly see what we need at each point. We will do it with two pointers. Okay, so this is what we need, that we should take out the maximum water, which will be the smallest part. We will do it in that. If we remain standing then there is no point, it means we can never find the maximum with this, we will have to move ahead from this, so basically we will take two points, left and right, what will we do, we will find the minimum between them, height is fine, multiply it. We will make the width of both of them that is right minus and whichever is smaller, we will increment it. Here we have incremented the left, then now we compared here, we have seen that the right is smaller here, so we will increment the right, again the right is smaller. If both are equal, then again we will increment the right, by doing this we will calculate at every point, so now its maximum is coming. Right, what is the maximum, this part of ours is coming, how much is this part, look here, seven is height and sen is the distance between it, 1 2 3 4 5 6 7 so 7 * 7 is 49 so 49 marks come. 4 5 6 7 so 7 * 7 is 49 so 49 marks come. 4 5 6 7 so 7 * 7 is 49 so 49 marks come. I am getting 49 marks, so that should be ours, it is ok, we will try without drying it, we will see without drying it, we said, let us compare, is the value of our left is smaller than the right, yes then it is ok, we are still waiting. We will remain in the loop as long as we run this loop till the value of left which is smaller than the right, if it overpasses then there is no use of running it. Now we will check whose height is smaller, currently left is our row. The right one on the right index is ours on the right index 8 7 6 5 4 3 2 1 0 Okay, so we checked here, we said whose height is smaller, the one on the left is smaller, so which will be the minimum, what will we do with the left one into this? Is right minus left that is 8 my 0 e 8 So here P is our 8 We checked which is smaller Our left is smaller We said let's increment it Let's bring the left here Okay then We have calculated which is the minimum among these two? What is the minimum index of 8? What is the value of 7? How much will we do in these 8 minus 7, so our 49 has come, the answer is ok till now, what is our maximum answer? 49 is being made then. We checked who is smaller among these two, his height is eight, his height is six, so D is with us, so we will increment it and decrement it. Right to right, one will come ahead, then we will calculate again between these two. Who is the minimum among them? What is his height? Okay, and the minimum has become 3 * Okay, and the minimum has become 3 * Okay, and the minimum has become 3 * 6. It has become 18. Who is the maximum among them? It is only 49. Now again what have we done? We have incremented the right. Our right has come here. So we checked again what is the minimum height of both of them, they both are the same, so our height into width is 8, so it is 40, now our maximum is coming to this, okay again we checked these. We take the case which is equal to two in both, whenever it is equal to two, we will increment and decrement the right, here the right will come, what is its height, 4 then 4 * 4 16 come, what is its height, 4 then 4 * 4 16 come, what is its height, 4 then 4 * 4 16 4 * 4 * 4 * 4 16 then one, we will increment it again. It will come right here, we were right here, then it will come right here, okay what is its height in 3 e 15, then it will come right here, now this in both of these, who is the minimum in these two, this 2 in 2 e 4 and last left is this in Whose height is smaller among the two? This is 6 Nav E 6 So we can see in this that our maximum is coming this is our answer, here we are using two pointer and in two pointer we are taking the decision which height is smaller. Is it right on its basis and yes we are able to solve this question using this approach so basically why is this approach strong? Our height which is our entire area is always limited on height. The limiting factor here is the height because we want the maximum which is width. We can take that index last, meaning we can take it between the last index and the first index, but whatever height is smaller, it will limit our total area, so what we can do is we can try to maximize the height. Keep minimizing and simultaneously keep checking out which is the maximum in whatever area is being built, right, so this was the whole idea of ​​this approach, let's of ​​this approach, let's of ​​this approach, let's look at the twelve code, so find the height, left and Right is taken, answer is taken, as long as the value of left is less than right, what will we do, we will find out the answer, that is marks of answer, comma, this is our width, right minus left is minimum of height of left and right, if left is smaller then left is plus. If there is nothing like this, then right minus ts it and this will pass all our test cases. Right so if you have any doubts, it is okay to try a dry run first. In this, I used a two pointer just because of this. One, we have to order it. Right had to be done in n, it had to be done in the order of n and we do not have many options to do it in the order of n. Whenever we have to solve a problem, we can either put the prefix sum in it, right or We can do something by taking extra space in it. Okay, we could not do sort in this because by sorting our whole thing will get spoiled and its time complexity will be different n and this was this is one of the approachable n has to be brought in. Our time complex means that we have to reduce one from n squared or bring it to n -1 by any power. For this bring it to n -1 by any power. For this bring it to n -1 by any power. For this we use two pointer like two has become even, three has become even, four has become even. We do these questions, we do questions with differences, we use two pointers in all these because it makes our time complex less, so I hope you guys must have understood this, do check out ago prep d a and i. Will see you in the next one
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
24
Hello everyone welcome to me channel in pairs ok read number 24 medium to mark but aap sorry sun lo you bill be able to solve it on your own I am pretty sir ok very similar researcher solution today I will tell on this video ok so It is not medium at which is fine, it will be very easy, trust me, look at the input output and understand what is the question, then look at the question, here I will explain it to you, I have given you a link, okay, the question is quite simple, I have given you pairs only. I have to swap the notes, not the value of the note. The entire note has to be swiped. Okay, look, this is A, it will go here, and this is B, it will go here. Look, this B is here, A is here, this is here. It is okay, similarly, this C note has gone here and this one has gone here. Look, you have to swap it, you have to swipe the notes, not the value of the note. So let's see how to solve each one. If you can then see, you can solve it very well in the requested manner, isn't it attractively but the best approach is solving the questions on time or there were other links too. The questions are very well like lying in a linked list and flattering a doubly linked list. In such questions, if you do it iteratively then it will be very difficult because you will have to maintain the pointers or you will have to enter a lot of checks, then the best solution is for such questions, brother, you write the explanation for it is very nice and the explanation is very good. It is helpful in making questions like licks. Okay, so here let's understand a small story so that they can be able to write the description very easily. Okay, so let's start our story. So, let's start our story. Okay, so see. First of all you should know what head means here head is pointing to A and you also know who is next to head brother head connection now let's move towards our story okay so like mother Let's say you are standing here, now you are standing here, you know right now, okay, I am standing on the G note, with whom do I have to swap it, whatever is just next to it, okay, that will also be tasted later. But where I am standing right now, I should taste myself, just from the person next to me, it is okay till now, it is clear, so let's see how we will swap, okay then like mother takes it, whenever if mother takes it gets swapped, okay so It is the same thing, A will go here, okay, if A also goes here, then what will be the next one, this part will be this part and these parts will also have become taste in itself, okay and I will tell you brother. Swap the next link list and bring that one, I will assign it to the next one, that is what I am saying, what will happen in a N I did it yesterday and said that brother, you swap and bring the result, I will sign it, okay, now what am I sending in Swad Solve, by the way, this is the first link of the part, I will send its note, I will send it to C, right, send it to C. I will give and what is C, look at me, then head is next to next, okay, so what will I send here, head is next to next, okay, so this line should be clear, you must have cleared this line by now, okay, so this line. Okay, I am moving here separately and I am late. I have written this line below here. You must have understood that I have not put any extra thought into it. I just said that A is next because it is here. It will be swapped and this next one will be a part of the link, right, and it will itself be swapped because I have written the recovery, it will do it for me, I have the trust, I have it, okay, we have solved this. Lia, now the question has come that brother, what is this, is it right, what will be the next of B, it will become A, so let's write it here brother, what is the next of head, so instead of B, I write there is head connection. Okay, now last tell me one thing, okay, B is here, A is here, okay, that means our link list has been swapped, so remember, B is here, A is here, this is the taste of Dhaba. Let's take our mother after getting anything A. Okay, so now which is the starting note of my link list? Brother, B is there, remember that So we will return that only, now the first note of my link list is temp, that means the head has changed, it has been solved, okay and you have got a little bit of confusion relief here, a little back when you look again. Let me repeat our story again, what we said is that brother, from where I am standing, I can swap A and B. Brother B goes here to A. This should be a part of the remaining link list because there is another B. So if I have solved then send C here OK, I have written the same line here that brother, whatever is A, what will happen next, this is the remaining link, its answer is correct and this was mine, what was the next head of A, connect this equal, you solve it. This answer of mine to the remaining link is clear till now, what did I say that brother who was B is going to be next to B, now he is going to be A. So here I wrote that brother who is next to B is going to be A if he says head. Then I saw here that you can write 'A' instead of 'head', can write 'A' instead of 'head', can write 'A' instead of 'head', so instead of 'head' I so instead of 'head' I so instead of 'head' I wrote 'sorry head' and 'b' means what was 'B', 'B' wrote 'sorry head' and 'b' means what was 'B', 'B' wrote 'sorry head' and 'b' means what was 'B', 'B' was my 'B was my'. You are changing the next fact of 'head' here, so what have I done? The one that was next to the head is actually the old one, that new link of mine is going to be its head, so I will return this one, see I have returned this one here, think it dry a little bit and do more and see your [ __ ] will be all done dry a little bit and do more and see your [ __ ] will be all done with ok dry color. First tell me one thing mother, let's take the input that you have given, the link list is something like this, it means there is only one note in it, if it is tap then nothing has to be done, meaning if the next head is tap only then it means There is only one load, nothing has to be done, just return it, or if the head is taped, then brother, how am I, what do we have to do, we have to return it, ok, return the head, nothing can be done, ok, so remember what I said. He said that first of all what I will do is that the head is next, right now the head is pointing to it, I will store the head next in the temp, so what have I done in the temp, I have connected the head, if it is brother, then B and so on. I have done it and what I said is that what is next for the head, what is going to be made next for the head, I have taken the new link, I have taken the link for the children, I will write a function named 'Vasd Pairs' for them and I will write a function named 'Vasd Pairs' for them and I will write a function named 'Vasd Pairs' for them and I will send the next for the head, which means the next for the head. I will send the next one and he will clean it and bring his own. Okay, so what does it mean that this function is not this function, it will reduce my whole, meaning what will it do, it will really solve my answer here. Here I went, three A, okay, here I went C, so mother, let's take this function, it gave me the answer by swiping and sent it, brother, one's next, which means this is the new link, this is the link, right? Its starting note has been given, now the starting note has been given, earlier it was C, now it has been given, so it is okay, Head will be DC in the next, so what was the head, brother, was it my B, so who has signed it in the next. I have signed it, I have remembered that means this link must have been broken and it must have started pointing to it, okay now I went back that brother B, this is B, next to it should be A, only then the swap will happen, okay so here. But remember what I said, the time connection is also mine, it is okay till now, it is clear, then what is to be returned in the last, return taper has to be returned, A has been there before, right before, A has gone, this is my B, this is the one which is A. Now I have my 4G here, I am telling you that if you go to make such questions like flattening of link list now then you will face a lot of problems. I just did this yesterday and said brother, you solve it and bring it for me. That's all. This part had to be assigned here, and ours is reduced, okay, we do it in liquid, friend, we have understood the very simple calculation, so I have to say, friend, it is very important to write a story for such a question and the calculation is nothing but. Just writing a beautiful story, you trust me, okay, what I said in the beginning, if my head is the tap or is the head's next channel, this is what I told you, do you remember, then you will swipe from someone next, what will happen now? What was going to happen, brother, the remaining link list is the remaining link list, where does the head start, the next one starts from the next one, which is my seat, remember, I will write. I also give this, what was mine was head, okay and B was mine, what was next to head and what did I do After that, what I said was that brother, the one who is B was going to be next to A, so at one place, head. Wrote and instead of B, what is the problem that brother, look at the head connection here, we have modified it, so let us store the head connection here, this is equal, the head connection is fine and the head connection will be done, it is easy, submit. Let's try using and recjan approach any doubt comment area ultra next video thank you
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[2,1,4,3\] **Example 2:** **Input:** head = \[\] **Output:** \[\] **Example 3:** **Input:** head = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. * `0 <= Node.val <= 100`
null
Linked List,Recursion
Medium
25,528
191
hey everyone welcome back and let's write some more neat code today so today let's solve number of one bits this is actually another blind 75 problem and we've been tracking all blind 75 problems on this spreadsheet the link to that will be in the description today we'll be doing number of one bits one of the last problems remaining that we haven't done and i also have a youtube playlist for the blind 75 solutions link to that will also be in the description if you do want to take a look okay so now let's get into it we are told to write a function that takes in an unsigned integer which isn't really important for this problem because all we want to do is count the number of one bits that it has so the concept is pretty simple so when you take a look at this number we can see it's made up of zeros and ones and we just want to count how many ones it has clearly it has one two three so we can return three but how can we actually count the bits so obviously we need to do a little bit of bit manipulation i'm going to be showing you two different solutions one of the solutions the second one is going to be slightly faster if you're interested in it and it's pretty difficult to come up with but the first solution is a little bit more straightforward and is more doable so like i said the easiest way is just to count manually bit by bit and then see which one of them is our ones and then increment our total and then return the total but let's see how we can actually accomplish that so how do we know let's say we want to look at the first a bit on the right side how do we know if it's a one or a zero well there's actually two different ways one way is you can and it with the integer one so since the integer one just has a one here and then the rest of them are zeros when we do a logic and operation logic and is basically taking the and of every bit but we know that every bit is gonna be zero when we take the logic and it's gonna be zero for every bit except for this one which can either be zero or one it'll be one if the bit in the input integer is one then we'll get a one in the output if it's a zero over here then we'll get a zero in the output so that can tell us if there's a 1 here or a 0 here another way to do it is just to mod this by 2. modding is basically taking this dividing it by 2 and getting the remainder since this is the ones place if we mod it by two and there is a one here we'll get a one in the output if there's a zero here we'll get a zero in the output so we have two different ways to do it i think i'm gonna stick with modding but you can do it either way okay so we have a way to detect if the first bit is a one or a zero but what if we want to look at the next bit and the next bit how do we do that well the easiest way would just be to take all the rest of the bits and then shift them to the right by one and luckily most languages can natively support this and it's a very efficient cpu operation this is kind of the preferred way to usually do it in bit manipulation just shift every bit to the right by one we can achieve basically the exact same thing by taking this and then integer division by two dividing it by two will basically shift all the bits to the right by one as well but usually the bit shift operation is a little bit more efficient on your cpu so that's what i'm going to prefer so basically we're going to take these shift them to the right so now we're going to have a new integer 1 0 1. again we want to know if this bit is 1 or 0. we're going to mod it by 2 we're going to get another one so far we have counted two ones and again we would want to take these shift them to the right this time we get a one zero we mod this by two we get a zero in the output that means there's a zero here so we don't add to our total this time and lastly we take this shift it by one we get another we basically get the integer one we mod it by two one divided by two the remainder after that is just one so we got our third one so our total so far is three ones that we counted and lastly we're going to take this and then shift it to the right but what exactly is going to be remaining after we do that well basically zero and once we have a zero it basically means we have all zeros right 32 bit integer we'll have 32 zeros and that basically means that we can stop our algorithm now and we're done so we counted in total three ones and that's what we can return so once you're familiar with these bit operations it's a pretty straightforward problem so let's code up the first solution okay so now let's code it up i'm going to declare one variable for the result which is basically the total account the total number of ones that we're going to have and i'm going to continue counting the ones while n is greater than zero or in other words while it's not equal to zero which i can you know do just like this and that'll work in most languages i think and then we want to know if the ones place is a one or a zero so we can take n and mod it by two now this will either be a one or this will be a zero if it's a one then we wanna increment result if it's a zero we don't wanna increment result so in other words we can just basically add this to our result itself and then we don't want to forget to shift everything to the right by one so what we can do is set an equal to itself bit shifted to the right by one after that last thing we have to do is just return the result so now let's run it to make sure that it works and as you can see it does work and it is pretty efficient but what exactly is the time complexity of the solution well the good thing is that we're guaranteed that every input is going to be a 32-bit integer so we know that be a 32-bit integer so we know that be a 32-bit integer so we know that while loop we had is going to run 32 times so really the time complexity is big o of 32 which is constant time right no matter what the input is the time complexity is not going to scale up so basically the time complexity is constant we can say it's big o of one and there's no real extra memory complexity needed as well so that's also big o of one but a small downside of our solution is it has to count it has to look at every bit even the ones that aren't ones so for example what if we had a number like this in this case we're gonna look at this bit first okay it's a one we're done with that then we're going to look at this bit every bit here even though they're zeros right that kind of wastes time wouldn't it be convenient if we only had to look at the bits that were one that meaning our algorithm only has to run as many times as how many ones are actually in the input and yes there actually is a way we can do this but it's not very easy to come up with and it's probably not even worth coming up with because the time complexity will be the same it'll still be constant time and constant space but it might be good to just you know get really good at your bit manipulation tricks and stuff and maybe you'll see this in an interview so the main operation we're going to be doing in our while loop with this trick is basically taking n and setting it equal to n logic ended with n minus one and this is what we're going to do in every iteration of the loop and each time we do that we're going to increment our result by one but the question is why does this work first let's see what will happen so okay so what's gonna happen let's take this integer and subtract one from it right that's what we're gonna do over here so n minus 1 which is going to be this and now we're going to logic and them together what are we going to get when we do that we're basically going to be removing this right this we're going to get n minus 1 itself and we're also going to increment our result by 1 now regardless of what the output happens to be okay so now our n value is going to be set to this okay so now our new value is going to be 1 0 and all zeros okay now we're going to take this number and subtract one from it what is that going to look like in binary well it's going to be 0 1. okay and now we are gonna logic and these two together what's that gonna look like well we're logic handing every bit this one is gonna turn into zero now and the rest of these are also gonna be zero even though we have ones in the bottom number we have all zeros in the number above so now we're actually done with our entire loop now we have all zeros we incremented our result by two so now our result is two and then we return right which makes sense because when you look at the original number we started with it yes it did have two ones in it but how did this algorithm work well it's actually really simple but it's definitely not easy to come up with what we're doing when we're subtracting one from itself is we're basically getting rid of a bit right when we took this number and subtracted one from it we got rid of this one bit right and remember we're counting one bits so when we did that we increment our result by one but then why did we logic and it together with itself well basically since the rest of the numbers stayed the same and you know we took this one away here and then we logic and them together we're basically removing that one bit so then when we logic ended these two together you can see that the one bit was removed but the rest of the number stayed the exact same on the left okay that works but what about this number right then we were left with this and then we subtracted one from it then what did we do well again when we subtracted one from it we basically got rid of the next one bit right you can see that when we subtracted one from it this is what the number looked like we got rid of this one bit but we introduced a bunch of other one bits but these are all okay because we know they're gonna be and any one bits that we introduce are going to be on the right side and we know that if we just deleted this one it was the right most one bit that we had so any ones that are introduced to the right side won't matter in this number this is n minus 1 by the way any ones here won't matter because remember every time we do that we're logic ending them together we're logic ending n with n minus 1 so these are all gonna cancel out and this is going to cancel out as well the position where we you know remove the one bit so basically what we're doing here is we're skipping all the zeros in between we're basically allowing ourself to run the loop as many times as basically as many one bits exist in the input integer it's kind of a really weird trick but it definitely works and it makes sense why it works now we can code it up and it's pretty simple so you can see that this was our original solution and we only have to modify this a little bit so what we're going to do is get rid of this line and instead of incrementing our result by n mod 2 we're actually going to increment our result by one each time because each time we increment this we are going to be setting n equal to n anded with n minus one so we're going to be counting the number of one bits exactly and this line can actually be slightly shortened by doing this in most languages and yeah so this is about as efficient as we can get we won't run any extra iterations of this loop when we have zero so let's run it to make sure that it works and you can see yes on the left side it works yeah the run time is about the same because it's still the same exact big o time complexity but i hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **Constraints:** * The input must be a **binary string** of length `32`. **Follow up:** If this function is called many times, how would you optimize it?
null
Bit Manipulation
Easy
190,231,338,401,461,693,767
1,455
hey what's up guys today not true alex at this connection structures and algorithms check if a word occurs as a prefix of any word in a sentence so prefix so given a sentence that contains of some words separated by a single space and a search word so search words and uh sentences you have to check if a search word is a prefix of any word in the sentence return the index of the word in a sentence where search word is a prefix of this word n minus one indexed if a search word is the prefix of more than one word return the index of the first word minimum index if there is no such word return minus one so prefix of a string s is any leading contiguous sub string of this i know they're talking a lot again i love eating burgers search equal to this problem is an easy problem okay search word equal to pro or pro so like this sentence this yellow medium this is it so prefix diction but i know because there are index in general but in this case so uh this pro is an easy problem let me know output two pro is a prefix of problem which is the second and the sixth word in the sentence but we return to as it's the minimum yeah i don't know why uh confused so ziga i'm tired the please like subscribe the channel subscribe
Check If a Word Occurs As a Prefix of Any Word in a Sentence
filter-restaurants-by-vegan-friendly-price-and-distance
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** sentence = "i love eating burger ", searchWord = "burg " **Output:** 4 **Explanation:** "burg " is prefix of "burger " which is the 4th word in the sentence. **Example 2:** **Input:** sentence = "this problem is an easy problem ", searchWord = "pro " **Output:** 2 **Explanation:** "pro " is prefix of "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index. **Example 3:** **Input:** sentence = "i am tired ", searchWord = "you " **Output:** -1 **Explanation:** "you " is not a prefix of any word in the sentence. **Constraints:** * `1 <= sentence.length <= 100` * `1 <= searchWord.length <= 10` * `sentence` consists of lowercase English letters and spaces. * `searchWord` consists of lowercase English letters.
Do the filtering and sort as said. Note that the id may not be the index in the array.
Array,Sorting
Medium
null
1,461
hello welcome to my channel today I am solving the problem 1 4 6 1 check if my string contains all binary codes of size K so given a string s and an integer K we have to return true if all the binary codes of length K is a substring of s otherwise return false so for the example 1 we have a string 0 1 0 and K is 2 so for K 2 let's start so for K 2 for K equals to 2 we have here like K equals to 2 we can write 2 for 1 I will append 0 1 0 and 1 so in this string we have this so our string s is this string s so if we check we have 0 yes we have 0 we have 1 yes we have 1 we have 0 1 as well and we have 1 0 so we are able to get all 4 so this will return the to all four binary representation of length to be having that string so it's certain for similarly in example 2 we have 0 1 0 and K again to so if we check 0 1 is there when 0 is there one when you know again we have to return true because we are able to get all the 4 in example number 2 0 K is 1 0 &amp; 1 is only the 2 number 2 0 K is 1 0 &amp; 1 is only the 2 number 2 0 K is 1 0 &amp; 1 is only the 2 binary division so we can get in example number 4 we have again case 2 0 1 we are getting 1 0 we are reading but 0 string binary representation of string to rank two we are not getting so it's will return false because we are not getting all we are only getting three so for this solving this one approach is like generate all the winery representation of length K and then check all in the string better is contain or not a system so that will be air too costly and the brute force solution but another thing what we can do we will cut all the substring so we will generate all the substring from as so generate all the substring so this is the string and this is I and so we will generate all the string of length two all the string from this our string has substrings of length K basically so K is 2 here too so we will get here from this all strings are 0 1 again and 1 0 so we will get all them so if we save this all of them in the side so the duplicate strings will be returned they moved automatically so we will only laugh 0 1 and then 1 0 so this is total for total 4 and which is equal to keep our 2 so to keep our K so this is the approach we will use to solve this and simple using sliding window we will create all the substring of length K so let's start the implementation so implement for implementation for int so I need a set which will hold over all the sub strings of length K set is equal to noon as and after that we will run through this in I is equal to 0 I less than or equal to s dot length minus K because till max K we can generate only n minus k plus 1 sub assisting in my script so this will be I plus and after that we will add sad dot ad as dot substring of length substring from i to i plus k and in the end we just simply return if set dot size is equals to mat dot power of 2 comma k so that's it let's run our quote seizing is chatting - let's take all the other is chatting - let's take all the other is chatting - let's take all the other test cases so we have this custom test case so here in custom test case this example - and let's see create 0 1 0 and example - and let's see create 0 1 0 and example - and let's see create 0 1 0 and most K is 1 and let's create a another one the example number 4 which is length 4 so the example for which K has 4 less radical our custom examples so not a valid type oh okay well II type of type a string so I think okay the comma a mystical meaning so if we see it is passing all the custom test cases let's submit our solution this is accepted so this solution time complexity is just simply orphan here an interesting land so that's it thank you if you liked my video please hit the like button and subscribe to my channel for future videos
Check If a String Contains All Binary Codes of Size K
count-all-valid-pickup-and-delivery-options
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively. **Example 2:** **Input:** s = "0110 ", k = 1 **Output:** true **Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring. **Example 3:** **Input:** s = "0110 ", k = 2 **Output:** false **Explanation:** The binary code "00 " is of length 2 and does not exist in the array. **Constraints:** * `1 <= s.length <= 5 * 105` * `s[i]` is either `'0'` or `'1'`. * `1 <= k <= 20`
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Math,Dynamic Programming,Combinatorics
Hard
null
63
Big Max Speech on WhatsApp Welcome Back To This Note YouTube Video Dance Video Vishal Ginger Hai Number 63 Also Called S Unique Path To File 2004 List To Challenge Solt With A Robot Is Located Top Left Corner Of My Grand Master Tinder Diagram Below The robot can only move down or sight at any point of time on this front camper bottom right corner of the greats monthly pension diagram block key consideration of the girls where to the great women unique 5-day week of clans Pisces Smart Tab-10 respectively 5-day week of clans Pisces Smart Tab-10 respectively 5-day week of clans Pisces Smart Tab-10 respectively In Sacred To Give Number And Grade To Which You Can Also Called Me And Be Given To You And You Are Trying To Reach The Top Left Corner Bottom Right Corner And Subscribe 120 Ki And Everyone Laugh Kal Grade 2018 Latest Video Examples To Understand Problem Statement - 01 Initials of the method for Statement - 01 Initials of the method for Statement - 01 Initials of the method for example of service and rest where quite subscribe to the Page if you liked The Video then subscribe to the u Research and Similarly in the End Khwaab Nikal 8051 Chaudhary Only One Father Died Later This Problem Solve Question is the thing subscribe Video subscribe solution OK what is the thing subscribe And subscribe The Amazing off kar do ki spoch dat we are going to end support videos science college and Function And Press The Parameter Squat Performance Function Award Winner Equation And Can Check For India Servi Current Acidification subscribe The Video then subscribe to the Page I am very ok software engineer Settings Variables and Rebellion and Columns and after doing all passing affairs including subscribe and subscribe the Present Position Not Outside 3500 and Video then subscribe to the Page if you liked The Video then subscribe to the Wind The students drowned with sacrifice of President on the definition of the last rights where written records - 2 - Current rights where written records - 2 - Current rights where written records - 2 - Current Affairs Hindi World Channel Ko Subscribe if you liked The Video then subscribe to the Subscribe To Vikas Aur Problem His Lord Of Overlapping All Problems Overlapping Problem Video Record Only And Only Parameters Petting $100 For Meter Report To The Land Of Blood $100 For Meter Report To The Land Of Blood $100 For Meter Report To The Land Of Blood And Difficult Values ​​For The To Do And Difficult Values ​​For The To Do And Difficult Values ​​For The To Do Subscribe And Subscribe of subscribe and subscribe the Channel subscribe Loose Already Calculated and Fruits Calculated Will Just Returned at Distance a Lot of Time and Lot of Resources at this Thursday subscribe and subscribe the Subscribe Complexity of Boys by clicking on subscribe The Channel Please subscribe and subscribe the Video then Aadha Kal Grade OK Inverted Basicly Deposit An Ambrose And Mrs That Time Of Length And Width Appointed Point To Same Sense Of The Rings With subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page The Fact That Condition That They Are Adding Years Were Attacking Before Making The Record Schools Were Taking Note Of Mike Myers On Doing Withdrawal As Already Made videos Returns The Video then subscribe to the Page if you liked The Video then that and three to four Lines with three to four lines you can completely cover problem to complete only solution the power off shoulder dress programming language problem turn on bluetooth setting subscribe thanks for watching this Video don't think in terms of water every cell of unique way to reach to the problems of Your life you two things for subscribe to ok to dozen observations that I want you to know details of look at all the best problem and only one possible unique web site you can restore this is Bigg Boss side considered that gives users can go to The Only One Way Go From The Go To Do Subscribe All The Best Compliments And Complaints From Which The After All The Values ​​But With Hubris For Values ​​But With Hubris For Values ​​But With Hubris For Students Long Life Dieting Tune Of Good Boy Dress Possible Because It's Due To Give The Country Has Not Been Given And The Air Cleaner Simple Example To Explain The Scene More Medium To Subscribe And Subscribe To This Channel They Present To Stop This Way System Is That One Witch Is On The Topic Plus One Witch Is The Date Off Birth only two possibilities and which has already been calculated from being one does so for this particular central total number of units subscribe to subscribe the Channel Please subscribe and subscribe the Channel subscribe and subscribe the Top Fans Subah Two Plus One Should Also Welcomes One Okay and finally Bigg Boss you look plants from this particular you can come from top and from love you can leave a comment for final destination wedding subscribe and share subscribe anywhere between to of the that as you would happen to WhatsApp Ne I Just More Something Like This Youth Option Hair Soft Basically A Tourism Studies For The Days For Students Fall Ill Have You Tried For This Point To Do The Fair For This Point To The Point For The Subscribe The Video then subscribe to the Page Andar Voice recording to credit and creating dp table and initializing at all students similar to the top grade the terror attack in rome and settings problem with that person lump setting bluetooth off the they can only and only for telling withdrawal subscribe Complete The Phone Is Boot Complete Leave Respected And Not For The Okay So Doing Yr So In This For Loop Yorker Complete Problem Okay Yr Do The Wolf Olins ep01 More Settings To Visit In Between The Thing Open Bluetooth Settings Evidence Of subscribe The Channel and subscribe the Channel that in 10 Previous Lucerne OK Fennel Here What They Are Doing This of Acid in Adhoi subscribe to the Video then subscribe to the Page if you liked The Video from Dr to Look Pyaar President and Be Appointed Complete Detail The Question is Did for Its OK gold water every particular slot dutiable means set for that particular and number of tourists from the top fatty acid total number of the best tourist destination from the first flight mode person to person i india se twerking dance including da loot ok bihar greeting for millisecond Hand Price and 63.22 Circular SIM Solution Hand Price and 63.22 Circular SIM Solution Hand Price and 63.22 Circular SIM Solution and Told to Give Sake Mil 100 Don't Worry About This Time is the Mission Subscribe Button Comment Subscribe subscribe The Channel and tap on [Praise] [Praise] [Praise] Kar Do Ajay Ko Kar Do Hua Hai
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
55
hello everyone welcome back to sudokoda this is raveena and today we're gonna solve problem number 55 that is Jump game so let's start by reading the problem statement it says that you are given an integer array nums you are initially positioned at an arrays first index and each element in the array represents a maximum jump length at that position return true if you can reach the last index false otherwise and we have a example here so first let's try to understand what the problem needs us needs from us okay so let's go to the notepad so what the problem is saying that we have an array and then we have some elements in it and whatever the value whatever the element inside that array is how maximum can be jump so basically if this is 3 that means that I can jump at one with length 2 and then length 3. we can only jump in the right direction so if you are here say if you are at 2 then you can jump two times you can jump with length one and length 2. if you are suppose here that means that you but you don't have anything you can jump zero of zero length that means you stay here so that is what the problem is uh we can actually solve this problem using you know backtracking or greedy approach I'm gonna just walk you through the backtracking approach and then tell you why we are not doing it and then actually implement the greeting approach with you so let's start uh I'm going to just write this down again so what's going to happen is with backtracking we are going to so it's look gonna look something like this we have index 0 1 2 3 and 4. so these are my indexes uh let me actually do this in a different color so 0 1 2 3 and 4. I'm gonna start with my index 0 at the top and then see what is my value at 0 it's 3 and so that means that I can have three parts in here I can go from three to two I can go from three to one and then I can go from 3 to 0. so for that I'm going to create three branches it's going to be index 1 index 2 and index 3. once I do that I'll be like okay I have now three other branches let me explore them so I come here it with my first branch and I see what do I have here I have two and what can I explore with that so that I have two length right so I can go from here to index 2 otherwise I can go to index three I have two steps so I'm gonna do that I'm gonna explore it with index 2 and then I can go to index 3. all right let's see how we can expand the element of the index two okay so right now I'm here this is my index 2. I check okay I have one in here so that means the maximum I can go is one so I'm gonna go through one so what is that index that is index three so I come here I get index 3. I go in and look at my third index now I just I'm just doing breadth first search you know just going through each and every level and all the elements and just expanding it so I come here I come to three I'm like okay how what value do I have here I have 0 that means that I cannot go anywhere from here that means that has come to an halt so this is actually a dead end that means we cannot go any farther from three all right I come back I come here I see another three which is right here if I try and recollect three was not three was a dead end so this also becomes a dead end I come back I'm gonna explore this 2 right here the two index so I am here which is two this is two index so the value is one that means I can go one level to the right and so I am going to write that down I am going to write 3. I come to this 3 here and I see that oh it's actually a dead end we already know that from a first scenario so this becomes a denim I come back to the last one and this is also a dead end so you see there is no way for us to reach the last element and that is why it's gonna return false now this is the backtracking approach and this is going to repeat for each and every index remember that so for example we started with 0 for the next one we are going to increment our counter and we are going to start from 1. so it's going to happen for each and every element as the root and it's going to calculate that tree the time complexity of this is actually n raised to n because there are n possibilities of the tree and there are n elements so that's why it's n raised to n you can somehow optimize it by using memorization now what you can do is if you look at it you will see that 2 is been calculated here and then 2 is again calculated here so that means that when I calculated 2 I could have you know just stored it somewhere so I could say something like you know the two index at two index the value is actually false because that leads to a dead end and then when I come across 2 so when I come across here I'll be like oh I already know the value of 2 from the memoist point so I just update that so I don't need to calculate this part so you can save on Save on some complexity some time complexity and that time complexity is actually going to be increased too now that is the backtracking with memoization what we are going to do today a greedy approach and that greedy approach is going to give us a linear time so let's see how we will be approaching that for the greedy approach we are going to check how far right can we go so that means that for example I'm gonna just tweak this one I'm gonna take another example same example but I'm just gonna add additional element here so let's see for if I start at 3 the farthest I can go is really you know let me write down the indexes as well so 0 1 2 3 4 and 5. okay if I'm starting at 3 how far can I go I can go to you know my index is 0 I am at 3 so 0 plus 3 is 3 I can go here I can go three steps if I start from 2 how farther can I go I can still go to zero remember one and two if I start from 1 it's gonna also take me to 0. and you see the 0 is actually a dead end for us it doesn't really matter if you are calculating if you are in your Loop in your eye Loop and you reach here if you reach at one you'll be like oh yeah I'm just one step away from four but it doesn't really matter because your cursor couldn't reach at zero it could not move past zero because 0 doesn't have any jump length and because 0 doesn't have any jump length it cannot jump from zero to one so there is a bridge a breakage right here so that is the reason we are gonna calculate a farthest right that is going to see how far can we move if we start from a certain point and then we are gonna keep track of our I simultaneously and then we are gonna check if my furthest right is actually less than my I or my I is greater than my father's right then we return false then we say that we cannot reach the end and this is the perfect example of it so let's see uh let's go through the steps and see how it's gonna pan out okay so first thing is I'm going to have my father's right so I'm going to have my FR for this right here and I'm going to have my I here first I check is my I greater than my father's right not right now my I is 0 and my for this right is also 0 greater than 0 no okay I go to the next equation I then check is what is my father's right gonna be then what is going to be the maximum it's gonna be here it's going to be actually I plus X so it's gonna come to this place which is 0. all right and then I update my father right now I go to my next element in my eye I am right here I'll check is my I greater than my father right no it's not that means I can still calculate things now I'll check what is my father right gonna be my father right is gonna be my Max of the farther right that I already have or my I plus X so the farther right I already have is three my father X my I plus X is gonna be really one plus two which is 3 and that is also gonna point to zero so my father right actually stays the same now my I increments again my eye is here I'll check if is my I greater than my father right no it is not okay now how many ways can I reach forward its length is 1 so I can go one length forward that is again three and I'm gonna check what is my maximum of further right versus I plus X my I plus s is actually three and my father right is also 3 so it doesn't matter my father right stays 3. I increment my I now check is my I greater than my father right no it is not both three I am going to calculate my farther right again my father right is going to be maximum of father right and my I plus X my X is actually these elements keep in mind that so it's gonna be three plus zero it's again 3. so my father write again comes out to be 3. since it's already 3 it's not gonna get updated and then we move our eye pointer here once we come here we check is my eye actually greater than my father right yes it is then we return false and this is really important to understand why do we have that condition it took me a while to understand why do we need that condition it's because if you cannot see you have to have jumps to reach a particular step you to reach the end and if you have a break issue it doesn't matter if you have links right here and you have links on the left you are never going to reach the end and that is the reason why you need to have a father right with you now let's see how we can turn this into code it's actually really simple so let me open my editor all right so the first thing was our farthest right so my farthest right is gonna be zero it's really confusing to say farthest right every time and then I am going to write a for Loop so my for Loop is going to be for every I and X in is in enumerate nums that means that it's gonna read for every index and every element in the array and the first thing was to check is my I greater than my farthest which I misspelled farthest right if that is true then you return false that means that we are we have a breakage right and otherwise what you are going to do is you are going to initialize your file this right and get the maximum what is going to be your maximum my maximum is going to be Max of my farthest right or my I plus X once I have that you know if the whole Loop executes properly then in the end you just return true let's see if this runs okay let's submit all right so this solution is accepted now let's talk about the space and time complexity of this algorithm so the time complexity of this algorithm is you as you can see is linear we are going through each and every element just once so the time complexity of this algorithm is O of n whereas the space complexity of this algorithm is constant because we are using just one variable that also to store a integer so that's why the space complexity of this algorithm is going to be constant and the time complexity is going to be o of n so I hope you like this video I hope you like this solution if you like my videos please give it a thumbs up comment below if you want me to solve any other questions please let me know in the comments below I am also on Discord so feel free to connect with me there if you have any questions or you want to connect I will be available there and the code for this is going to be on my GitHub repository and the link I will mention in the description below so thank you so much for watching and you have a nice day I will see you next time thank you so much
Jump Game
jump-game
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** true **Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[3,2,1,0,4\] **Output:** false **Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 105`
null
Array,Dynamic Programming,Greedy
Medium
45,1428,2001
1,822
okay lead code number 1822 sine of the product of an array the task is pretty much what the title says we have to find the sum of the product negative minus one positive one and then if it is zero we should return to zero the curious thing about this is that when i was checking the acceptance rate it has 60 and that is pretty much considered as like averagely difficult so we'll find out why it is so okay we can calculate the sum on the way i think the zero can be checked separately so if it's a zero the answer is definitely going to be zero and let's say if it is a negative i can just multiply it with -1 just multiply it with -1 just multiply it with -1 and continue otherwise don't do anything so and return the sign so let's see why it had an acceptance rate of 65 yeah perhaps this was the reason i didn't initialize it but i still doubt it and i didn't submit so that doesn't count as an acceptance i suppose okay so it worked so we're done
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516