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,814 |
hello hi guys good morning welcome back to the new videoi I hope that you guys are doing good just let me know how you guys are doing uh in this video Problem count nice pairs in an array so it has been asked by Uber Navi and it's a good frequency in the last one two years let's see what the problem says is exactly see we should remember the trick what these kind of problems use so that we don't think of anything else and we just start solving it all together we have seen such kind of problems a lot in the live contest discussions and also in the previous daily contest daily problems so let's see uh it just says that we are having an AR nums uh that consist of non- negative integers which let's and non- negative integers which let's and non- negative integers which let's and let us find the reverse of X as the reverse of the non digit X so basically reverse of a number is just the reverse of that and if you don't know then there are two ways to find a reverse if I have a number 1 2 3 and I want to find the reverse I can convert this to a string 1 2 3 simply use STL to reverse this string 1 23 and then I can just convert that STL back to a number a 3 to1 that is one way other way is that I just iterate on all of its like the entire number I'll at any point time I'll just get the last digit by just using a modulo then I will know that I've have got the last digit and I will just divide the number by 10 to get the remaining part I'll at every step I'll keep on multiplying this first part by 10 which is the remainder by 10 so I have got the answer So Far So my answer so far is zero I'm building my answer which is the reverse I'm building my reverse value let's say the reverse value I'm building right now so for sure the reverse value will be a zero right now so it will be 0 into 10 + 3 and now so it will be 0 into 10 + 3 and now so it will be 0 into 10 + 3 and still I need to evaluate this remaining part so it will be right now three only then next time when this part needs to be evaluated string like still I'll get the remainder I'll get the remaining part this is the answer so far which is the reverse value so far it is three now I will first do the same thing multiply this by 10 and then add the remainder cool I'll just do a 3 into 10 + 2 I get a + 2 I get a + 2 I get a 32 again this will be a new reverse value for us so last will remain this I will just find the remainder again it is a one remaining value is a zero so this is a remainder remaining Valu is a zero again I'll do the same thing reverse value into 10 plus this remainder which you have got I'll get a 3 2 1 so this is how you just simply get a reverse simply get the remainder multiply that by 10 at each step simply get the remainder multiply that number by 10 get the reverse value so basically you multiply the reverse value by 10 and then adding a remainder in that cool so that is how you can find the remainder this uh you can find the reverse these are two methods to do that now okay then let's say you know that part also so just says as the reverse of the remember a pair of indices I and J is nice if it satisfies all of the following conditions firstly that it should not be equal which means I is less than J and also nums of I plus reverse of nums of J is equal to nums of J plus reverse of nums of I so firstly now I just have to return all such nice pairs which follow these conditions that is one thing so one thing for sure in this is that what this thing indicates R and this thing only indicates that I is less than J it just indicates that the pairs are unique which means if I count if I have let's say an AR like this of five elements if I have I here and J here I should count this pair only once this thing is saying that thing if let's say if I would have true condition on inj so I can I could have counted that pair twice also so yeah this condition only says that his thing when I is less than J only count this as once so okay uh one thing this says is Count this as once but my ultimate Target was to find the pair itself how to find the pair can I just infer something from this one way is I'll just go on finding all the pairs which is I go on all the IGS and go on all the I PS is just o of n square and O of n Square would not work for sure for us so what we can do in this such cases we have already seen whenever some condition is given on I and J just separate those conditions and get I different and J different so what we will do with this condition is I'll just get I different and J different so I'll write the same thing as nums of I minus reverse of nums of I should be equal to or like equal to nums of J minus reverse of nums of J so this is my condition now how I knew that I want to you will see that it's a common trick just to get variables in just one term now why is this useful we will see it's only useful so that you only have to work on one variable now you don't have to go on J now you can only start working on the I itself just make sure that you take the ones which are having the equal value so now I can just consider this as one value let's say I consider this as one value let's say Val now my main target is to find all such pairs which have the same value how I can do that I can simply go and let's say for this example I take the 42 now I'll just take okay uh 42 11 1 97 I'll just simply do a reverse of this I'll just do a reverse of this okay it's the actual number which is let's say num I'll do a reverse of num and I'll get a 24 I get a 11 I get a 1 I get a 79 right now I'll just do a quickly subtraction of this nums minus reverse I'll do a nums minus reverse and what I will get with this nums minus reverse is just simple like this nums minus reverse right so I have got this now this nums minus reverse just simply indicates this value Val now my main target was it's a simple problem now my main target was just to find all such pairs having the same Val how we do it as simple as that we can just simply keep on going in the left and I can just keep this map like keep this value frequency I can just infert this number as a Val I can keep this value frequency in my map okay so right now when I 18 I am looking for any number previous 18 I have found okay right now I have not found okay his contribution is zero right now cool I went on to him zero I again asking for any zero value I have found previously or not oh sorry I have not found any value previously okay again his contribution also zero but I'm also updating my map okay the frequency qu of 18 has been 1 the frequency of zero has been one I'm just updating frequency why it is useful because it will help me in future to say that okay for this number zero I'll firstly ask him zero bro have you find anyone like you previously he will say yeah bro I have found and there is one of the zeros so this indicates that for him for this particular zero his contribution will be one how one he can just pair up with the previous this index zero Ian what if it would have previously more zeros cool no worries if it would have been more zeros let's say three zeros would have been there 1 2 and three so his contribution would have been three how he can pair with him these three pairs he can make so his contribution is three so for sure his contribution right now will be one cool I just go ahead and for sure I just up a frequency also two so that in future anyone else comes in let's say zero comes in so he knows that he can make a pair with him and that's a simple prefix uh computation which we do that we just use prefix to actually find in the answer for the current number and it was only uh like possible when we have converted it to into just a one variable I so that I can just compute that value for the specific I itself now I have the value for the specific I itself right that's the reason now I just again we'll go on to 18 now I just ask him bro uh what's the Frequency you have got have you got other 18 previously also yeah bro I have got 118 so this will indicate I can make one pair with the 18 previous 18 I can make one pair with the previous 18 so that I will make his contribution of answer will also be one and I update the frequency also so his contribution was one his was one ultimately the final answer is two as you will see the final answer is two so that's how you can just simply convert your first you have your uh this nums you can find the reverse of nums you will compute this value which is nums reverse of nums so that you have got all the values with you then you can just go on from left to right and just keep on track ultimately there's another way also just to find the frequency let's say the frequency of these zeros are let's say n so ultimately the number of unique pairs unique as in the one satisf the condition that I is L than J will be nothing but n into for the N values it will be n into nus 1 by2 that's one way but it is much more complex to firstly find out and thing of so although like it's a very simple proof that if you have n values which are same the number of unique pairs will be n 1 by 2 how for just n for like for every let's say if you have these three values for each value you can just choose other two values so for n values you can choose other n minus one values but let's say for this value you choose this small like other value now again for this value you choose this value so it's a pair which is counted twice that's the reason you just do a n into nus 1 by 2 that is one way to solve it also but we just prefer this common standard prefix way to solve it because it's a very standard technique both are a standard technique please remember this fact cool ultimately we have just got the answer now we can just simply keep on adding the frequency which we have found earlier of a number in the answer and also keep on updating the frequency simultaneously let's quickly code this up it will be pretty simple um so firstly as we saw that we need to find the reverse of a number so I can just say that I just find the reverse of a number and while I have the number left because ultimately I'm just concerned about the last digit and I just get the last digit which is nothing but num mod 10 now I have got the last digit also so just simply uh do one thing that you have your Val multiply the existing Val by 10 add this last digit in your Val uh value and that is done for you now also you have consumed the last digit so just remove that last digit ultimately I can just return my value which is the reverse value now I can just simply do one thing I can just simply keep on going in my answer in my nums but for that I just knew that I need to update I need to keep track of the frequency of nums minus reverse of nums so uh firstly I just also want the answer then I can just go on inside my entire element so for auto element in my nums I need to find uh this value as I showed you this Val will be nothing but element minus reverse of element and I'll just keep track with that frequency so I'll just do a answer uh but yeah here also we need to have a modulo so just do one thing that uh take a hash Define mod 1 2 3 4 5 6 7 8 9 seven then it will actually help us to do a modul with the Val now I have added my Val if there is and also for sure uh it's not simply Val it's just the frequency of the number Val right now I just update the frequency also for that Val and simply return your answer with the mod value hope this works uh if you have no types and stuff yeah so yeah thank you so for watching see bye-bye
|
Count Nice Pairs in an Array
|
jump-game-vi
|
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])`
Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[42,11,1,97\]
**Output:** 2
**Explanation:** The two pairs are:
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
**Example 2:**
**Input:** nums = \[13,10,35,24,76\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
|
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Medium
|
239,2001
|
2 |
hello welcome to my channel i'm here to do my angelico challenge and today we have lit code two add two numbers you are given two non-empty linked lists you are given two non-empty linked lists you are given two non-empty linked lists representing two non-negative representing two non-negative representing two non-negative integers uh the digits are stored in reverse order and each of the nodes contain a single digit add the two numbers and return the sum as linguist so you may assume two numbers do not contain any leading zero except the number zero itself so now you can see this example we have linked list right here another language here but actually what they are is reverse order so the first language looks like is an integer 342 next one is 465 and they just do the regular um regular uh addition and you see 807 but in the reverse linked list form so what's that mean is this linked list one always start with the beginning which is two and here the same as five what we can do is add this number together and sum up and store it in this new linked list that's for output so we have seven here but now we have four and six add up as becomes zero and we mod that total sum as equal to 10 then uh mod this sum to 10 so we have one as i carry on for next digit so now in this number at all this sum up and this carry-on so we become eight and this carry-on so we become eight and this carry-on so we become eight so that's the idea of this questions so let's take a look at the code now we have list node output i will just randomly make the nodes zero and another temporary pointer dummy pointed to the same output and like what we said we need a carry for it okay and then while let's see that we need to keep looping until um they all finish so if l1 is not equal to no then you have to keep looping uh and l2 is not equal to no or carry uh not equal to zero so if l1 is not equal to no now we add out one dot value at one dot value into the carry and l1 equal to l1 dot next so l1 will go to the next node right here now we have this put 2 to the carry and also put 5 to the carry so if l2 is not equal to null and we need to put that to the carry and l2 is equal to l2 dot next so l2 will go one step forward so now we have this two number capture to the carry and we check let's see so we can do dummy.next let's see so we can do dummy.next let's see so we can do dummy.next to a new node create a new note here okay so a dummy is right here so dummy 0 and dummy.next so dummy 0 and dummy.next so dummy 0 and dummy.next is right here we create this node that will put carry carries a total right now but we need to mod it with 10. so modded with 10 for example if the sum is 8 so marked with ten is eight but the sum is equal to ten the amount will be zero and then next step will carry is equal to carry divided by 10. so um this carry will divide by 10 and then have the carry become one for next step so we have a one carry on for next step if they the sum is more than 10 and after that dummy will move one step forward and that should be it this question so now we have output always point to the beginning we just i'll put the output down next so that's it for this question i believe okay let's see what's missing um oh okay i think the mistake is right here should be two okay run one more time submit one more time that's it for this question and if you have more questions please comment below and i will see you in the next video bye
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
289 |
all right so let's take a look at this problem called game of life according to wikipedia's article the game of life also known simply as life is a cellular atomic automaton devised by the british mathematician john horton conway in 1970 the board is made up of an m by n grid of cells where each cell has an initial state live represented by a one or dead represented by a zero each cell interacts with its eight neighbors horizontal vertical diagonal using the following four rules taken from the above wikipedia article i'll put this wikipedia article link in the description any live cell with fewer than two live neighbors dies as if caused by underpopulation any live cell with two or three live neighbors lives on to the next generation any live cell with more than three live neighbors dies as if by overpopulation and any dead cell with exactly three live neighbors becomes a live cell as if by reproduction the next state is created by applying the above rules simultaneously to every cell in the current state where births and deaths occur simultaneously given the current state of the m by a grid board return the next state so as you can see here uh it only cares about what the current state was not you know intermittent states the reason why they're saying simultaneously so as you're going from one part of the board to the next you're not looking at what the new state was to figure out um you know previous one so if i was on the second cell i'm looking at the original first cell value not its new value so now as an example here this particular live cell ended up dying by under population because it has fewer than uh two live neighbors and this particular cell that was dead ended up becoming a live cell because it had exactly three live neighbors so how might we go about solving a problem like this the naive approach would be probably to create a copy of the original array so that way you could reference the copied value and update your existing value because you're not returning a new array they're just expecting you to update the board uh so that grid board and its new values is what will be returned because the function is just updating in place but you need something to reference so creating copy would work but then your uh your basically your memory complexity would be that you're storing another copy of the grid so another m by m as far as space complexity so what could we do um you know it would also be m by n to go through the array twice or the grid rather so it's uh let's think about this more could we do an in-memory could we do an in-memory could we do an in-memory in memory would um would work how would it work well we have integers so we don't store only zeros and ones we could end up storing a value greater than or less than 10 so then our tens digit could store the value of what it currently uh currently is and then our single digit could store the number of alive neighbors it had and then we could just apply our rules after that so then that would be still 2 m by n which becomes m by n time complexity but our space complexity would be constant space because we are just using the existing board just changing the values and then iterating through it twice all right let's go ahead and write the code for that so uh while i equals zero i is less than board dot length i plus so in this case this will be allowing us to iterate from top to bottom we need to also iterate from left to right so uh we'll do j and board of i so this make sure that we at least take a valid uh row here and count how many columns it has and then j plus okay and we do know that we are going to end up iterating through twice so i can just copy this all right and then what are we doing uh the first time we're going to change the value so we'll just make an encode function to encode the value to something else and then we can just call the other final iteration update and then we start writing our functions here so avoid encode what is it going to take uh well let's pass it our board and then we also want to know what is the current uh i and j that we are looking at this tells us where we are in our board and then we need to start looking at the neighbors so we can actually go ahead and set this up here so we don't forget to come back to this later so board i j board and i and j in our update because we're just going to look at the values all over again but then determine what the new value should be so for encoding what are we doing um well we need to figure out how many neighbors were alive uh so we could store that in the singles digit and then how many uh and then what was the value itself was it alive or dead we're going to store that in the tens digit so let's keep track of that a live count of neighbors so first it's going to be zero and now we need to figure out how we're gonna look at the neighbors uh there's different ways to do this uh for me personally this is kind of the way that i prefer to look left right up down so we will have let's say we're going to go ahead and look at a row so we'll say row equals r so we're going to start at its first value which will be negative one this is so that way we can look at the row above it and then we also need to make sure that we stop after we look at the row below it so it's actually going to be less than or equal to or you could say less than two also okay but less than or equal to one and then i or sorry not i this is actually r so our row is less than or equal to one and then it's r plus okay so the same thing it's a little easier now because we can copy paste this and say the same thing but for our columns which we'll say is c okay so we have a way now to look at the previous row look at the previous column or look at the current column or the next column in the current row or the next row okay so now that we have that we want to make sure that we only look at uh valid values but let's go ahead and see where we are each time so what we're doing in this looping is we're figuring out which neighbor we're looking at so we'll say that neighbors row equals the i value plus the row value so if we were at i is one uh is one j is one we would be here and so then if we add the rows and row is negative one we're going to be looking at this uh row up here actually and then if we look at the column as negative one we'll be looking at this value here so uh let's also get our column i'll go ahead and bump this back because it looks like the spacing wants to put me here so neighbor uh column equals and then our j is what we're using to keep track of our columns plus our uh column negative one zero or one okay now we need to make sure that we're only getting valid values and we're not running off the end of the array so we need to make sure that our row is greater than or equal to zero and it is also less than our board dot length additionally we also want to do the same thing but for the column so neighbor column needs to be greater than or equal to zero and we want that column to not run off the end of the board so it must be less than board and we know there's at least one row so we say board of zero dot length okay so we're avoiding our index out of bounds issues and now we will go ahead and start looking at the value so we know we're not going to run off the edge let's just go ahead and get the value of the neighbor so the neighbor value equals board neighbor row neighbor call okay now when we're here's where it gets tricky we know that as we're going from the top to the bottom we started changing some of these values so if it's a value that we've changed we're going to need to change it back um at least in our temporary variable neighbor value here so that way um that way you know we're looking at either a uh a one or a zero so uh let's see what would signify that we're looking at a previous value so if uh let's see if the row uh well actually yeah if the row is equal to negative one so if we're currently saying go up negative one then uh we're on this row that is definitely a previous one or and we only want to count this particular column the one that's to the left not the one to the right or below and to the left so uh or if the row is our current row and our column we're looking at is the previous column there we go okay so if that is the case now we need to update our neighbor value equals neighbor value divided by 10 so that gets the tens digit because we know we've already potentially made it larger than 10 if it was uh less than 10 this will just give us zero all right and now what we're doing is we're trying to figure out um the count of the neighbors that are live so if the neighbor value uh equals one uh then we're going to add the live count so live count plus but there's a problem here we also don't want to count the current value we're looking at so let's also make sure we don't do that so we'll say and not so our row should not be equal to zero when our uh column is also equal to zero this means that we've not modified that uh neighbor value at all we're not looking at a neighbor we're looking at our current cell so if the neighbor value is one but we're also not looking at the current cell bump that alive count okay so after we have done that uh we've gone through the loop to look at all of the neighbors all right so now we have that alive count and what we do from here is we update that value to the encoded value how would we update to the encoded value okay so let's look at what our current value is it is board i of j equals and now we need to update the tens digit in the single digit so uh board i of j times 10 reason being that if it's a 0 or a 1 we're changing it to 10 or 0 this is so that way we can store a 1 as a 10 and then we're just adding our live count all right that's it for that so we now have a way to change uh essentially if it was this value here which is a 1 to an 11 because we multiplied the 1 by 10 and now it is a 10 and then we added the live count for the neighbor which is only a one now we have 11 here okay that looks good so now the next thing we need to do is just write our update function so void update and we're going to also pass in the board again and we want to know where we are in our for loops okay so now that we are at this point what are we doing we're applying the rules so to apply the rules what do we need to know if the cell is live or dead and how many neighbors it has uh so let's go ahead and keep track of how many uh neighbor count so this is how many of the neighbors were alive and we stored that in a single digit so what we're going to do is board of i j and then we'll do uh mod 10 and then i can store this in an integer or i could just make this a boolean so we'll say is it alive and that would be board of i j divided by 10 so that gets the tens digit and is that equal to one okay so now we know was it alive or not and how many neighbors it had that excuse me that were alive okay so at this point let's just start applying the rules all right so if it is live let's take care of cases where it's alive and it dies so that would be case one and case three so if is alive and uh let's see neighbor count uh if it's fewer than two so less than two or the neighbor count is more than three so we'll say neighbor count is greater than three this is a case where uh the board will be updated to zero because it dies okay next let's go let's cover another one so else if uh let's say now we have condition two and four so let's handle uh condition two real quick so if it is alive and it has two or three neighbors it's this so not less than but instead it is exactly two or three then it is going to be alive now all right and then we did not cover case uh where it is dead so that'd be case for so if it is not alive else if not is live and it has exactly three neighbors for this particular case it is alive again instead of dead and any other case we just want to put the value back to whatever it was so um we need to get our we have our tens digit of what it was or not it just is live so we will say that it equals and then uh we could use a ternary here is live so if it was alive we want the value one if it was not alive we want the value zero and that should be it so we have covered all four rules our uh catch case if it does not apply to any of these rules and we can go ahead and submit great so our solution was accepted uh apparently it's faster than 100 of the solutions here and as i said before when you're using this solution you are using a big o of one con so it's constant space because you're using the existing board that is there you're just changing the values in it and you're iterating through the board twice which has a size of m by n so your big o time complexity is just m by n because 2 and by n just simplifies to m by n all right that is it for this problem if you have any questions let me know in the comments below please take a moment to like and subscribe for future content you
|
Game of Life
|
game-of-life
|
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. "
The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_.
**Example 1:**
**Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\]
**Example 2:**
**Input:** board = \[\[1,1\],\[1,0\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 25`
* `board[i][j]` is `0` or `1`.
**Follow up:**
* Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
* In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
| null |
Array,Matrix,Simulation
|
Medium
|
73
|
706 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem design hashmap basically we want to implement the main operations of a hashmap which includes putting or inserting a value using some key we can map it to some value also we should be able to retrieve elements that are already stored so given a key we should be able to retrieve that element and lastly we should be able to remove elements based on some key value now of course we can't just use a built-in hash course we can't just use a built-in hash course we can't just use a built-in hash map so we have to implement our own there's a restriction that we're going to be using which is that on this hash map we will have at most a thousand operations that are done that's just based off like the test cases so we probably won't need to store more than a thousand elements but other than that we'll still be implementing the main operations from scratch so what is a hash map well generally we want to be able to map any arbitrary key in this case the key value is just going to be an integer so that simplifies things for us even more but usually we want to map a key to some value and we want to do it as quickly as we can on average most hash Maps will implement this in constant time and we also want to be able to retrieve elements doing the same thing the easiest way to implement hashmaps and most of the time this is how they're implemented with an array and we know arrays just generally have an index and a value but we will be using the index instead as the key value now normally what you want to do with that key value is map it to some index within our array in our array we're going to have about a thousand elements so the valid indices are going to be starting at zero and probably going up until nine so how can we take a key value in this case the key value is an integer and then map it to an integer between 0 and 9 99 well the easiest way is to take that key value let's say it's a hundred and mod it by a thousand so modding by a thousand will always give us a value between zero and nine because with a hundred modded by a thousand we'll just get a hundred so any value less than a thousand will just get that value but what happens when we start getting up until that value well a thousand modded by a thousand is just going to be zero a Thousand and One modded by a thousand is going to be one and so on so every value is guaranteed to be between 0 and 999 so we'll have a way to map the key somewhere here now another issue that can happen with hashmaps is this concept of collisions so what happens if multiple values are mapped to the same index like we talked about we had a hundred modding it by a thousand will give us a hundred what about 11 100 modded by a thousand that will also give us 100 so multiple values will be stored at the same key location let's say the key is a hundred so multiple values could be here how are we going to handle that well there's multiple ways one is open addressing which we won't talk about right now because it's a bit more complicated than the one I'm going to show you which is called chaining is pretty straightforward because just as the name implies if we have multiple values here let's just say the first value we were inserting was a one and now we want another value with a different key is going to be a value too we would just take those values and add them into a chain so we can store multiple values with a single key I guess it's misleading to say we have multiple values stored with the same key it's just that those multiple keys will map to the same index they will be different keys so I guess a better way to illustrate this would be that let's say these are the two insertions that we did so a key value of 100 will be mapped to one key value with 1100 will be mapped to two we know both of these Keys when we mod them by a thousand we are going to get the same index so over here they'll both be mapped to index 100. now when we actually store the value we will store them in that linked list that we were showing earlier so we'll store the key value 100 and we'll store the value itself which is one so both of those will be stored in that linked list node that we were talking about and if we inserted another value here and we saw that well there's already a node stored here doesn't matter we just insert a new node and connect them via like a pointer just like you would with linked lists the value in this case or the key is going to be 1100 in this case and the value is going to be 2. so we store the keys in the nodes because we don't want to lose any information sure the 100 here matches the 100 over here but the index here doesn't necessarily mean it's going to be the same as the key like in this case we have an 1100 stored over here so we don't want to lose like the original key that we were using that's why we add that to the node we don't just rely on the index so we just showed the put operation so far but I bet you can tell how the get and remove operations are going to go so with get it's also going to be similar we're going to take whatever key that we're given so maybe it's 1100 we're going to mod it by a thousand so we're going to get the index which is a hundred then we're gonna go through that linked list until we find the key that we were looking for if it exists at all so we're looking for Eleven Hundred so we're going to keep going through this linked list until we find a node that has the key of 1100 which is this node over here so then we would return its value which is two now if we don't find a linked list node with the key that we're looking for then I believe we just return a fault value of negative one and lastly how would we remove a node well just some pointer manipulation which would mean we would go up until we reached the node so maybe this is the node that we want to remove so we'd go up until we reach the previous node and then we'd take its pointer and then set it to the next node so maybe we have three nodes in this case in that case we'd remove this pointer and then set it to the next node or maybe there's nothing over here in which case we'd set the next pointer equal to null and this node would basically be removed we could delete the memory that stores this node or we could not usually encoding interviews you don't really need to but that's how this would work now one last thing I want to mention notice how there's kind of an edge case here what if we were removing the first node well there's no previous pointer in front of that so it would be a little awkward we need additional conditions to be able to handle this case so an easy work around is to initialize every linked list here with like a dummy node so we'd have a dummy node that's starting here even though there's no nodes here we'd still have a dummy node here and we'd have a dummy node here that's pointing to this first real node that we have so if we wanted to remove this we'd just take the dummy node and set its next pointer equal to the next node which is over here so that's mainly it now technically the way we've written this hash map it's not going to be constant time in every case we could have a bunch of values that are inserted at the same index it is possible but on average chaining is pretty efficient and we know we're not going to have more than a thousand elements in our data structure so assuming that they're evenly distributed these operations should be pretty efficient so now let's code it up so the first thing I have here is my list node we know we're going to have a key value a real value and a next pointer to now get started on our hash map we know we're going to have an array I'm going to call it our map but it's technically an array and I'm going to just initialize it to be size of a thousand so for I in range a thousand we're going to initialize every index with a dummy node as I kind of mentioned earlier so we're going to create a list node for a thousand times and then that's what the array is going to be initialized with and that is pretty much it now for the put operation there's actually two cases we have to handle one is if we're inserting this key for the first time in that case we would create a new list node but if we're not then that means this key already exists and all we want to do is update the value of that key first what we want to do though is take the key and map it to the index so we decided that we were just going to take the key and mod it by a thousand aka the length of our hash map so this will give us the index and we're going to be needing this a few times actually so I think it's worth putting it in its own helper function so let's define one where we can hash some key value then we will return the hash of that key and we'll be needing it pretty much in all of these because this will tell us what index we should go to and once we have this index we want to start at the head of that linked list because we know it's going to map to some linked list so we're going to say in this map at this Index this is going to be the start of the linked list so I'm going to call it Cur we're going to take our current pointer and while it's non-null we are pointer and while it's non-null we are pointer and while it's non-null we are going to continue to Traverse this linked list so we're going to set the current pointer equal to current dot next but there's two cases remember one is that we find a node so if current dot key is equal to the key that we were given that means this node already exists this key already exists so we just want to update its value so current.val would be set to the new current.val would be set to the new current.val would be set to the new value that we were passed in and then we want to return immediately the second case is where we will reach the end of the linked list and at that point we want to insert a new linked list node at the end now the way our current Loop is coded up by the time we reach the end of the loop our current pointer will be equal to null but that's not where we want to end we want current to be pointing at the last node so instead of saying while current we say while current dot next remember that our current will start at the first node in the linked list which is going to be a dummy node so when we actually check these values we shouldn't say current dot key we should say current dot next dot key is equal to the key that we were passing then we would update current dot next dot value so now if we never find that key in our linked list and we reach the end of this then we know we can now insert a new list node so I'd create a new list node with the key that we were given and the value that we were given just like our Constructor is defined up above and we take this node and we'd say current dot next is null now because current.next is null that's why the loop current.next is null that's why the loop current.next is null that's why the loop terminated so we want to set current.next equal to this new list node current.next equal to this new list node current.next equal to this new list node and then we don't really need to return anything but now we can get started on our get method which will be pretty similar to this we just want to get the head of the linked list that this key maps to so we'll just go ahead and copy and paste this and what we'll be doing this time is while our current pointer is not null we're going to check if current dot key is equal to the key that we were passed in then we return current dot value otherwise we just take the pointer and set it to the next pointer now if we ever reach the end that means we didn't find the key that we were looking for in which case we can just return negative one that's the default value that we want to return and one minor change here we probably can go ahead and take this and set it equal to dot next because we don't need to start at the dummy node in this case we don't need to check the dummy nodes value so it makes sense to just start at the second node of that linked list lastly we have our remove method we're going to do the same thing that we did up here but we probably do need to start at the dummy node in this case because we're going to need to do some pointer manipulation so now we want to check if current is non-null and current dot next current is non-null and current dot next current is non-null and current dot next is non-null then we want to check if is non-null then we want to check if is non-null then we want to check if current dot next the next node's value or rather its key is equal to the key that we were given if it is that means this is the node that we're going to remove and then after we remove we can probably just go ahead and return how do we remove it and more importantly the reason I'm using current.next in this reason I'm using current.next in this reason I'm using current.next in this case is because we want our current pointer to stop at the node right before we delete a node so we want to stop at the node prior to the one that we're deleting so then we can say current dot next is going to be equal to current dot next so we're just setting its next pointer and skipping a node the node that we're skipping is the one that we want to delete and this is basically us performing that deletion we don't really need to delete the memory it doesn't really make a difference most of the time it doesn't make a difference on leak code and it usually doesn't make a difference in coding interviews so I won't do that but lastly here we need to set our current pointer equal to current dot next so either will reach the end of the loop in which case we won't remove anything or we will remove the node and then immediately return so this is pretty much the entire code it's not too bad luckily we didn't need to handle the resize method usually hash maps are growing and as they grow we need to double the capacity every time they exceed the current capacity or exceed some threshold but in this case we don't really need to do that so I'll go ahead and run the code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of check out neatcode.io it has a ton of check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Design HashMap
|
design-hashmap
|
Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`.
* `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`.
**Example 1:**
**Input**
\[ "MyHashMap ", "put ", "put ", "get ", "get ", "put ", "get ", "remove ", "get "\]
\[\[\], \[1, 1\], \[2, 2\], \[1\], \[3\], \[2, 1\], \[2\], \[2\], \[2\]\]
**Output**
\[null, null, null, 1, -1, null, 1, null, -1\]
**Explanation**
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now \[\[1,1\]\]
myHashMap.put(2, 2); // The map is now \[\[1,1\], \[2,2\]\]
myHashMap.get(1); // return 1, The map is now \[\[1,1\], \[2,2\]\]
myHashMap.get(3); // return -1 (i.e., not found), The map is now \[\[1,1\], \[2,2\]\]
myHashMap.put(2, 1); // The map is now \[\[1,1\], \[2,1\]\] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now \[\[1,1\], \[2,1\]\]
myHashMap.remove(2); // remove the mapping for 2, The map is now \[\[1,1\]\]
myHashMap.get(2); // return -1 (i.e., not found), The map is now \[\[1,1\]\]
**Constraints:**
* `0 <= key, value <= 106`
* At most `104` calls will be made to `put`, `get`, and `remove`.
| null | null |
Easy
| null |
513 |
hey guys welcome back to my channel and in today's video we are going to solve one more lead code question that is question number 513 find bottom left three value so this is a medium level question and it has been asked by these many companies Amazon and Microsoft in last two years so let's see what this question is all about so in this question we are given a binary tree and we have to return the leftmost value in the last draw of the tree so if we see this example that is given so this is 213 and in this Tre the leftmost value in last row is one if we see another example so in this example we can see this is slightly bigger tree and in this if we see last row and leftmost value then it's seven right so this is what we have to find out so let's see how we can solve it using this example so in this example we can see that there are so many levels and the last row consist of only one element that is eight so eight will be the answer that we will be returning so how we can Traverse this whole tree and reach this leftmost value so for that what I will be doing I will be firstly coming up to this place and I will be checking that here at this point our depth is zero and the leftmost value is 1 right now what I will do I will go to next level on this level I will increase my depth right I will increase my depth and I will check the leftmost value so this is the leftmost value at this depth then again I will proceed and I will see if the depth is greater than the previous one so right this is greater and there is a value so what I will do I am at that I am at level two and the leftmost value Val will also get updated again what I will do I will go to Next Level I will go to next level and at this level as well I will do the same thing I will check if the depth is greater than the previous one that I stored or I observe so I will again update the depth and the value in that level so at this level the greatest value is six so what I will do I will come I will simply update it here again I will do the same thing I will go one level further and I will check if the level is getting updated then update the value so this is simply what I did but if From cod's perspective I have to look at this approach what I'm doing is I'm traversing this tree and I'm traversing its nodes so left and right node I will be checking both the sides of the tree because we don't know at the last row on which sub tree we are going to get the leftmost value right so for that we will be traversing the whole tree and we will be traversing all the nodes as well so parall I will be parall I'll be calling the left child as well as right child and I and in that manner we will be traversing this whole tree so for this approach what we did DFS right we proceeded with DFS and we updated the leftmost value depending if the depth is getting increased and how we are identifying that the depth is getting increased firstly we will firstly we'll reach a node we'll check if fine if this node is having a value then simply check our initialized depth and leftmost value so at starting what we can do we can keep our depth as minus1 and leftmost value as zero so we will initialize our max depth and left most leftmost value with zero after that we will start traversing from root so root is having a value so we will firstly check the level is zero here level is zero so we will update our Max uh we will update our uh depth first so it will become zero and then we will update the value with the leftmost value so this will become the value the current value will become the value because if the depth is getting increased then only we are updating the value right every time we did that if the depth is same we are not going to update the value so let me just clean this board and we will go through that algorithm which will help you to understand this whole procedure even better because I guess till now you all must be bugged with this whole explanation so I will try to make it a bit simple so what we are doing is we are doing DFS like we can solve this question with BFS as well but for this video we will concentrate on DFS and maybe in some other video I will let you know how to do it but uh at the end both the approaches are of same time and space complexity so we can focus on any one for this video so for now we can focus on DFS so we will start performing DFS on this tree for all the noes we are going to travel all the uh nodes or we are going to visit all the nodes but we are going to update our max depth and leftmost value only when the depth is getting updated so what I'm trying to say is firstly we know what we need to focus on we need to reach the depth last depth or the last level of the tree so what we can say let's define a level equals to minus one because right now we hadn't started traversing right so for now we can initialize it with minus one secondly once we had defined the level after this we need to find the leftmost value so leftmost value for now will be zero so this is how we initialize these two variables now what I'm saying is let's start performing DFS on this tree so we will come to this place this is the root at this place the level is zero the depth is zero so what we will do we will check if depth is greater than level if this is true then what I'm saying update our value so value will become the value of the node right node's value and this is how we are going to update it so at this place right now we know that depth is zero which is greater than minus one so we will update our depth or level so it will become zero and the value will be equivalent to the value of this node so it will become one now what I'm saying simultaneously go for both the children so we will call A cursive DFS on left child and right child again we will do the same thing for both of them so firstly we will come to this place we will check if the depth is greater than the one that we already stored we updated our variables right so at this place we will check the level so level is one here which is greater than zero so what we will do we will again update the level it will become one and as we are updating in level so we are going to upgrate the value as well so it will become two then when we are checking for three what will happen here we will come and we will check is depth greater than the one that we are already having so it will go to this variable level variable and check so it is not greater it is equivalent so what we will do we will leave it as it is so in this manner we are maintaining the leftmost value of that level in the back value variable right so again I will so again we will do the same thing we will proceed and do DFS on other sub trees so here again same thing happen is level greater than the one that is already stored already present so yes it is greater so we will update it to two and this will be updated to 4 then we will go to this place level is equivalent so we are not going to do anything then we are going to go to this nodes these nodes and when we reach here what we will do the same thing we will check if D is greater than L then simply update it so this will become three and six and for seven it will check and it will do nothing because depth is same then again we will do the same thing proceed further and come to this last level and again check the same thing level is four so we will update it and update the value and at last we are going to return this value so this is how we are going to perform DFS and this is the simple condition with which we are maintaining the leftmost value so now I guess this is better than the previous explanation things must be way more understandable for you all so let's Now quickly code the solution but before that uh let me just tell you what's the time and space complexity of this approaches so time and space complexity of this approach will be biger of n both will be bigger of n because um time complexity is bigger of an as we are visiting each and every node right because we don't know uh at the end which sub tree is going to have the last Leaf node so for that reason we are traversing each and every level and visiting every node and that's why time complexity is bigger of N and space complexity is bigger of n because we are calling DFS recursively for every node for every child node right so for that there will be a call stack or yeah recursive call stack and in worst case scenario if the tree is unbalanced and it's in this shape then in that case the uh then the space complexity will be equivalent to number of nodes rather than equivalent to number of levels so that's the reason why we are having space complexity biger of n bigger of n so now let's quickly code this solution and we are again going to solve this in two programming languages so firstly let's define all the variables that we discussed that firstly we need Max uh max depth so we are using self here because we will be accessing these variables out of this function from our DFS function that's why I'm using self or you can even pass if you want those variables but this is way more easier so that's why I'm defining the max depth and uh it will be GR into minus one firstly then leftmost left this also has to be in the same format so I used it leftmost value will be equivalent to zero and once these two variables are done what we will do we will call DFS and inside it this will be self. DFS and inside this what we are going to pass our root that is the node and depth so the starting depth will be zero and after this once this DFS is been performed what we will be returning the leftmost value so here we will be returning self dot leftmost value so this is for this function now we are calling DFS function so let's define that as well TFS and firstly it will have self then node and depth and inside this what we will check firstly check if it's node this node is having value or not if not then simply return and if depth is greater than self do Max step in that case what we were doing we were updating max depth with depth and self do leftmost value with node do value that's it and after this what we were doing we were calling the DFS function for node do left and depth will be + one because we are changing the be + one because we are changing the be + one because we are changing the level right we are going one level further so same thing we will do for right node as well and at the end we will add a return statement and that's it this was the whole code now let's check if I hadn't made any mistake then this should work and yeah this is accepted so let's quickly code Ruby solution as well in Ruby as well we are going to do the same thing firstly we will define those variables that is max depth so this at the rate in Ruby is going to act as the self that we use in Python so this is for accessing the class instance so this will variable will be accessible after out of this uh function as well so now what we will do is we will assign minus1 and leftmost value today why my hands are crippling so after this what we were doing we were calling that DFS function so DFS and inside this we were passing root and depth will be zero for root and rather than DFS it became dep and after this what we were doing return at the rate leftmost value so this was for this function out of this function we will Define our DFS function which will accept node n depth and then inside this function we are checking return unless node so this is checking whether node is having a value or not if it is having a value then check if depth is greater than at the rate max depth in that case inside this if condition update Max step with depth and leftmost value with node do Val and then outside of this if condition again call DFS for node do left comma depth + one do the same thing for comma depth + one do the same thing for comma depth + one do the same thing for WR node do write and depth + write and depth + write and depth + one and return now let's quickly run and check this is also going to be submitted yeah so this is also working and it is being submitted so these were the two solutions and the whole explanation and I hope this video was helpful for you all and if it was then don't forget to like share and subscribe my channel and I will soon come up with more such questions till then keep messing with algorithms and thanks for watching
|
Find Bottom Left Tree Value
|
find-bottom-left-tree-value
|
Given the `root` of a binary tree, return the leftmost value in the last row of the tree.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,2,3,4,null,5,6,null,null,7\]
**Output:** 7
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
338 |
hey guys welcome back to your channel today we're going to start with code 338 counting bits okay it's a easy problem but to be honest it was kind of tricky for me to kind of figure out how to solve it but it says easy so we're just gonna go with whatever they say okay so feel free to pause video just to read through what the problem is asking why find the examples more descriptive okay so given n equals two so we wanna create an array of two okay of zero the zero index one two where each element in the array is the number of ones in the binary implementation of that so again zero in binary just zero right there's no one in there one is just zero one right in binary there's one in there two is just zero one zero okay there's one in there so it's just the number of ones in there okay so first i'm not gonna go through this but again zero this is there's none three there's two four that's one five is this okay so that's a straightforward way to do it this is using a built-in this is using a built-in this is using a built-in python function from the collections module called counter so first i'll create a variable called results so let me go to empty matrix okay then i'm going to iterate for i in range um what range and plus one and i'm doing n plus one because the range operator is exclusive of the upper bound so this is just going to go from zero to n it's not going to go to n plus one because it's exclusive of the upper bound okay so this is what i wanted i want to append to result so i say result dot append now what do i want to append okay i want to use the counter this is a method provided by the collections module of python okay binary okay and so i'm converting n to binary that's what this bean n is doing okay converting him to binary then i want to count him so what counter does is it returns a dictionary key value pairs of each element of whatever string you pass to him or whatever list you pass to him and the number of recurrence so the key is the elements the values and number of times you occur so i want the number of times one occurs okay so once i do this for the following follow-up is done i can the following follow-up is done i can the following follow-up is done i can just return my result okay so let's go ahead and submit this and see what's up let's see what's going on let's see what's cooking okay um oh okay so it gives us an error this is correct but it gives us an error it says built in method we're not allowed to use a built-in method let me make to use a built-in method let me make to use a built-in method let me make sure that's why okay yeah i believe that's why we're not allowed to use in a built-in we're not allowed to use in a built-in we're not allowed to use in a built-in method like we're using the collection so let's think of a different way to do it okay you have taken the liberty to write out some things for us okay i wrote out the numbers from 1 to 15 and it's binary representation so let's go in and manually count the number of ones in there so for 0 there's obviously 0 1 in there for one there's one in there for two that's one for three there's two ones for four there's one or five we're just manually counting in this two six there's two seven there's three eight is 1 9 is 2 10 there's two 11 there's three for this damn twelfth is two 13 there's three fourteen that's three fifteen that's four okay do we see a pattern can we see a pattern in this okay so let's look for a pattern okay so i'm gonna call this first guy he's our base case okay let's see again let's forget about these numbers we just wrote down let's forget about all these guys for now let's see if we can see a pattern that actually derive him okay so this guy's our base case when is zero obviously um i'm going to call this a right i'm going to call this case a and obviously a equals zero okay he's our base case we know that zero has zero one so now for the next guy this guy i'm gonna call him b and can we see that okay i'm gonna draw a line here actually for a okay can we see that b is just equal to a plus one okay a plus one and since a zero which equals zero for a plus one so b is just one like one okay kind of like we expected okay i'm gonna also draw a line a b that's a terrible line i'm gonna undo it first i'm gonna draw it okay i'm gonna redraw a line okay we have b so now let's find c so what is c is just going to be i'm going to call this two c and c is just equal to the cumulative list of a and b okay at least including a and b plus one okay so in this case what does that mean it means here this first guy's gonna be a plus one and what is a zero plus one he's going to be one okay this second guy is going to be b plus one whereas bb is one plus one is going to be two okay kind of can you see how it's matching now okay now we have one and we have one i mean it matches the guy we counted okay now let's draw a line across c okay now next is d okay what is d gonna be d is gonna be cumulative a b c plus one okay so now let's start with a was zero okay i hope this is making sense but anyways let's go a was zero right zero plus one is one okay next is b was one plus one is two next is c is this next two guys right there's two elements and see c is one the first guys is one plus one is two second guys two plus one which is the i plus one three okay let's draw a line here now all these guys are d do you see the pattern now okay let's create e is gonna be obviously equal to a b c d cumulative plus one again let's start with a and see how it's all matching again back to e so a was zero okay zero z you see a was zero plus one is one okay b was one plus one is two c was one uh let's see well there's two elements in c right the first guy is one so add one to here with the second guy's two right add two to him he's three now d is the next four guys okay so they just take each element and d and just add one to them so just two three again three so we're here two plus one is three now we're here three plus one four so do you see how it all matches right this is e okay so pretty much this formula holds okay you can create the next guy you can create b from a by just adding one to a you can create c by adding one to a and b you can create d by adding one to a b c d you can create e by adding one to a b c d okay so now that we've figured out the formula let's go ahead and see what the code looks like again this is correct but it just gave us the error because we used a python package we're not allowed to use like if you look at the bottom it says can you do it without using any built-in can you do it without using any built-in can you do it without using any built-in functions okay so now let's cool what we just explained okay we're going to create a result variable kind of like we did before a list not an empty design we know the base case is zero right we established it we said a is the base case is zero okay then let's build up from that base case okay so we're gonna say while okay well the length of results okay right now result has only one element but while the length of result is less than or equal to n and it's the number we're giving whatever number because the problem asks us to go up to that number okay while he's less than or equal to him let's do some stuff what do we want to do one of the results dot extend not append in this case e x t e and e yeah i suck at spelling but extent not a pin but extend what do we want is extent i want to extend that list by a list which is just i plus one remember whatever was previously in the result i we want to extend him by i plus one okay now this is called the list comprehension for i in resolve the same for each element in results go ahead and append addition of one to that element back to him so we're extending results by this okay and then once we're done with the while loop we just want to return results okay let's go ahead and run the code and just kind of like a sanity check just see what's going on says our answer is wrong okay why is that answer wrong okay i'm sorry okay we want to return results okay but we don't want to return result by itself okay we want to return everything in results okay up to n plus one okay because he's gonna keep going okay we wanna um you see how we have a two in here we don't care about the last one we just wanna stop right here okay now let's try that again okay accepted let's go ahead and submit bam so 97 as far as speed goes we're also moving and space is not too bad but yeah that's it for the video i hope it was helpful and i'll see you guys in the next one
|
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
|
417 |
hey everyone welcome back and let's write some more neat code today so today let's solve pacific atlantic water flow so this is another problem from the blind 75 list and that's why i'm doing it today the link to this spreadsheet will be in the description again and so we will be able to fill in one more graph problem today from that blind 75 list we're nearly done with that list now at least most of the important problems on this list i think there are some binary questions that i haven't really done and i might not do these because i feel like binary questions rarely come up in interviews but for this problem so the text is a little small so let's focus more on the picture so we're given a two dimensional grid of values and so each value represents a height so this has a height of 4 this has a height of 5 etc we are claiming that the top border of our grid everything you know right above our grid and everything to the left of the grid is going to be called the pacific ocean and everything to the right of the grid and everything below the grid is going to be the atlantic ocean so for any particular cell we want to know can this cell reach the pacific ocean and can it reach the atlantic ocean if it can then we are going to include this position in the result if it cannot reach the atlantic and pacific ocean then we don't include it in the result so how do we know if this cell can reach the pacific and atlantic ocean because clearly there's a path you know straight to it well there's one condition we want to know if water from this cell can flow to the pacific end to the atlantic and water can only flow from the perspective of a cell to an adjacent cell that has a value that is lower than the original cell or equal to the cell and it can only flow in four directions straight above to the left to the right and below that's pretty straightforward usually you can't go diagonally in these types of graph problems and so in this case for this five we see that the above neighbor three is less than five this is less than five and this is less than five so clearly five can go to all of its neighbors now let's take a look at the three okay three has a neighbor one is less than three so it can definitely flow in that direction and now see this one is bordering the atlantic ocean so clearly that means five is able to reach the atlantic ocean now let's look left it can reach four and four can definitely reach two because two is less than or equal to four so from this perspective we can also now reach the pacific ocean so water from this position can flow to the pacific and it can flow to the atlantic so this position is going to be included in our result so a brute force and naive way to solve this problem is to simply go to every single position do some kind of graph traversal dfs or bfs would probably work and doing that search check from a cell can we reach the top and left border and can we reach the right and bottom border and if we can then we're going to add this cell to the solution set if we can't then we don't add it right so if we're doing a dfs or bfs on every single position starting at every single position in the grid we're gonna get a time complexity of basically the size of the grid let's say that's n times m which is you know the dimensions of the grid and if we do that from every single starting point we're gonna get n by m squared as the big o time complexity and you might think well since we're doing this recursively we're probably doing a lot of repeated work right so for example if i'm starting at 3 right doing a dfs from here i'm gonna go to its neighbors and then do dfs from here and maybe you know by doing that i can cut out the repeated work right and so i won't and so we won't have to you know restart a dfs for every single position in the entire grid and you might think that will work but i'm pretty sure it doesn't i'm not going to go through the details of why and somebody in the comments can correct me if i'm wrong maybe there is a clever way to get that to work but i tried to do it myself and i was not able to so i don't know if it's actually possible to do it that way there's a different clever way to solve this problem how about rather than us going through every single cell and checking if this cell can reach pacific and reach atlantic how about we go for start from the pacific ocean right and let's find every cell that borders the pacific ocean clearly everything in the first row borders the pacific ocean right that means everything in this cell can reach the pacific ocean and everything in the left column can also reach the pacific ocean and starting from each of these nodes what we're going to do is now find what are all the other nodes that can also reach the pacific ocean right so at the end we would have you know some kind of set maybe you know it looks something like this right or whatever and then we know okay these are all the ones in purple can reach the pacific ocean and similarly we would also do that with the atlantic ocean we know everything here on the right side can reach the atlantic ocean everything at the bottom can reach the atlantic ocean similarly we do some kind of dr graf traversal starting from each of these positions right and see okay what nodes can reach the pacific ocean as well and at the end we would want to go through every single position in the grid and we'd want to find positions like this one that can reach the atlantic and pacific ocean that we marked as being able to reach the atlantic and pacific and then from these ones that can reach both we would add them to our result and then return the results so that's kind of the general algorithm of how we're going to do things the reason this is more efficient this is going to be big o n times m we're not going to be revisiting nodes mult you know several times we're not going to be re-running a graph traversal to be re-running a graph traversal to be re-running a graph traversal what we're going to be doing is starting at each of these nodes right doing a depth first search right so for example let's say we started at this one right we'd do a depth first search and then see all the other nodes that can reach the pacific ocean right you know let's say we marked these and these right and then maybe we do the same thing starting at this one right and we'd you know go over here maybe and then go over here and then we'd come back here if we ever got to a cell that we revisited we would not want to continue our debt for search from a repeated cell right so we just wouldn't do that so that's the main idea of this algorithm but there's one last point i want to make before i start going through the code and that is remember how if we're starting at a cell like this one water can flow from this cell to a cell that has a smaller value right like a cell a small cell like three for example and then it can flow down to a smaller cell like one and then it can reach the ocean right so if we are going starting from a cell and reaching the ocean we are allowed to go at equal heights so one can reach one or we can go in decreasing heights like these ones but if we're going in the opposite direction if we're starting at the atlantic ocean and going to a cell like 1 going to a cell like 3 and going to a cell like 5 then we're going to have to do the opposite we can go to cells of equal heights or cells of increasing heights right you kind of see why that's the case because what we're saying is water is allowed to flow from five to three to one so therefore water from the ocean is allowed to go from one to three to five because that does mean that five can reach the ocean so with that being said the first thing i'm gonna do is go through the first row which is gonna be pacific ocean values and then i'm gonna and from there i'm gonna run depth first search to see all the other nodes that can reach the pacific ocean and i'm gonna do the same thing at the bottom row seeing which nodes can reach the atlantic ocean and i'm gonna be maintaining those in a set let's call it a visit set it's going to be a hash set so that we don't end up adding duplicates to it so now getting into the code so the first thing i like to do with these problems is just get the dimensions of the grid so we're guaranteed that this grid is not going to be empty so we don't have to you know worry about that so let's get the length of heights which is going to give us the number of rows and then get the number of columns as well and so i'm going to be having two hash sets pacific and atlantic maintaining all the positions that can reach the pacific and atlantic oceans respectively and then what i'm gonna do is i'm gonna go through every single position in the first row so i'm gonna go through every single column in the first row right and what's going to be every single position in the first row from here it's going to be 0 right in the first row is 0 and column is going to be the column position and so what i want to do on this position is run a dfs right so i'm going to run a dfs on this position right and so i'm going to pass in a visit set to this dfs function since this is the first row means it's the pacific ocean right it's not the atlantic it's the pacific so that's what i'm going to pass in as the visit set the pacific ocean so i want to visit this position and i want to see all the other positions it can reach now we know that water from the ocean to other cells can only go at equal values or greater values right remember we reversed the thinking since we're going from the ocean to the cells we're going to have to do the opposite so we can go to greater cells so i want to always pass in a previous height variable to this so if we're going to visit a cell i want to make sure that you know we're allowed to visit that cell so i'm going to pass in a previous height so since there is no previous height for this position i can just give it a default value and i'll just give it the same height as this position because that's going to be allowed remember we're always allowed to visit heights of the exact same height as the previous position and so while we're at this right we're going through every position in the first row why not go through every single position in the last row which tells us the atlantic ocean right so what's the last row it's going to be the number of rows minus one and going through every column in that rows and so instead of passing in pacific let's pass an atlantic because the bottom row refers to the atlantic ocean and similarly we'll pass in the height of this position as the previous height so we're calling this dfs function so let's might as well define it up above here now the first two parameters are going to be the row and column and the next is going to be the visit set now since we're reusing this function for both atlantic and pacific we'll just give it a generic name like visit we could be passing in either of these two sets and the last parameter is the previous height so if this position has already been visited meaning if row column is in visit then we're going to return we're not going to continue this function or if it's out of bounds we're also not going to return right because remember we're already going from the ocean from let's say the pacific ocean and trying to visit all the cells that we can because that's going to tell us all the cells that can reach the pacific ocean so we're not even trying to reach the ocean right now we're going from the ocean to all the cells so if we go out of bounds then we're going to have to return so if let's say r is less than 0 or c is less than zero or if r is equal to the number of rows that means we've gone too large or if c is equal to the number of columns that also means we've gone too large and the last case where we would want to return is if the height of this position row column is less than the previous height because remember we're only allowed to go to heights of greater height or equal so if the height was too small then we would want to return if we're not returning that means we're finding a new cell so let's go ahead and add it to visit we're visiting this new cell row column and then on all four of its neighbors we also want to run dfs on all four of those neighbors and we could do that with a loop but i'm lazy so i don't want to write that out i'm just going to copy and paste this four times so row column passing in visit and passing in the previous height which is just going to be heights at this position row column let's copy and paste this four times and so we're gonna go through all four of its neighbors so row plus one is one neighbor row minus one is a neighbor column plus one is another neighbor and column minus one is another neighbor and that's going to be the entire dfs function for us it's going to be marking all nodes that can visit that can reach the pacific ocean or the atlantic ocean depending on what we pass in and so right now we're doing that for the first row and the last row but we also know the first column is going to be the pacific ocean and the last column is going to be the atlantic ocean so let's do that so for every row in range of rows we want to get every position at the left most column and call dfs on it so for row we're just going to pass in the current row we're going to go through every single row and for column we're going to pass in zero right we know that the first column is zero and if and the first column can reach the pacific ocean so that's what we're going to pass in and for heights we're just going to give it the default value of this position and similarly let's do the same thing for the last row let's do the same thing for the last column so for columns instead of zero let's do columns minus one and instead of pacific let's pass in the atlantic ocean because that's what the rightmost column refers to and heights is going to be the same default value and so we don't have to rewrite the dfs function right because we already wrote it up above here we're reusing that function so once these two loops have executed we will have marked every single position that can reach the pacific ocean in here and we'll have done the same with the atlantic ocean so now after that let's just go through every single position in the grid brute forcing it so every single position every single row every single column and for every single position we want to know if this position row column is in the pacific ocean and if row column is in the atlantic ocean then what we want to do is let's first declare a result list if this position was in both atlantic and pacific we want to go ahead and add it to our result and we want to add it as a let's say as a sub list and so once we've done that then we have definitely found out every single position that can reach both atlantic and pacific ocean and then we can go ahead and return that result okay i had a pretty stupid bug so sorry about that so when we're passing in uh we're you know we're finding the position of heights so you know we have column because that's what we're at for row we should have zero because that's the position that we're starting at so sorry about that let's change this to a zero and similarly down here i actually think we have this right so rows minus one because that matches over here but down here we have row and column zero so we want to change column to zero over here and over here we do have row so that matches but columns minus 1 is the column value that we want to pass in so with those changes you can see that this solution does work and it is about as efficient as you can get for this problem so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Pacific Atlantic Water Flow
|
pacific-atlantic-water-flow
|
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105`
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
| null |
942 |
okay so what do we have here di string match so let's see what the problem says so basically the problems is that we have a we have our a and let's just open the screen face yeah so we have this array we have this string and we have to print out an array such that if it is I a I should be less than a is 1 if it is D here it should be greater than I yes you have to form an array a okay so how do we solve this question so at the surface this is this seems like a very difficult thing to do keep track of all these small details but let's see how we can solve this efficiently so basically the idea behind this is that the array a the elements in the array a will revolve from 0 to n where n is the size of the array and he would be one greater than size of string so we will have something like this so 0 4 1 3 & 2 so 0 4 1 3 will this so 0 4 1 3 & 2 so 0 4 1 3 will this so 0 4 1 3 & 2 so 0 4 1 3 will correspond to this value and 2 will correspond like make sure that this value a I since it is it falls in that da is greater than a I plus 1 so in order to fulfill this we have to have one more element in the last ok so how do we solve this thing so basically this so we have a will have to two variables I and low high is I would be the maximum value that I can afford which is four in this case because the size is four and low is a zero so if we have a if I have includes if we have I then we know that the next number must be greater than this current value meaning if we have I here this value will always be greater than this value okay so AI will always be ki plus 1 is always be greater than AI okay so since we can have this low attributed to this guy here and then we'll increase the low one and then I can keep doing what we're doing so then if we have between concord rd then we know that current value must be greater than its next left its next right value okay so we will have a maximum value which is 4 we'll save it here and then we'll decrease the four to three okay and so on and so forth seelix let's do it properly it's going down properly okay so here we have this Eddie okay so the odd now so I is zero and I is for low is zero so this is answer Marie that we have if since it is so since this value is I will just since this value is high we'll have to slow value attributed here and then we'll increase the logo one and we have D so we'll place for here and then will decrease for two three and we have i7 add one here and then we'll increase the low two and we have D so we put three here and then it decrease for that it - here and then it decrease for that it - here and then it decrease for that it - no so up till now we have traverse the array now is the point in a time for the last entry so as you can see high and low points to both points to two so we can just add the last high audio at the end of the array so let's see how this last value points let's see how this last value is how this is always this always be the same okay so next let's see let's take a case of DDI okay so Dee and I okay so high is three low in zero so versus T so decreasing so on so we'll have three here and we will decrease the height or two and we have our game D so we'll add two here we'll update the hi to 1 and we have I so increasing meaning that we put 0 here and then now see both have same value so we can put the last element I know so basically the idea behind is that if it is d this the it device should be increasing from left to right if it is I the value should be decreasing when you go left so in this case it is decreasing 0 - it so in this case it is decreasing 0 - it so in this case it is decreasing 0 - it is increasing from here it is decreasing so 3 to 2 so for decreasing we have this hype I variable for increasing will have the slope will increase the low and then decrease the high and that's how it will all play out thank you for watching have a great day
|
DI String Match
|
super-palindromes
|
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where:
* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* `s[i] == 'D'` if `perm[i] > perm[i + 1]`.
Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`.
| null |
Math,Enumeration
|
Hard
| null |
476 |
hello everyone welcome to the channel today's question is number complement if you are new to the channel please consider subscribing we sold a lot of interview question on this channel and that can definitely help you with your interview the question says given a positive integer output its complement number and the complement strategy is to flip the bits of its binary representation means let's say at the example we are given with 5 and the binary representation of 5 is 1 0 1 we will complement it so it will become 0 1 0 and 0 1 0 is 2 so the output is 2 and if you look at example number 2 we are given with 1 so we will take the binary representation of 1 that will be 1 and the complement of 1 is 0 then minus 0 is equal to 0 so the output is 0 so let's move to pen and paper let's see how we can solve this question after that we will see the code I have taken the example given in the question is asking us that we need to convert 5 into binary then we need to take a complement of it and then need to written to sound so before we see how we can solve this question this is a table of X so this is how XOR works so what is the easiest way that is just ways I will come to every digit and I will revert it that means I will make 1 to 0 to 1 and 1 to 0 but we need to find the way we can do it they just phase every time I will take our eggs or with 1 and we can see when I do with 1 it will give us 0 and when I give it zero 1 it will give us 1 when I do it with 1 it will give me 0 when I will do it with 0 it freakingly 1 when I will do it with one it'll-it'll meet you and do it with one it'll-it'll meet you and do it with one it'll-it'll meet you and then this is true and we can return it so we find that our way we will define a variable that will be equal to one and we will take X bar of num with bit and bit is 1 and after taking for the first time it will become 1 0 now we will move our bit to the left so here we can use the left shift by 1 so it will come here again we will do the X bar now it will became 1 2 again I will move my bit to the left by one and again I will perform my XOR here it will become 0 1 0 and we can written 2 but here we have a problem and the problem is we don't know where to stop out this performing of X or Y because 1 0 1 can also be represented as 0 1 and if I will perform my exhort with 1 in this way at the end I will get 1 0 1 2 we need to find a way where we can stop our performance of XOR here so the easiest we fit that is we will use a combination of left shift and the right shift and let's see it with example so we have 1 0 1 so we know what we are doing a XOR with bit and we are moving the bit to the left in the same way if I can take 1 0 1 and move it to the right every time when we perform bit so let's see it with the example we have 1 I perform the X bar it will became 1 0 I will move my bill to the left it will come here and I will move my nums to the right by one trick lubricant one zero because I moved it by one again I will perform X watt it will become 1 2 and again I will move it to the right by 1 so it will become 1 now again I'll move my bit to the left it will come here and now my answer will become 0 1 0 and again I will move it to the right by 1 it will become 2 and when did it become 0 we will simply return this so here we go what we will do we will take a while loop while my name is not equal to 0 I will perform num equal to num XOR bit and then I will make a left shift to my bed then I will make a right shift to my our temp which will be equal to norm put m equal to M pride shift 1 and that then I will simply written my now so this is the way we can solve this question let's move on to the coding part and let's see the code so I made a variable M which will be equal to our num and I've taken a bit which will be equal to 1 so while my M is not equal to 0 or you can say till the time my temp exists I will make her legs were with bed and I will move my bit to the left by one and then I will move the temp to the right by one and why we are doing this so that we can know where we have to stop this execution and at the end I will simply return now so let's see whether it works or not here I submitted my code and it caught us up there so this was for this problem if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe
|
Number Complement
|
number-complement
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
| null |
Bit Manipulation
|
Easy
| null |
405 |
Hello Hi Everyone My Name Is Ayush Mishra And Definition Of Voters Today We Are Going To Talk About Convert Number On List To Hexadecimal About This Problem What To Do With The Problem That You Must Have Given An Interior Name You Song Have To Convert This Number With It In This And according to whatever your skin representation is going to come, what do you have to do with the edition on this issue and give it in the report. Now one more thing said in Punjab that if you delete it or give it, then it is impossible for him to remove it in it. There is a complete method, you will also see that we are given a negative number, I keep its money aside here, now we simply read the question and for some time there is extra water in it is told here. It has been said that whatever latest they are is fine in your decision, but it should be in the test and there should not be any leading zero there and if you are 50 then there is no problem. Okay, so you have done it here. During this discussion, we would like to explain it to you quickly, what does it mean? First of all, the hexadecimal letters. Out of this, we come first. There is a number system in the country. If there was a dish number system, then let us know how many digits are there in it. 2012 348 Here, the appointment is made. By using this we can make any number and how many total numbers in it. Now let's talk about the total time. If you all know, 2000 means that if you send any number and subscribe then you can use it. Okay, what does it mean? What about it is from zero till evening, it has digits in it, our zero one two three four five six seven and at the same time we change the number. Okay now let's talk about it. Subscribe to this channel 09818369381. Here the one who will tell you. So as I have subscribed to this and you who are going to talk about this to them, then we will understand how to that also happens so zero that I take this breath here, take 0123 and 500 600 800 Subscribe and to prevent any disease from changing us, we will have to use all these, some of these are simple, they are called in 2001, they speak, so here if you want how many people in the village, 0689 ABCD 2 So I have talked about the representation, now let's talk about how a number is connected, so here you must know how to convert it into decimals or not, then one can quickly take a peek and see like I have ever seen one. The number is the file, now what we have to do is to change it, how many digits are there in the outer water, the maximum that can be given is either zero, open it, then we divide it by two and after dividing, you have our lion like we Will divide one and a half 2020 for them into two times 245 How many reminders have I written here, which is the question here, well, it means that the forest president has appointed 40 from the bottom to the top, this is our Ghaghra, well, you tell me that. If you have any number, then change the pipe in the country because it is already in decimal. There are 20 minutes of people looking at us brother David crore 1000 then how much fun is land acquisition either you are going to get only one profit divide from Edison UK. If you save 400 rupees then you will have to do some event and you will have to divide by 6. Okay, through the festival of finding you will understand how to do the system. So suppose we have given the number 6, this is 666 128. One more thing, if by zero. If any number has been given to you in the report till hanging, then your answer giver must not have been from zero to 120. On the other hand, if you have given it to someone in 120, if you have given ten, then you will give the answer. This thing will happen in the middle of the 11th assembly. There is no need to remind me of such a promise. If we don't know how to edit above 15, then how will you write to him, he understands that he is middling, we will divide by 6 and question more, we people will now see this in this ashram divide actually. This is how we do 6069 Interpress here, this is this, after 6 to 7 minutes, we here, if you subscribe, then I, on the other side, what do they say and till we say what do we say, this is answered in this 1 That you must have understood the thing from the media, okay, hey, it was an example of the early time, understand that, what does its shells say 16th, okay, the system will come only after a minute, let's talk about how printing is, how to make a craft, wash it with 16161 Go 1617 how much is left for a like it was made here and when the crows fall on the body then all my money is 1 and 4314, don't take it as torn, understand that this forest is different and different like this, before this the governor was installing the channel and was repairing it. If you like then subscribe here, how we have subscribed the positive number here, that if it is given to you, then you add to it that 32a, if you add to your daughter's number, 2532, then whatever your It is up to you whether it will become positive or not. Now whatever post number will be created, its effect will be there, whose value will be seen here that 2532 is our number here - one will become our actual number - one will become our actual number - one will become our actual number because. 3232 I have given it here, whatever you want in MS Word, it is in 628 hours, so you are going to see something like this here, this is the number, then I will tell you the pot that I recommend to you have to add it on the tube side, simple, good. Now let's talk about some steps here, what is telling me that the number will be negative and posting can happen, both of these have been taken care of, launched and thought, after this the nearest number can be - after this the nearest number can be - after this the nearest number can be - from toe power and minus one to soon. It is possible that there will be a war as you can see, here we used to divide and keep its clouds from Malhar, we will keep it on this, we will subscribe here, don't forget to subscribe it, these complaints will come separately in the exam, now if we want. One cotton can help in making another one by turning it in this way like let me tell you that if it happens in this way for 30 subscribers which we will appoint it then aloe vera in it ok-ok if any of my number is negative ok-ok if any of my number is negative ok-ok if any of my number is negative And if any number is negative then we add 232 to it, we will replace it with my number, the number is minus one, so now we have subscribed this number - 1898, that's how we subscribe six and here we are. Do you know that when you are dividing any number, you should use it here, Monica Roshni will at least get it, that will go in the mental, by keeping this reminder in the digit, it is good for the people, it is okay. Will give number is this number, it should come here, so it means score divide subscribe, so for this, we were doing this question here, above here, for this, how are you, how will I get the question here, reminder got set. By raising the question, the reason is that I have to remind the forest about the yagya, quick problem, enter advance from here onwards, our number has changed, the total capacity in this has changed, Alka Yagnik, okay, now one more thing, when our reminder comes, this reminder is put. If it is up to 1079 then there is no problem then it has to be changed, what did we say that if the responsibility is mentor, it is bigger than 9 and at the same time it is less than 16, it means if it comes in 10 to 15 days, my if The reminder is coming in 10 to 15 minutes, so we will have to change it, so when I said, change its fate, pick up the character of its glass water from the dictionary, change it to that, it will be better in simple view, mine will change to this and I will go and get a stone in my stomach. Okay, if this works then add, it will not work for me and then we will go there and put one of ours in a list named Answer, so this is here, it is ok, I have understood how it should happen. Here we have taken out a reminder that if mental is coming between the two then what we have to do is simply change it to the point character near it and whoever will react after picking it up will react ah good luck hey okay. Let us assume that now this is my creation, okay, now next time again this number of the loop is mine, we will figure out its meaning, we will put in it, something special is going to happen by subscribing, 600 here and here the question, what does it mean in the middle of 2019? Village, now as if we are appointed here, what do we have to do, now we wanted hatred here, in the play list, what will we do to reverse the list, after that I wrote that if the list is to be reversed then it would be a fashion statement to use it and after this If you want to join the reverse list, then join here without taking space, meaning what score do you join, then my uncle has understood how I have changed my number after sixteen, I have to revise it, which is reminder question time. We have to keep hold, if our mental tension is in the middle of the system, then we have to keep the character in its report and from the poor but this is in between, so we all subscribe in the subscribed list, if you are not subscribed then you make sense of this
|
Convert a Number to Hexadecimal
|
convert-a-number-to-hexadecimal
|
Given an integer `num`, return _a string representing its hexadecimal representation_. For negative integers, [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
**Note:** You are not allowed to use any built-in library method to directly solve this problem.
**Example 1:**
**Input:** num = 26
**Output:** "1a"
**Example 2:**
**Input:** num = -1
**Output:** "ffffffff"
**Constraints:**
* `-231 <= num <= 231 - 1`
| null |
Math,Bit Manipulation
|
Easy
| null |
295 |
welcome back to agwood yes today's question is leak code 295 find a median from datastream so the median is the middle value in an ordered integer list if the size of the list is even there is no middle value and the medium is the mean of the two middle values so we have two examples here we have two three and four the median is going to be three right so it's going to be the middle value because this array is odd length with even lengths we just add up the two values or the two middle values and then divide by two right so we need to build out a class called medium finder and then we're going to add methods to this one called add num which is going to add a number into this class one called ad num which is going to add the number into this medium finder object and lastly we have find median method which is going to find the median within this medium finder object so let's start off with an array right that's what we're going to initialize this class to we need to add numbers in here say we have 1 and 3 already in this array what is the most intuitive way of finding the position to insert an integer into an array with log n time complexity well it's going to be using binary search right so we're going to use binary search to find the position in order to add a value say the value is 2 we're going to have the left pointer we're going to have a right pointer and we're going to have a middle value and if there's middle value that we calculate from adding these two together and dividing by 2 if that is equal to the value then we can slot it in there otherwise if it's less than this number then we're going to increase the left pointer right so the left pointer would move to Mid plus one otherwise if the middle value is greater than this number well we know that it's not going to be in the right side so we are going to move the right pointer to Mid minus one and then in order to insert this value with in the array we're going to have to splice it in now this is the only drawback to this solution is that we are going to be using slice to insert the values so it's not just going to be log n time complexity it'll probably be okay login right because we are going to be splicing next is finding the median and there are two ways that were stated in the question there's an approach where the length of the array is even and there is approach where the length of the array is odd now if it's even we need to find the two middle values within the array so we can calculate the middle value by simply doing array.length array.length array.length divide by two so this grabs us the middle value so say we have an array of one two three and four so this is going to grab us this value here three we also need two here so we're going to have that value as well and we can just grab it by saying this value minus one and then we can just add these two together and divide by two so it's going to be five divided by 2 which is going to give us 2.5 and then with odd length arrays us 2.5 and then with odd length arrays us 2.5 and then with odd length arrays it's even more simple we're just going to calculate the middle value so in this example up here the middle value is going to be 2 so we're going to do r dot length divide by 2 and we'll have to floor this as well right so it'll be math.flow r as well right so it'll be math.flow r as well right so it'll be math.flow r dot length divided by two this is going to give us the index of one and that is going to be pointed into two right so then we can just return that value within the array so this will be running in o1 time complexity okay so let's dive into the code so for the medium finder we're going to initialize the array so have it equal to an array then within the add num method we're going to initialize left and right because we are using binary search so it's going to be this dot r dot length minus one and then while left is less than or equal to right we're going to get the middle so the middle is going to be masked up floor right plus left divide by 2. great so we have the mid now we need to work out whether we need to shift the left pointer or the right pointer so if this are at Mid so the middle value if that is less than num we know that's not going to be in the left side right so we can shift the left pointer to Mid plus one else if the value within the middle of the array is greater than them we know that it's not going to be in the right side of the array so we can shift that to Mid minus one and then we have to splice it so we're going to splice this which does slightly increase the time complexity right so this dot r dot splice the first parameter we pass in is the index right so we're going to be passing in a value at this index the second parameter passed in is how many items we need to remove we're not going to be removing any we're just inserting here so this can stay a zero and then the Third param is going to be what we are inserting so that's the ad num method sorted then for find median it's pretty straightforward we just need to work out whether the array length is odd or even we can use the percent sign two if this is equal to zero then we have an even array so then we can work out the mid right so that mid equal this dot r dot length divided by two then we need to add this dot R mid with this dot R mid minus one right because as it says in the question statement if the list is even the median is the mean of the two middle values so we have the two middle values here we're going to divide that by two to get the median and we're going to return this else we have an odd length array so we just need to work out the mid which is going to be mapped up floor this dot r dot length divided by two and then we just return this dot array at that middle value okay so let's go ahead and give this a run been accepted let's submit it and there you go if you like this content don't forget to like comment subscribe it really does help out with the channel and I'll see you in the next one
|
Find Median from Data Stream
|
find-median-from-data-stream
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
* For example, for `arr = [2,3,4]`, the median is `3`.
* For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.
Implement the MedianFinder class:
* `MedianFinder()` initializes the `MedianFinder` object.
* `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
* `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input**
\[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\]
\[\[\], \[1\], \[2\], \[\], \[3\], \[\]\]
**Output**
\[null, null, null, 1.5, null, 2.0\]
**Explanation**
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = \[1\]
medianFinder.addNum(2); // arr = \[1, 2\]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr\[1, 2, 3\]
medianFinder.findMedian(); // return 2.0
**Constraints:**
* `-105 <= num <= 105`
* There will be at least one element in the data structure before calling `findMedian`.
* At most `5 * 104` calls will be made to `addNum` and `findMedian`.
**Follow up:**
* If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
* If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
| null |
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
|
Hard
|
480,1953,2207
|
338 |
So hello friends, today is the 67th day of our counting bits and we are moving forward like this. In Blind 75, I like this question because it looks easy and the questions are easy to understand. There is fun in doing everything and it builds our confidence that we are moving forward so much and even after going, we are getting easy, so let's come to the question quickly. We have to go ahead till + 1 quickly. We have to go ahead till + 1 quickly. We have to go ahead till + 1 i.e. we have to reduce from zero to tu and i.e. we have to reduce from zero to tu and i.e. we have to reduce from zero to tu and tu is zero then we have to reduce for tu what we have to do is after writing them in binary as many vans come then when zero van If you do, then whatever is zero in it, zero van comes in binary, van also comes in van, you come b1 man, okay in binary, when we write in the form of 0 1, then count d number of ones and here But let us understand first of all what is Dena Media that we have like N = 2 is Dena Media that we have like N = 2 is Dena Media that we have like N = 2 then what will be the answer for van and tu here what should we tell when we write it in binary then I know how to write binary means like If we have 4 at the end, then what do we do for four? It happens that man lo, in the beginning all the 00's are there, so here it is 2^0, so that means it is for eight, so how do I have to make it from these? By doing the same, how will four become four? Here is four, then van, make the rest 00, one becomes three, then zero becomes zero van, here 1 + 2 becomes 3, so look at it like this, of zero, here 1 + 2 becomes 3, so look at it like this, of zero, here 1 + 2 becomes 3, so look at it like this, of zero, all zeroes remain, zero of van, zero van The last one remains, right? What do you mean? All the zeros behind will remain. What will remain for you? 010. Put zero in front too. No problem. If you understand then tell me how many vanes are there in it. How many vanes are there in it? One stop is visible in it, how many in it? Vans are visible. Okay, so from zero to length means the output that was going to come was zero van tu hain na because for whom are you for three, if you write in binary then how many will be made, two vans will come in three, now what should be the method of this? Well, I have already told you a lot about beats etc. when we saw Batman etc. because Blind 75 which deals with a lot of questions, so what are we going to do here or if we do it like this? We came to know that once we shift, we will also see this van, right? By doing this, we will check how many vans there are, although there are many ways to do this, divide 3 by 2 and we get van. If we are doing modules with 1, then again 1 is 1, then we get 2 1, after that when 1 is divided by 2, we get zero, after that less is reduced, so it means we can do it in three as well. If our method is to see the repeated thing, okay, this is the best part of it, then first I write what is their binary representation 0 1 2 3, so see, it will continue like this, now I have written the binary of all in front. Look at the thing, how many vanes are there in it, number of vanes is zero, one is visible in it, how many are visible in it, only one is visible in this, two are visible in three, two are visible in four, now look at the thing carefully, one is visible. Look here, this is the setup. Same setup is here too. You can see how it is getting repeated. Actually, these are the most significant bits, like I told you 2 rice, power is the most, let's see them. I take days from the account, from CNT there is one, you are four, that is, the table runs properly, it will become 16, then it will become 32, then it will keep increasing, the table runs fine, you keep multiplying with your power. Van tu ki power tu kar hai nahi, one thing we have come to know is that the significant beat has changed here, first look at the basic that here we have initially given here, then here it has changed on the second. So I came here, went to the third place and went down and took the eight also, because here in the fourth place, let's find out what is its condition. Also because of the DP, if you look at N- Also because of the DP, if you look at N- Also because of the DP, if you look at N- 4 date, go back four steps and look at it, then Han Bhai, who is in this. The answer is that it is going to be added here. What is the condition of Punch? Look, whatever is its condition, it is going to be added. How many one and two are there in Punch? One was already there and one has been added now due to significance. So the thing repeats, here we initially saw van, then we will make it 1 + DP off and initially saw van, then we will make it 1 + DP off and initially saw van, then we will make it 1 + DP off and -1. Okay, one step behind, we -1. Okay, one step behind, we -1. Okay, one step behind, we will see one step behind, if you come to van, then van plus DP off is changed here, so N - If we have to do 2, we will have to do plus DP off is changed here, so N - If we have to do 2, we will have to do DP of N - 2. We will have to do OnePlus DP of N - 2. We will have to do OnePlus DP of N - 2. We will have to do OnePlus DPO. Okay, here our significant weight changes again, so 1 + DPO and - 8, then 8, whatever was there earlier will be 1 + DPO and - 8, then 8, whatever was there earlier will be 1 + DPO and - 8, then 8, whatever was there earlier will be repeated, so let's code this thing and this This is the Van of D good part of dynamic programming which we just saw, okay so now you heard the explanation, see, this is such a small code, it becomes very small because of DP, so initially we will take everything from zero to man, so N + 1. Tak which is N was the man, so N + 1. Tak which is N was the man, so N + 1. Tak which is N was the name, so we initialized everyone in the DP with zero, so we took the count as 1 person who was checking the infant beat from month to month and this range will go from 1 to N + 1. and this range will go from 1 to N + 1. and this range will go from 1 to N + 1. What will we keep doing in the count? We will keep doing 2* in the count. If our in the count? We will keep doing 2* in the count. If our in the count? We will keep doing 2* in the count. If our equal, you van comes, we come for it. Okay, as we are increasing, so initially zero, van tu gaya hai, na to tu ja four hota hai, so our beat changes on four. Then look ahead, it will become 8 pe, tu pe ho gayi thi beat chain, na to si equal tu i will be made, but if this friend changes the beat, then the count will keep increasing like this and DP fee equal tu van plus DP of I. - C will keep on happening as I of I. - C will keep on happening as I of I. - C will keep on happening as I told DP of I - C will keep on happening, now what was I, what DP of I - C will keep on happening, now what was I, what DP of I - C will keep on happening, now what was I, what was ours, you can do it with N man also, meaning this is the same thing N and N - like 4 are doing D, so like this N - like 4 are doing D, so like this N - like 4 are doing D, so like this Our DP will be less and the final return will be done. This is just a small code and it is the same thing, it has been written logically, you will get its link in the description. If you like it, then you understand it. If you don't know how to like, then you can ask doubt in the comment. See you in the next video
|
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
|
70 |
Google loves to ask dynamic programming questions so let's solve one suppose we're climbing a staircase and it takes end steps to reach the top each time you can either climb one or two steps in how many distinct ways can you climb to the top n is equal to three you could take one step and one step you could take one step and then two steps or you could take two steps and then one step let's suppose there's 1 2 3 four steps to get to the top well how many ways can we get to here well it's just one step from the start to get right here to get here there's two different ways Two Steps from the beginning or one step from right here to get to three we can get there from two from this step or one from this step but there's two ways to get here so it's going to be 2 + 1 which get here so it's going to be 2 + 1 which get here so it's going to be 2 + 1 which equals three ways to get here to get to four you can get there from here or from here but there's three ways to get here and there's two ways to get here so it's 3 + 2 which equal 5 here's my solution 3 + 2 which equal 5 here's my solution 3 + 2 which equal 5 here's my solution in Python if you'd like to check it out
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
283 |
now let's take a look at a legal problem called move zeros so given an array of integer nums write a function to move all the zeros to the end while maintaining the relative order of the non-zero elements non-zero elements non-zero elements so in this case we have a uh integer array and we want to move all the zeros to the back while maintaining the order of the array so in this case we still have one comes before three comes before twelve but we're just moving all the zeros to the back and the space complexity in this case we wanna keep any constant so to do this in a constant space complexity what we can do is we can use two pointers and the idea is this we're going to have one pointer which is the left pointer points to the uh the left pointer right the first element in the array and the right point is going to point to the second element array then what we're going to do is we're going to see if we can be able to find a element that so the right pointer is there to find to explore a non-zero there to find to explore a non-zero there to find to explore a non-zero element and the left corner is there to find a zero element right so we're trying to get the left pointer anchored down to a zero element so that we can get the right pointer go out on the right side explore a non-zero on the right side explore a non-zero on the right side explore a non-zero element so that we can swap their position right so zero one in this case we're going to swap them now we have zero here and one's here right so now we're gonna move both of them one to the right and then we're going to talk uh think about uh we're getting the left pointer anchor down to a zero element then we're going to move the right one and one to the right to explore a non-zero element that we have three so a non-zero element that we have three so a non-zero element that we have three so we have swap three with zero and then we're going to move both of them one to the right so now we have the left pointer is anchored down to a zero and then we're going to focus on getting the right pointer to try to find a non-zero element so now to try to find a non-zero element so now to try to find a non-zero element so now we have 12. so 12 is a non-zero element we're going so 12 is a non-zero element we're going so 12 is a non-zero element we're going to swap them and then we're going to shift both of them to the right so now you can see we're out about and then at the end we're going to return uh or i should say in this case we return void so we're not returning anything so at the end we're basically solving this using two pointers so let's say we have another example where we have the elements are already in at the back of the zeros at the uh at the end of the array so we can do the same we can apply the same way right so our job is to get the left corner in the correct position so if left one or does not equal zero we want to make sure we keep moving them to a zero position to a zero element then we're gonna get the right point or try to explore a non-zero element in this case non-zero element in this case non-zero element in this case this is a this uh this example is already good so we can our job is done right so now let's think about how we can do this in code so first we're going to define our base case so in this case it doesn't really say if this is the array it does uh it's empty or anything so we want to make sure we the array is not empty so then we're going to focus on defining the pointers so define pointers and then we're going to move zeros to the back okay so now let's define our base case so we're going to have integer n which is equal to numbers.length n which is equal to numbers.length n which is equal to numbers.length so if n is less than 2 we can just return right so if in this case if there's only one l in the array or if there's zero element in the array we can just return our job is done so once we have our base case defined we're going to define our pointers so now we have our left which is equal to 0 our right which is equal to 1 because we know that we have the space right because now n right is going to be bigger than or equal to 2. so in this case we once we define our pointers we're going to think about how we can be able to move the zeros to the back so while right is less than n we're going to focus on those cases the those conditions that we talk about so in this case if we first have to get left pointer that's very important the anchor pointer moves to our correct position so in this case we have integer uh sorry in this case if we if nums at left right does not equal zero that we have to get nonsense in the correct position so in this case we're gonna move left and right both one to the right otherwise if we have a situation where nonsense right does not equal to uh in this case does not equal to or i should say equal to zero right if it's equal to zero then we have to get right point or move one to the right to explore to find elements that does not equal zero so once those conditions pass the in this case if we have a situation where nums at left is equal to zero and numbers are right does not equal zero so we can now swap them right so to swap them a elements in the array and have a temp variable that stores the value that we have num to the right is equal numbers that left and numbers at left which now equals 10 and we're not going to move them forward because in this case where after we swap them we're gonna for the next iteration it will focus on deciding whether either of those conditions met right so in this case nums that left does not equal zero then we move both of them to the right so in this case we're going to continue to do that until we get to a point where we have the entire array right and all the zeros at the back so now if we were to run the code okay so now let's try to submit so here you can see this is how we solve this problem in a linear time complexity
|
Move Zeroes
|
move-zeroes
|
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
**Note** that you must do this in-place without making a copy of the array.
**Example 1:**
**Input:** nums = \[0,1,0,3,12\]
**Output:** \[1,3,12,0,0\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you minimize the total number of operations done?
|
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
|
Array,Two Pointers
|
Easy
|
27
|
226 |
another day another problem so let's Solve IT hello guys I hope you are all doing well in this video we're gonna solve the problem inverse binary tree so let's get started the problem is that they give you a root of binary tree and they ask you to invert the tree an inversion or mirror of binary tree is just a binary tree whose left and right children are swapped for example if we have a tree that look like this after the inversion it should look like this so to solve this problem we're going to use my favorite technique the dipped first search algorithm or recursive pre-order traversock means we're gonna pre-order traversock means we're gonna pre-order traversock means we're gonna visit the current node then recursively call itself on the left shell and finally recursively call itself on the right shell and swap them so the steps are easy to solve this problem here is how recursion gonna work under the hood for this solution even if you have problem with recursion you're gonna see how it's gonna work so the first thing we're gonna do is to initialize two variables to keep storing the children of the current Row the left gonna start the left children two and the right gonna start the right children 7. then recursively we're gonna call the invertery function on the right shell 7 and set the current root to be 7 and store their children left and right say means 6 and 9. then another time recursively called the invertery function and the right children nine so here we have no more chillers so what we're gonna do is to return none and then recursively call the invertery function in the left Shield of the current root 9 which is sex sorry it's gonna also return none because there is no more note then we're returning the route to the right children that call the two children which is seven and swap the left and the right children in six and nine and goes back to the first route that's called all those function which is 4 and we set the left children to be the seven so I'm gonna keep it like that so you don't go so you don't get lost during the explanation after I finish I'm gonna swap them the second step is that we're gonna call the invertery function recursively on the left shelf and assign The Returned value to the right Shield of the current node so here is our how it's gonna work under the hood so here the function invertery gonna be called recursively in the left shell too and we store the value on the left and right variable then we call it again with the root 3. so here is there is no more children so return not and call the left children also there is no more children will return none then we return to the root means the left children that's called the two children which is two and swap the left and the right children one and three then finally we're going back to the node with the value 4 with all this work that we have done and we swap the right children to the left children and this is how it will turn out in the end that's it guys I try to simplify the explanation to the most possible way hope that's helped so let's jump as code in the solution the first thing we do is to set a base case which is if there is no children will return none then we initialize two variable left and right that keep track of the children note after that it recursively called the invertery on the right shell and assigned the return to the left Children of the route next we call again the function in virtue cursively on the left shield and assign its value on the right Children of the rule then finally we return the rule so the time complexity of the solution is often where n is the number of nodes in the tree because we are visiting each node and the tree for the space complexities of H because the input binary tree is a full binary tree where H is the height of the tree but in the worst case when we have a skewa tree and the height is n the space complexity gonna be of n but in the best case where the tree is a complete balance a tree the space complexity gonna be off Logan thanks for watching see you on the next video
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
68 |
good morning it's still very early so I'm not gonna be very loud so a little bit of whispering it's 7 20 A.M it's 7 20 A.M it's 7 20 A.M all right so I um I tried to solve this yesterday so that took now a whole hour and then last night I funnily like around midnight I finally got it to work so this was from eight hours ago so this entire thing took around one hour um 15 or 20 minutes I think so I just want to make another video here so I can explain my solution and then we can do the time and space analysis and then we will also take a look at top Solutions people don't like this problem so much which I mean this is a really hard problem so I'm just so happy that I actually managed to make it work in the end I'm pretty sure there are way smarter Solutions than this all right let's go over it the function what's it called it doesn't show okay but this is the function that you're given with and you're supposed to write and this is the additional function that I'm using it's called rearrange so we have this result which is going to be a list of strings for each line I'm trying to build each line so this will be a list of words so also on this stuff strings it's Edward is a string so that's for each line and we have this count to help us with all the Y spaces so we wanna go over all the words and we also need this index so for eyeing range first we get which word it is so let's take the first one that's an example so first word is this has four characters so count is starting from zero then plus four that is not exceeding the max width of 16. so we are gonna put this word in the list so we are storing all the words for each line and then we're gonna rearrange that line separately okay so we store this in this line list and it is not the last word of this entire words list yet so we just go in here restore that and we increment the count by the length of this word plus one which is the white space that needs to come after this word because we need at least one white space between the words for each line so that's the minimum so what we're counting here is the minimum amount of spaces that's going to be used for that line and we're gonna do this until we see oh okay there's no more space then we need to the next line and rearrange this line we just finished okay so for this word we're doing this if we're not going here and we're not going here then we have the next word is same situation going this if we append is July so now line has two words this is and then we are adding another so four plus one five plus two seven plus one eight so right now count is at eight and we do the same thing again for n so now count is at 11. and our Max width is 16. so we have counted 11 currently next word is example so example has seven letters so we had 11 plus 7 will exceed 16 so we're going here so result that's the final result we want to append some rearrange function will give us a string so we want to append that string to our final result let's go and look at rearrange so it takes this line which is the previous line that we were just using which has this and three letters in there a list of three words sorry so this is a list of three words next width is 16. count minus one so count is currently counting this plus ones quite space this is plus one white space and then n plus one white space so we're just removing one from it which will give us exactly how many spaces it takes to have this is and with only one white space in between so that would be the minimum amount of spaces these words need for that line okay so we're going here we have this line we have next width and we have the minimum number of spaces need for those words with one white space in between um so this is to handle the situation where there's only one word so let's look at that later so return we're returning a string so we're gonna build this string start with the empty string now what's the number of total watch spaces that's what we're calculating here mix with minus so count is this with only one white space in between and the number of Y spaces in between are simply the number of words in this list minus one so length of line minus one that will be the amount of white spaces that's in between and if we use count minus that we will be getting exactly the white spaces that the words are using without the in between word spaces so that is what's in here this is simply the int well this is the entire this is the number of characters in this eldest we could I mean we could actually just count that here instead of using this little calculation but I thought that was additional and necessary calculation since this is already red this is ready and I thought this would be a little bit more efficient he's probably not gonna make the most difference all right so this is the number of white spaces in total that we want to add between all these words so now how many what's the minimum amount of white spaces that's gonna be in between all the words so say if we had eight white spaces and we have three words that means um we need at least four white spaces between words and say if we had 10 white spaces and three words then we will be doing 10 divided by two we will still have four minimal y spaces between but we'll have a remainder of two which no oh my God sorry that's horrible example Okay so between is using the total amount of white spaces divided by the number of so this is again the number of words in this line minus one because we don't need y space after the last word so if there are three words we only need to calculate two in between y spaces so that will give us the minimum number of Y spaces and if we had remainder from this so this needs to be an integer otherwise it will return the float so if we had remainder let's say so in this case we had four and four yeah that's why I was using eight and what if we had 9. so 10 doesn't work because that would just be five and five so if we had nine and then it will give us between four and the remainder one minute one which means from starting from the left because this is one of the condition so if we have remainder then we wanna add one extra white space padding starting from the left so if we had so here we have four words let's say um between will be two and remainder um two that means it will be two white spaces between each of these words and we want to add one extra white space padding to the first two in between so here and here we will be having two plus one patty starting from the left um so I have to explain this part now we wanna start constructing this string with the words and the padding so line is all the words in this line so for other word to other words in this line we are doing this until the second to last because the last one doesn't have padding so we're just gonna add that in the end so this is going to iterate from the first word until the second to the last word so for each of them we're adding the word we're adding the amount of in between white spaces and if we have remainder then that means we're adding an extra white space just what one extra so if we had remainder two we'll be adding us the first word we add one and we'll decrement remainder then of the second word we add one again we decrement now remainder is zero so it won't be adding more so this will construct this string that we need and we're adding the last word to the end so this will return that string and we're going to append that to the result which is a list of these strings so then what we're doing here is we are done with this previous line and we want to now start with the next line so the word is actually at example because it's because that's where we realize oh okay example cannot feeling the previous line so that's where we stopped and rearranged the previous line so now we are starting with the next line we are resetting count to the length of the first word example plus one for white space and the Line is now a new empty string starting with the line is going to be a list so this list now has one element which is the current word and then it will go over again to append the next word so next round we have a count which is example seven plus one count is eight lying has one word which is example so of will be going in here again appending to the long list incrementing count and the text same thing and then last one let's do the last one so um now we're at word justification with this period so this is uh together as a string so word is that we're also at the last index so we see that it will exceed Max width so we're going in here so this will take care of this line and put that into the result now we reset content line so we are at the last one so we are going in here and what do we do here since we are since we have this for the last line it should just be left to justify no Extra Spaces inserted between words then we simply leave it as it is and add padding to the right which is what we're doing here line which is simply just the current it's just one word but let's see if this if it's this case it'll be a better example so while we're at the Shell we are when the word is at Shell we will go in here do this line rearrange and then reset count to B the length of shell plus one and Line is now having this one element of shell this is not the last so it doesn't go here yet and then we have B okay so that is still not exceeding Max width so we are appending this so 9 has shall be and count has shall be plus the one y space here so it is the last word so line has these two words um without the Y spaces because it's just a list of words so we want to join them with white spaces that will give us the shell white space b and now this function is gonna add all the padding we need to the right so a foot so the entire length will be this Max width the end we're adding y spaces so that's what it does so this part gives us shell white space b you know in a string I believe and then we pad spaces to the right so in total we still have this Max width so this is the final string we append that the result and we return actually we don't need return results there so we're gonna return here because this is the last word anyways okay so uh the only thing I haven't talked about is this one so this will be a good example for that as well so when we are at toward the shell we're gonna go in this rearrange function and the line would only have one word which is acknowledgment so line only has one length one why do we need to do this separately it's because this is being divided so if we don't handle this will be dividing zero also give us a divide by zero error so one this is only just one word we don't need any rearranging all we need is to put that word there and add the padding to the right like we're doing here so we're just taking that one word adding padding to the right and make sure it's got total mixed with so that's what we're returning as that string okay so that's oh I can't believe I took 20 minutes to explain and go over if it works yes okay so it is very efficient then I believe so there it is that's my solution I'm sure there are smarter Solutions so for this solution let's see what's the time and space for this solution so we are going over each Wars then we're storing them in like this we are rearranging so this is linear so this for Loop is linear because we're going over each word we started them in the list we're going one by one so that's linear now for each line we have this rearrange function which is also linear because real range is gonna take every word in the line and just add padding to it so the algorithm goes like okay it goes through these and then it's gonna go rearrange this so essentially it's linear but it's traversing this part twice and then it goes through this and they will rearrange this so it's linear but it's traversing to so it's still linear in total and for space we are also using extra I mean the output will be needing all the characters and the words so it is a linear in space as well storing we are building this result we are storing them yes so linear time and space that's really good all right let's look at the other Solutions so hungry I will go over this quickly and I will eat foreign okay um a lot of functions but yes exact same idea different implementation hmm all right okay a python solution let's see list zero for all the words okay I'll need more time to read this since this is more cryptic current I wonder what this current is okay current is incrementing the length of all words okay just like that whole words plus minus one that's the words plus away space okay mine install it I arrange ments with most number of letters okay I will need more time to look at this but I'm too hungry right now so um okay interesting all right so I will conclude my video here for this problem I'm just happy that I managed to solve a heart problem know it takes over an hour so hopefully I will improve and eventually I can solve a heart problem we think that hour I guess that's the goal all right I hope this is helpful and let me know if you have any questions or any requests for any specific problems I will see you in the next one have a great day and weekend yes bye
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
394 |
hey everybody this is larry this is day 19 of the leeco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm decode string unexpected wow looked like someone forgot to decode their string but okay let me refresh that's actually kind of a hilarious hair error but okay decode string given it an encoded string we turn it to go to string shanghaika uh hit the like button hit the subscribe button join me on discord let me know what you think about today's problem um so yeah so decode string giving it a string returning decoded string um okay so this is just like one length encoding but not actually because you could do it recursively i see um i think for this one it seems pretty like in terms of understanding the problem i think um it's pretty straightforward and that it's just some kind of recursive thing perhaps uh but i think you can also deal with a stack yeah i think you could do it also with a stack and i think that's how i'm going to do it uh and then after that it just becomes an implementation problem so definitely something to think about um but yeah that's let's do that so yeah given that n is less than 30 and the numbers are less than 300 we can just generate a string should be short enough yeah okay so let's just start with stack that's let's uh keep track of the current uh because whatever so i'm just trying to avoid having a lot of string concatenations so i'm just going to do results in an array and then we'll pass that into a string later on um and then now for okay so now we just pass this as one character at a time and yeah so now let's start with current multiplier which is what is going to be let's start one and if s do we want this to be one because if we see a number for the first time what do we do right we want to handle it differently so actually we want this to be zero maybe so now if s is alphabet okay if current is equal to zero current oops current is equal to one because it doesn't make sense for it to be whatever uh doesn't make sense for it to be zero so then now we push uh s into the answer well do we now we push it in the stack all right here i'm just double checking that whether the stack makes sense because here um i guess the stack kind of makes sense but we just kind of have to make sure that when we pop yeah okay yeah i mean i think like i said so what i'm trying to do now is just think about how to process this in my head in a way this is like a finite state automata again so i'm just trying to think about the states as i go through them uh sorry i'm not really articulate about this right now about that part but i'm just thinking through okay all the different scenarios and in this case if it's an uh with you know an alphabet then i'm just going for what that means i this is not done i think there might be more but let's stick with let's have this for now uh if s is numeric then current we shift to number and then we add this thing and then elsa s to go to the beginning of a thing the auto index pushes it if this is the case we what do we do right well we take the current number and we push it to the stack we might have to fix uh changed alpha but okay so then now stack dot uh append the current number and also current number is equal to zero again maybe yeah i might have to think about this part with the what happens in the alphabet again um but now else there should be all the combinations but let's put that way once we get to the end bracket we want to get so what that means what does this mean right that means that we want to get everything on top of the stack that until we get the number and then we multiply it by whatever that number is right yeah okay i think that's right so and we want to make sure that the current number is at least one it doesn't say whether the number could be zero or something like that positive integer okay i guess that's okay so okay um yeah so i guess for now leave it like this and here we keep on popping until the wait until we get a number so wow stack of negative one there's a number i mean my implementation here has been terrible to be honest and that's my bad uh again you i am solving these lives so apologies for not being you know i don't prepare for this because i want you to see my door process a little bit but yeah but so while the stack is an integer um yeah maybe i should on stack i should uh should change this to yeah let's just have a flag so that we know that is an integer so this is the beginning uh right now this is a flag for essay begin right um it doesn't really matter and it's zero to one so while stack is uh i guess it will encode this bit uh well just as you go to or not you go to begin we pop stack so it's stacked up pop so we get a string here um but now this is going to be reversed so we have to take that in mind but that's okay hmm yeah i'm just trying to think if i can do it in a way that doesn't reverse twice uh but yeah maybe that's okay let's focus on solving it first and then we'll figure out how to optimize this afterwards so yeah so let's just have uh um i'm just trying to think about variable name so yeah inside string that's quite that let's say inside is equal to empty space um or just in a way so inside that a pen stack.pop and then we'll just reverse it stack.pop and then we'll just reverse it stack.pop and then we'll just reverse it later and then now we push the string back on the stack which is that stack dot append uh and the other that's the other one maybe this is begin braces but um but let's just call it string is equal to one so let's put back string oh and this should be the second verb so um append this is the dot drawing on inside so now we have a string inside the stack instead okay so now we have to revisit this because i don't think i formulate this quite correctly but so what happens when we have an alphabet well we push it on the top of the stack as this is that good enough yeah i think so and then at the very end we can go from left to right on the stack and then put them all together because there shouldn't be any numbers left on this stack because for every number we do that yeah okay so let's take a look so and or rather um let's just do four you know um what's it called that's what type and item and in stack and now we're going from left to right so we are going from the bottom of the stack up if you want to call it that so we only want to get the item which is i and then we want to join on it so we could do something like that right let's see we have does it look right at all the answers no so um okay let's do some copy pasting so we could test them all together so i really would like this to be a little better than nothing but uh maybe this is one of those days larry needs a little bit more sleep uh yeah okay oh i'm being silly this is x not s this is what happens when you have single variable things uh you just confuse yourself now okay hopefully this is slightly better and i'm saying i do this live so ah string interfam okay that's weird that means that i haven't popped everything oh that's why because i'm because the top of this now is a begin that's what i forgot so that means that um yeah we should stack that top but it means that now during varian after this while loop is that the top of the stack is a big end thing which we want to pop but we also want to get the number right so multiplier is equal to stack and then is this times the multiplier now okay i definitely made i'm not gonna lie i definitely made this more complicated than uh complicated than necessary but it looks okay i'm just eyeballing the answer and expected answer and seeing whether they are this you know they're matching and that's when that real quick let's do something like empty string let's have one abc let's have two eight something like that just to make sure a lot of nested goodness uh oh okay so zero is not the case i know that's um if you don't watch the stream sometimes it looks like i checked this a lot but um the reason is because i misunderstood this problem why is this uh but it's because i you get bitten a lot well this is an extra one uh by zero cases and stuff like that because sometimes even if you read it they're not quite correct so that looks good so let's submit it woohoo yay so what is the complexity of this well it's a little bit tricky to say uh definitively because a lot of times these you know concatenation um of string concatenation a lot of times in a lot of languages they're not all one operations right so that like you know the character is or with a string has five characters and then you add another five characters to it actually takes over ten operations instead of like all one operations i mean i know well i mean i know of 10 is all one but in terms of um amortizing it does actually add up um but you can't implement this in a way using like string buffer or something like that and um book keep like bookkeeping which means just keeping track of the things so that you don't um you don't create the string until the very end right so maybe you could have uh store this instead of as a string you could store this as um something representing a string right meaning maybe a multiplier and inside string so that when you keep on multiplying it you just have to go for it at the end once instead of you know all this concatenation and stuff like that so uh and you know i have some weird constants as well but you know let's for now let's analyze this assuming that the concatenation is constant because you can do it and you should do it for practice for up solving um but you know but ignoring that this is going to be linear time because for every item in s we go for one so if it's albumin it's numeric one is which on top and here we only push it to the oops we only for every item we only push it to the stack once and then pop it once right so that means that every item can only be on the stack once or and have two operations done on it so it's going to be a linear time um in terms of space because we have a stack it's going to be linear uh space because it may go all the way through like something like in this case where it's just still linear-ish right where it's just still linear-ish right where it's just still linear-ish right um yeah so cool so linear time linear space assuming string concatenation is which you can optimize out as an implementation detail um cool that's all i have for this problem let me know what you think hit the like button hit subscribe on drummond discord and remember that like i do try and solve this lives and i was struggling a little bit in the beginning because i just woke up or whatever after taking a nap and you know i hope this is okay and be sure that you know uh if you really you know my style my videos are that usually you can 2x for it and it's okay so you know let me know anyway uh i will see y'all tomorrow have a good day bye
|
Decode String
|
decode-string
|
Given an encoded string, return its decoded string.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
The test cases are generated so that the length of the output will never exceed `105`.
**Example 1:**
**Input:** s = "3\[a\]2\[bc\] "
**Output:** "aaabcbc "
**Example 2:**
**Input:** s = "3\[a2\[c\]\] "
**Output:** "accaccacc "
**Example 3:**
**Input:** s = "2\[abc\]3\[cd\]ef "
**Output:** "abcabccdcdcdef "
**Constraints:**
* `1 <= s.length <= 30`
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
* `s` is guaranteed to be **a valid** input.
* All the integers in `s` are in the range `[1, 300]`.
| null |
String,Stack,Recursion
|
Medium
|
471,726,1076
|
88 |
Hello Guys Myself Amrita Welcome Back To Our Channel Technosis So In This Lead Card Series Today Bill B Solving Problem Number 88 Date Is My Sorted Are It One Of The Very Important Interview Questions So No Late Get Started And Let First Understand The Problem You Are Jivan tu wait arrest namas one and namas tu sorted in non decreasing order and tu in integers representing d number of elements in namas one and namas tu respectfully so in example you can see they have bin jivan one namas are three elements so am is three and Nos tu it also has 3 elements so n is three right or what they have tu do match one and nmas tu in n single are sorted in non decreasing order so basically they have tu mere dz tu arrest in one single are and it should also be Sotin right and the single sorted be stored inside the are name one take other separate are you from de merged are they have you modify the nas are itself and you are an accommodation this number one has length m + you are an accommodation this number one has length m + you are an accommodation this number one has length m + n first m elements give note the elements date Should be most and last and elements are set too zero and it should be ignored names too has length n so let's be we are going to solve this problem so let's take example one is number's one are which has elements 3 0 and They have in each other are date is namas tu which has elements 5 and 6 and they have bin jivan tu integers one is m which is number of elements present in namas one are date min is it is 3 and 10 which are men's number of elements present in jas You add which is also free and they have you both the arrest in de names one are itself so after merging name 256 right so what they can do first bill modified these empty elements date mains way bill put d larger elements come this point right because IF WE WANT YOU HAVE A SORTED ARE DATE MAIN'S LARGER ELEMENTS WOULD BE IN D STARTING POSITION SO DATE MAIN WE ARE GOING TO START FROM THE N LET TAKE N PAINTER EACH AND WHEN WE ARE COMPARING D ELEMENTS In de namas one are and namas tu are so per dat bill take tu points i which is de last element of nas one eric and j which is de last element of nas tu eric so basically they are going tu compa re i and k and wich Ever is larger they are going to put date come de care position so they bill compare and bill start writing the steps well so here you can see first bill check weather three give it greater 6 becomes one you three zero and six so let me write Dates well and different on de step how this element was greater they have tu put this element right so they can writer condition so date mens namas vani they are going tu put date come de care position in naam one error right so give number they are going tu care position so dat mens no element elements so they are going tu move k also tu de next position right mins three give it greater five which one is greater five is greater so dat mens they are going tu put five so it would be one tu Three zero five and six again move tu de next element so ja would be move every and k would be move tu de next position give they are going tu check weather number at i > > > 2 right no 3 is greater so date mens they are going tu Pat three at three care position so I would be one tu three five and six so date men in these days tu cases viver moving j painter and k painter tu de next position so they can right every a - - - - - - right and when number position is greater so They are going tu move i tu d next position and k also tu d next position so dat mens in this how it would be a - correct move dr tu d next element no tu and tu right tu give it greater 2 so dat mens it would Co tu de else part again so it would be one tu 35 and 6 tu de next position they don't have other position after this so dat mains they have tu break de loop here what dat mean they have tu run de loop only til when J let it be greater equals you zero and also I should be greater let us equals you zero so this is we need you solve this problem no let move ahead and let try this question on it so this is r class date is my sorted are no let start d method per it date would be public static wide let take d name write it know what it is d first i jn k so what would be the i so can see every last element of nas one are date min second position still m - 1 Right date min second position still m - 1 Right date min second position still m - 1 Right M - 1 And Similarly K Wood B N - 1 Date Is M - 1 And Similarly K Wood B N - 1 Date Is M - 1 And Similarly K Wood B N - 1 Date Is Last Element Of Nas Tu Are And What Bill B K Wood B And Last Element Of Nas One Year Which Is Total Length M + N - 1 Let Right Are Low Date Would be greater than equals you zero and also today they send I also should be greater than equals you zero and what was the first condition if Namas one come I should give it greater Namas you come they are going you put date in Namas one aate care position actually have tu move tu de next element in this how i > so dat mens we are going tu how i > so dat mens we are going tu how i > so dat mens we are going tu pat and de else part dat men no tu of k > so dat mens we are going tu pat dat and de else part dat men no tu of k > so dat mens we are going tu pat dat and de else part dat men no tu of k > so dat mens we are going tu pat dat aate di care position dat Hello is this mean function and let take d inputs date is one are elements 1 2 3 0 and they have one tu three and five correct and let they have tu integers one is number of elements in d number three which is also three no let tomorrow R Function Date Is More And Inputs Between Let Take Some Space To C The Output Clearly Let Run The Program And C D Output We Can See Every Way Output Is 1 2 3 5 To Arrest Tu Five Six To Late Test Date Today Well Late Run D Program In C D Output Frequency Ho They Need You Solve Let Run Let Vacancy Sweet Husband Submit Success So D Time Complexity Of This Approach Wood B O M + N C They Are Note Taking Other Separate You Steve The Murder Are Hope You Understand If You HAVE OTHER QUESTIONS OTHER DOUBTS PLEASE LET ME KNOW IN THE COMMENT AREA AND IF YOU LIKE THE VIDEO PLEASE PROVIDE YOUR FEEDBACK IN THE COMMENT ON THIS PROBLEM SO YOU CAN REFER DATE Aaj WELL THANK YOU FOR WATCHING AND PLEASE TAKE MORE SACH PROGRAMMING VIDEOS ON UFONE
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
64 |
hi everyone today we'll be taking a look at question 64 online code called minimum path sum so we're given an m by n grid with positive values and we want to find the path from the top left aka this one here to the bottom right which is this other one here which minimizes the sum of all numbers along its path and we can only move down or right so no diagonal stuff cool so this is a classic dynamic programming question what we'll do is we'll calculate the minimum sum for every single element inside the board and so by that logic and algorithm will have the middle sum by the end now how do we do this we can traverse uh from left to right and top to bottom meaning that every single new tile we come by we'll just choose the minimum between its left value and its right value which are the two previously visited values in our iteration as for edge cases since we have the first row in the first column here obviously they only can go one way so we'll update those first and then we'll update the inner uh for tiles in this case so let's update the first row and first column first and actually let's start one since we start updating by the second tile we can say plus equals zero i minus one so this will update the sum for the first row now let's update the first column um i zero just make sure that's correct grid i zeroed up equals grid um so once again this will just update the first column now to do is just update the inside so since we're starting at the first index of the row and column we'll say for that i equals one and four j equals one we'll update every single one by choosing the minimum between its left neighbor and its top neighbor why do we not take a look at the right and bottom because once again we are going on an iteration from left to right so we can only choose between elements that have already been visited and tested so in this case since we haven't updated this one or two yet we can't consider it in our um i'm sorry an hour update here we can only consider this value and this value has been updated so as it says we choose the minimum so we say math.min between math.min between math.min between the one above it so this will just continuously update every single element until we get to the bottom here at which point we can just return the last element which is just cool so let's see if this works just fine and we're just fine cool uh let's talk about runtime these are both going to be uh o of n and m where n and m are going to be the length and width of our matrix but the bigger iteration happens over here where we visit every single element inside so worst case this is a of oops n times m where m and with the gray respectively so once again the logic behind this entire question is just updating every single element with uh the cumulative sum up to that point to figure that out we always choose the minimum between its left and top neighbors and that's it and you keep entering until you reach the bottom this is considered memorization by the way because we are using previous results and choosing one of them to update our current result so with that i'll put a link to the questions those might get helped down below and i'll see you guys next time
|
Minimum Path Sum
|
minimum-path-sum
|
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
62,174,741,2067,2192
|
7 |
Hello Gas Myself Amrita Welcome Back To Our Channel Techno Sage So In Today's Video C Are Going To Discuss Lead Code Problem Number Seven Date Is Reverse Wait So Let's Get Started Let's First Understand D Problem Given Un Sin 32 Beat Wait X Return X With Its Digits Reverse so basically you need to reverse the 32 beats wait if reversing Which would be reverse of date particular number which is three too one in next example - 1 2 3 Reverse of mines one which three would be minus three too which is next example - 1 2 3 Reverse of mines one which three would be minus three too which is similarly next important so the output should be 21 because it would be zero 21 which would be further than this. 21 so it should display 21 so nine let's understand d approach tu solve this problem let's say see have a number van tu three and d re use of this number wud be 321 so first we need tu find d reverse of d number so nine if i Find d last digital convey form a number can see write it like this three in tu 10 plus tu which would be equals tu 32 similarly 32 * 10 + next digital van similarly 32 * 10 + next digital van similarly 32 * 10 + next digital van date is 3 2 1 and in d first step can see it write it zero in 10 + 3 which would be equals to three zero in 10 + 3 which would be equals to three zero in 10 + 3 which would be equals to three you find d first digital so from these three steps can see right un formula you find d reverse and other number c can say reverse in 10 plus digital and date digital what would be d last digital so date mains First you need to find d last digital and then you need to reverse in 10 + digital so every you can see let's say you reverse in 10 + digital so every you can see let's say you reverse in 10 + digital so every you can see let's say you have un number one you three so first time you need to find this is 3 right so digital would be equals Tu if I divide this particular number by 10 so tender would be three so like this c can find d digital which would be equals tu number mod 10 because it will always give us the remorder and then coming d starting c can initialise zero so in D first step it would be zero in 10 + 3 is first step it would be zero in 10 + 3 is first step it would be zero in 10 + 3 is d digital so it would be equals tu three so nine c need tu find d next digital date is tu so tu find tu c need tu have d number one 12 so date mens in d Third Step C need tu divide this number by 10 Correct number 10 so in this case 123 / 10 which will be Correct number 10 so in this case 123 / 10 which will be Correct number 10 so in this case 123 / 10 which will be equals tu 12 so nine d number is 12 c need tu find d next digital date wood b 12 mod 10 which will be equals tu end and d next step nine our reverse is three so it would be three in tu 10 plus dies it is tu which would be equals tu 32 and in d last step so nine c need tu find d next digital date mens c need tu divide Contact number 10 again 12/10 witch would be equals tu van so nine 12/10 witch would be equals tu van so nine 12/10 witch would be equals tu van so nine number is van tu find de digital c need tu say van more ten witch would be equals tu van so nine reverse is 32 * 10 + digital is van so nine reverse is 32 * 10 + digital is van so nine reverse is 32 * 10 + digital is van so de number Give this 3 21 If you divide this number nothing will come it would be zero so here we found reverse so basically only three steps this is first step you find d digital and d next step is you find d reverse and third step is you Divide Date Number's 10 So Dez R D Three Steps Which C Need Tu Us Tu Find D Reverse Of N Wait Nine In D Question C Se Date C Need Tu Consider Overflow Condition Date Mains If Reversing Causes D Number Tu Go Out Of Range Give C Need you return zero so ho rc going to do date nine you check d number if it is going out of d range date mains date number should not be greater give minimum values so nine so basically in minimum values so nine so basically in minimum values so nine so basically in reverse c are doing reverse in ten so c Need you check weather this reverse in 10 is not going out of d range since mains reverse in 10 should not be greater than d max value but give it less d minimum values so can see write it give it less d minimum values so can see write it give it less d minimum values so can see write it like this reverse greater than max value of 10 Reverse less give minimum value of 10 let c need tu return zero so nine let's try it solution for it so let's try d method date would be static in reverse and it would expect one number date would be x so nine c are going to do d Three Steps So Before Date First See Can Say Revise Zero In Which See Are Going To Reverse Of D Number And Then Will Date Number Is Not Equal To Zero Since The End Date Number Become Zero So C Need You Run D Loop Until Date number bikams give zero first step c need tu find d digital Reverse nine we need you check d overflow condition so see can put a condition every if reverse is greater than wait dot max value of 10 or if reverse is less than give integer dot min value of 10 then we need you returns nine let's call r function Date is reverse 123 let's try d print statement to see the output let's run d program and see the output should be 321 which is reverse of 123 so give output is 321 nine let's test with d other examples a well mine 123 output should be mine 3 21 c can see every d output is -321 and d third every d output is -321 and d third every d output is -321 and d third example that sp 120 so d output should be 21 so nine let's tested with this overflow condition also i have taken wan number reverse it is going out of range so i will take date number And will C D output where the output is returning zero or not so this is D big number so D reversing of this number you can check it is flying over so let's run it and direct output so the output is zero nine let me remove this and Show you how it works if I remove this condition let's see so sense this number is a big number when reverse it will go out of range and it will give same garbage value let's run program and see output so you can see Every It Is Same It Is Giving As Same Garbage Value So That's Same You Need To Consider This Over Flow Condition So Give If Reversing Of Doubts Please Let Me Know In De Comment Section Also Please Don't Forget To Like Share And Subscribe Channel In De Upcoming Video Will Solve More Lead Code Problems State You Thank You For Watching
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
263 |
hello Ellen welcome to nets at OS today in this video we will discuss about a glean number problem but before starting the video I will request you if you like my video do subscribe my channel and for understanding full concept of this ugly number problem do watch it till the end of the video so let's start ugly number problem so what are ugly numbers a real numbers are positive numbers whose prime factors only include 2 3 & 5 so I can factors only include 2 3 & 5 so I can factors only include 2 3 & 5 so I can say any ugly number can have 2 3 & 5 or say any ugly number can have 2 3 & 5 or say any ugly number can have 2 3 & 5 or the numbers multiple of it right so if I take first 10 ugly numbers 1 2 3 4 5 6 8 9 10 12 so these are the first 10 ugly numbers and if we have to verify are they ugly numbers or not one is an exception which is a typical ugly number why I said this as an exception because it is neither the multiple of two three not five now if I have to verify whether twelve is an ugly number or not I will take out its factors it will be 2 into 3 2 to the power 2 into 3 to the power 1 so 12 is a multiple of 2 and 3 or I can say 2 & 3 are the factors of 12 now if I say 2 & 3 are the factors of 12 now if I say 2 & 3 are the factors of 12 now if I want to see whether 14 is an ugly number or not let's take out its prime factor 2 seven here if I see two is a ugly number but seven is not a multiple of either two three or five so we can say forty is not a ugly number so basically an ugly number we are getting two types of questions first check if number is ugly or not second find a net ugly number so to check whether number is ugly or not which is also a question of leak code number 263 let's see how we can take out as I told you the definition of ugly number is the number which has prime factor two three and five or the multiple of these numbers so let's take these numbers as factor and here we need to keep two things in mind first one is typically treated as a gleam number and the second thing input should be within 32 bits signed integer range so it should lie within 2 to the power 32 minus 1 hence whenever we get a value let's say 14 we will take the factors which are 2 3 and 5 and the number is 14 here we will keep dividing it with these factors if we get remainder 0 return true or else return false let's say we have the number 14 so first we will divide the number with 2 so 14 mod 2 is 0 yes then so as we divide the number of the - we got 7 next we will take 3 the - we got 7 next we will take 3 the - we got 7 next we will take 3 is seven divisible by three No then we will check whether 7 is divisible by five no hands 14 is not a ugly number let's check whether 15 is an ugly number or not here this is a brute force solution where I have number 15 first I will take the factor 2 and we'll make 15 mod 2 is 15 divisible by 2 No so here we will take the other factor 3 is 15 divisible by 3 yes here we got 0 so after dividing 15 by 3 we got 5 now we will check the next factor whether 5 is divisible by 5 yes it is divisible by 5 so here after dividing 5 by 5 we got one so with this we can say 15 is completely divisible by these factors so 15 has the prime factor of 2 3 5 hence 15 is a ugly number that's what a definition is so when we make the program by brute force first we need to take factors 3 factors 2 3 & 5 need to take factors 3 factors 2 3 & 5 need to take factors 3 factors 2 3 & 5 and then we will make a loop for F in factor because we need to hydrate it one by one let's say here we have is equal to 15 then we will keep hydrating for numb if now is divisible by F which are these factors we will get into it and we will get the value divided by F and here at last we will check if num is equal to 1 return true else real time for and here we will have the base condition if num is equal to 0 it will return false if we come to its time complexity will be order of n square and the space complexity will be order of 1 this is just brute force for finding out whether the number is ugly or not now if I get the question find NF ugly number this question I will solve it by 2 methods method 1 will be the nape solution for each prime factor first of all I will get n top ugly number for each prime factor as here I am going to find out and ethically number let's say I want 4th ugly number so here I will need only for top ugly number for each prime factor so prime factors are 2 3 & 5 so factor so prime factors are 2 3 & 5 so factor so prime factors are 2 3 & 5 so for each prime factor I will get top ugly numbers so for 2 it is 2 4 6 8 4 3 6 9 12 4 5 10 15 20 second merge them in a single list whatever the values I have here the ugly numbers watch them in a single list which are two four six eight three six nine two then there are four top ugly numbers for each prime factor so for number of to four ugly number of three and four ugly number of five as like this and the third operation will be I need to sort them and here whatever the an ethically number will be there I need to find out in this final list one so here I needed fourth ugly number here I will get the fourth ugly number five this is one way of finding any table number it has time complexity here we are sorting it order of n log N and we are going to each number to the list so greater than order of n log N and coming new space complexity we took a space of list so it will be order of n now we will see how we can decrease this time complexity so for this we will use dynamic programming approach first of all I take the final result in a list and in this list I will have one by default because one typically ugly number and then I will take three variables I 2 I 3 and I 5 which will be having 0th index these are the index over you with this I will also have three variables next to next three and next five so this is our final result value all right over here now I will delete one so here I can say 1 is 1 0 to index and here next to will be having multiple of 2 next 3 will be having multiple of 3 and next 5 will be multiple of 5 and this will be result of I do which is 1 0th index this will have result of I 3 index and result of I for index and on I do I agree I 5 this will be I are initially at 0th index and here we will cap a variable next which will have minimum of all these 3 so initially I - minimum of all these 3 so initially I - minimum of all these 3 so initially I - I said 0th index so result of 0 is 1 so 2 into 1 will be 2 then result of I 3 0th index will be 1 so 3 into 1 will be 3 5 into 1 5 as all I do I greet I 5 is at 0th index here we will calculate the value of next among these 3 whichever is the minimum will get into next so next we will get the minimum value to this 2 value we will append a result so they'll be caught one index and whichever value will be here the index will be incremented by 1 so here I got one here there is a change in I do index I got I do as one-on-one I do index I got I do as one-on-one I do index I got I do as one-on-one index we have to so result I 2 will be 2 into 2 will be 4 now we will check whichever value will be minimum among 4 3 5 will be in the next variable and this next will be appended do please as we took the value from I 3 this I 3 will be incremented by 1 now I 3 is on one index and on 1 there is a value 2 so here I will get 3 into 2 will be 6 now let's say in our question we have to take out 930 number so for the next we will see whichever minimum then you will be there among 4 5 6 it's 4 so here I will get 4 and as we took the value from next to I 2 will be incremented by 1 so that we got to index now on to index we have 3 so 2 into 3 will be 6 now we got 2 6 & 5 now we will be 6 now we got 2 6 & 5 now we will be 6 now we got 2 6 & 5 now we will check next among 6 5 is the minimum number and we took the value from i-5 so number and we took the value from i-5 so number and we took the value from i-5 so that I fight incremented by 1 so you require 1 so for the one index the value is 2 so 5 into 2 can be gone this time now when we need to calculate the minimum between 6 and 10 where we have two sixes over here so what I'll do I take six because anyhow 6 is the minimum value here as 2 and 3 both are the factors of 6 so I will increment both by 1 so for Aitu it's third index which has the value for 2 into 4 will be 8 & 4 i three its 2 into 4 will be 8 & 4 i three its 2 into 4 will be 8 & 4 i three its second index which is 3 so 3 into 3 will be 9 now among 8 9 10 it is the minimum value I will copy here and we may change in the I 2 as I do will be incremented by 1 now we will check on fourth and X we have 5 so dough into 5 will be 10 then among 10 and 9 here we have two tens but minimum value is 9 so I will right over here and we'll increment I 3 by 1 so here I got third index so forth third index we have value for fourth reason well now this time we got to 10 which is the minimum value I can write over here and make changes to I - I over here and make changes to I - I over here and make changes to I - I will increment for I do index and I 5 index because 10 has prime factor 2 and 5 now 5th index is 6 so doing 2 6 will be 12 and here i 5 is 1 second index which has the value 3 so 5 into 3 can be 15 and here we wanted 930 number as the result started from 0th index that means 8 then we are 9th value so now if we see its time complexity v bar i creating each value once so time complexity will be order of N and coming to space complexity will be also father of and as we took the help of one more list now let's see how we can make a program for this dynamically so here I have my dynamic program for an ugly number where I have n as input argument initially I have taken a result list with one appended in I 2 I 3 I 5 0 initialized then I will take a for loop and we'll keep on iterating the value so that I can get all the multiples of 2 3 and 5 and then I will have the minimum value out of these three so that it can be appended to the result and thereafter I'll be checking each value if I took the value from next to I 2 will be incremented by 1 if it is from next 3 I 3 will be incremented by 1 and if it is from next 5 I 5 will be incremented by 1 and then the last value the NH ugly number so 4/9 the last value the NH ugly number so 4/9 the last value the NH ugly number so 4/9 ugly number here I got 10s like this so this is how we can solve the problem by brute force as well as dynamically after that there comes a concept of superbly number let's discuss this in next video so hope you like this video please give a like to my video and please subscribe to my channel thank you
|
Ugly Number
|
ugly-number
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.
**Example 1:**
**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3
**Example 2:**
**Input:** n = 1
**Output:** true
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Example 3:**
**Input:** n = 14
**Output:** false
**Explanation:** 14 is not ugly since it includes the prime factor 7.
**Constraints:**
* `-231 <= n <= 231 - 1`
| null |
Math
|
Easy
|
202,204,264
|
110 |
Hello Hi Guys Welcome To Record Mid-Day-Meal Solving Questions Balance - Problem Channel Subscribe To 999999999 Follow Then Balance Factor Good Wishes Left And Right The Balance Put 90 Function Arrangement Height p.m. Hey friend also down below Guru personal or not I button zero otherwise sitam oneplus maximum left or right a 2016 border height new * writer condition vitamins 2016 border height new * writer condition vitamins 2016 border height new * writer condition vitamins loot-loot difference light off do jhal ki naxal strike immediately give it to scientific members subscribe for example that Electronic your friend fear till your a that in Gautam approach will go to the lowest level and travel up the phone that I will also have height function that in your will have that Snowden channel this committee formation 0n otherwise past's semen left right in this Page To Show That Similarly It Will Give The Height Of Right A Inside Which Balance Page Straight Pimples That Be Different For You Left Side Is That Boat Vinod A Balance Factor Is Greater Than One Needs To Return To Are Call To Theorem In False Cases - Pandit Are Call To Theorem In False Cases - Pandit Are Call To Theorem In False Cases - Pandit aur teen thug hai a written on oneplus max left and right ki ab to vacancy hair oil ko great - ki ab to vacancy hair oil ko great - ki ab to vacancy hair oil ko great - close check weather left and right this also not able to - - - - a the this also not able to - - - - a the this also not able to - - - - a the walking hear bhi nahi chun right the written statement ho Gayi aur witch food gayi jo hello how to root is note ki value - hello how to root is note ki value - hello how to root is note ki value - features - adware a ki Bigg Boss safar trans ho ki aapke body submit school and support sab natak hai ki a
|
Balanced Binary Tree
|
balanced-binary-tree
|
Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
104
|
836 |
hey what's up guys Nick white here I did tecnico ting stuff on Twitch in YouTube do the premium way codes on patreon ask me anything in my disk or try to get back to everyone this is a rectangle overlap question it is easy got some likes here it was pretty good cool sometimes in an interview you might be asked something about math because software engineering does involve math depending on what you're going for you know software engineering specifically there's a little bit of math involved sometimes a rectangle is represented as a list x1 y1 x2 y2 where x1 y1 are the coordinates of the bottom left corner x2 y2 are the coordinates of the top right corner two rectangles overlap if they're err if the area of intersection is positive to be clear two rectangles that only touch at the corner or edges do not overlap ok two rectangles that only touch at the corner edges oh you mean if they're like bordering each other basically okay given two axes aligned rectangles return whether they overlap so rectangle one zero two rectangle 2 1 3 what do we notice about this and why is it true why do they overlap well we noticed that these numbers are greater than these numbers and these numbers are less than these numbers and that's pretty much the answer right there just looking at it but for math problems I do like to visualize so I wrote this out while I was trying to solve it just so I could see what was going on this isn't in the discussion or anything I just like to see what's going on with this so let me just show you the answer basically let's say we have a rectangle it's anywhere on a grid this is just a rectangle it could be anywhere on a graph or whatever so this is somewhere this will call it rectangle 1 rectangle 2 intersects with this rectangle if it is let's look at the for though different ways it could be in the top left of this rectangle so the bottom right corner would be intersecting right here it could be to the top right of this rectangle his burps are in the bottom-left corner his burps are in the bottom-left corner his burps are in the bottom-left corner could be intersecting with it could be down here in the top-left corner can be down here in the top-left corner can be down here in the top-left corner can be intersecting with it or it could be down here in the you know the top-right down here in the you know the top-right down here in the you know the top-right corner it could be intersecting with it you know those are some possibilities right there you know it could be a little bit more up there but like generally that's how it works we're not worrying about a perfect overlap but in this problem they don't account for that but here's what the idea is if it was in any of those positions the top-right any of those positions the top-right any of those positions the top-right coordinate for this new overlapping rectangle is always the X and y values for the top right is always gonna be greater than the bottom-left of this greater than the bottom-left of this greater than the bottom-left of this specific rectangle so you can see here the overlap right at the top right corner it's right here greater than these coordinates over here the top right corner somewhere up in space over here it's greater than these coordinates over here the top right coordinates somewhere up in space over here it's greater than these coordinates over here top right coordinate still greater than these coordinates so it's always greater and the whatever what was the other thing it was I already forgot the bottom oh yeah the bottom left coordinates of the rectangle is always less than the top right of the this rectangle so the overlapping rectangles bottom left see this is always less than this bottom left somewhere down in space less than this bottom left over here that's the whole idea so we can just write that out in a long boolean expression so it's return rectangle rect rec oh it's rec 1 of 0 so rec the X the starting x-value of the first the starting x-value of the first the starting x-value of the first rectangle is going to be less than the ending rectangle value of the second rectangle as well as the starting rectangle point of the what am I saying they're starting the starting y-value the starting y-value the starting y-value the starting Y value is going to be less than I just had to think and make sure I was right about what I was saying but yeah I am right is less than rec 2 of 3 so the ending Y value and then we just have to do the other so this what this says is that the first coordinates of this are less than the ending coordinates of the overlapping rectangle which we discussed and then the beginning right the overlapping rectangles beginning coordinate so rec 2 of 0 has to be less than rec 1 of 2 because that's the ending the beginning coordinate has to be less than the ending coordinates of the other rectangle and rec sorry let me expand a little bit in rack 2 of Y so rec 2 of 1 has to be less than rec 1 I didn't get that much sleep last night either so that might be affecting my mental thought process right now Rock 2 of 1 has to be less than rec one of through 3 yeah so this just makes sure that what I said is true think this will work if I submit if I also delete all that crap there we go it works ok that's the whole thing to check for the intersection like I said this checks the B's are the x and y values of the beginning points of this rectangle and they have to be less than the top right point of the ending rec tank overlapping rectangle and then the beginning point of the overlapping rectangle so these are the beginning points of the overlapping rectangle have to be in less than the ending points of the underlying rectangle that it's overlapping there you go that's it hopefully that makes sense to you sorry I don't have a pen and marker that I do you know I'm not doing the Khan Academy cool thing someone can comment below if you know like a link to do the little Khan Academy animations maybe I could start doing those but uh I mean I thought you know I thought it made sense the explanation so thank you guys for watching you know of course I had that error when I had you know this so you know I can't get by without an error but thank you guys for watching appreciate you guys I love you guys and you know thank you and I'll see you in the next one
|
Rectangle Overlap
|
race-car
|
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is **positive**. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles `rec1` and `rec2`, return `true` _if they overlap, otherwise return_ `false`.
**Example 1:**
**Input:** rec1 = \[0,0,2,2\], rec2 = \[1,1,3,3\]
**Output:** true
**Example 2:**
**Input:** rec1 = \[0,0,1,1\], rec2 = \[1,0,2,1\]
**Output:** false
**Example 3:**
**Input:** rec1 = \[0,0,1,1\], rec2 = \[2,2,3,3\]
**Output:** false
**Constraints:**
* `rec1.length == 4`
* `rec2.length == 4`
* `-109 <= rec1[i], rec2[i] <= 109`
* `rec1` and `rec2` represent a valid rectangle with a non-zero area.
| null |
Dynamic Programming
|
Hard
| null |
1,957 |
hey guys peng here so today we're gonna talk about question one for bi-weekly contest which question one for bi-weekly contest which question one for bi-weekly contest which is the past saturday the lead character to make fancy string defensive string is a string no three consecutive characters are equal given a string s delete the minimum possible number of characters from s to make it fancy return the final string after the tradition it can be shown that the answer will be always unique so let's look at example what's a fancy string so basically a fancy string is you can have three character consecutive characters being the same in this case e you know there's three consecutive e so we cannot allow that happen same thing here so three a's or four a's we need to minimize to two a's so what's our algorithm look like so basically we'll create a previous variable keep track of the previous character of the current character we are now we are trying to look at and we carry the string in a new string and then we initialize with the first character of the given string s so we'll put the string s by checking the first character in inside the new string we are creating and we have a variable called frequency we keep track of the number of same character appears and then we set it to one first you know so we need to loop through each character from in this character of inside a string given string from index 1 to index string length if we see the current character inside the string s is equal to previous character we incriminate frequency if it's not equal we set the previous character to current character the value we need to change the volume and then we set we reset the frequency to one if frequency is less than 3 we keep adding the character to the string to the new string we are creating and at the end we take a new string okay so it's pretty straightforward you know here's the previous character we set it to the given string and at character 0. frequency keep count of if the same keep calm the same character how many times it appeared new string with string viewer is easier so we append previous we will append the first character to the new string we look to the each character of s if the previous is equal to the current we it means we appear you know we appear twice so we add the frequency to but not add the frequencies to one frequency equal to figure c plus one right and else we reset the frequency to one and then previous equal to current if frequency is less than three we append those characters you know if frequencies at three we don't append because we it means like it's count these three consecutive characters appear and at the end after the loop we return the new string so let's look at it should be working yeah it should be working so here the time complexity is here we want to s so complexity is over right because we need to run to the length string length then space will create another new string so this one 2 also alright thank you guys have a nice day
|
Delete Characters to Make Fancy String
|
closest-room
|
A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**Input:** s = "leeetcode "
**Output:** "leetcode "
**Explanation:**
Remove an 'e' from the first group of 'e's to create "leetcode ".
No three consecutive characters are equal, so return "leetcode ".
**Example 2:**
**Input:** s = "aaabaaaa "
**Output:** "aabaa "
**Explanation:**
Remove an 'a' from the first group of 'a's to create "aabaaaa ".
Remove two 'a's from the second group of 'a's to create "aabaa ".
No three consecutive characters are equal, so return "aabaa ".
**Example 3:**
**Input:** s = "aab "
**Output:** "aab "
**Explanation:** No three consecutive characters are equal, so return "aab ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists only of lowercase English letters.
|
Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time.
|
Array,Binary Search,Sorting
|
Hard
|
2179
|
1,508 |
hi my name is Ray and today I'll be explaining question 2 from the codes by weekly contest 30 range sum of sorted sub-arrays ohms so the question gives sub-arrays ohms so the question gives sub-arrays ohms so the question gives you an input integer array the length of the array and two boundaries and you have to first calculate all sub array sums and then you need to add the sub array sums given the two boundaries and I know that sounds a little bit confusing but let's just hop in straight into example one so I can explain the solution so example one gives you an input integer array of 1 2 3 4 you can see the length of the array and it gives you 2 inclusive boundaries so the first part in explanation says all sub array sums are these so let's first find all sub arrays ohms and the way I did that was by creating an ArrayList to store the sub array sums after that I simply used two pointer brute force to add all subarray sums to the ArrayList and I know that this isn't the most efficient way but because I was in a contest and it was timed this was a solution that I came up with after that we need to sort the ArrayList I can show you what this is an example in example one so once we add all sub array sums to the ArrayList we would have this and then after that we would need to sort the ArrayList so that would be 1 2 3 4 5 6 7 9 and 10 I think yep now that the ArrayList is sorted we need to use any type of loop I use a for loop starting at left index and ending at right index to add the elements in the array list and note that the left index and right index in this question are inclusive so because it says left equals one we don't start at element one we start at the first number so which would be element zero and right equal five we would be ending at element four so that means we would say 1 plus 2 Plus 3 plus 4 that's 1 2 3 4 5 and that equals 13 and that's what we'd return an integer value in example 1 being 13 so that's the solution for question 2 if this video helped you in any way please like and subscribe and if you have any questions just leave them down in the comments below as always I will leave a link to the code down below thanks and I'll see you in the next video
|
Range Sum of Sorted Subarray Sums
|
longest-happy-prefix
|
You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed from 1**)_, inclusive, in the new array._ Since the answer can be a huge number return it modulo `109 + 7`.
**Example 1:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 5
**Output:** 13
**Explanation:** All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
**Example 2:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 3, right = 4
**Output:** 6
**Explanation:** The given array is the same as example 1. We have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
**Example 3:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 10
**Output:** 50
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 100`
* `1 <= left <= right <= n * (n + 1) / 2`
|
Use Longest Prefix Suffix (KMP-table) or String Hashing.
|
String,Rolling Hash,String Matching,Hash Function
|
Hard
|
2326
|
270 |
hi coders today we will solve a problem called as closest binary search tree value problem number 270 or lead code till now we have applied priority search on a sorted array where we try to find the target element a number range where we try to guess a number higher or lower than a given value and an unsorted array where we try to search for a target element in a rotated sorted array and a sorted array of unknown size in this video we'll try to apply binary search on a tree a special type of tree called as pst this product has been asked by facebook and amazon the past six months so let's go through the problem statement first we are given a binary search tree that is we are given a loop node and we can access all the other roots in the tree using that we are also given that the binary search tree is non-empty tree is non-empty tree is non-empty that is the root would not be null because there would be at least one value in the tree besides the root note we are also given a target value and the given value is a floating point what we want to do in this problem is to return the node value in the tree which is closest to the target the first approach that is coming to my mind is a recursive linear scan we travel to all the nodes in the tree recursively and return the node value which has the minimum absolute difference with the target value which is 5 in this case the time complexity of this approach is o n and the space complexity is o and that is the recursion stack the second approach that is coming to my mind is to do a recursive inorder traversal because if it travels a binary search tree in an order fashion it will be sorted and we can terminate the travel so whenever we get the value greater than the target that is if we see the inorder traversal we will have two answer candidates the upper bound of the target value that is eight here and the value before the upper bound of the target that is five so either of them would be the answer here also the time complexity would be omen and the space complexity would also be owen because it's a recursive traversal now if you think in the direction to optimize it further let's see if we can use any property of binary search tree to reduce the time complexity to logarithmic we know according to clrs any node value in a binary search tree is greater than or equal to the maximum of the left sub tree and less than or equal to the minimum of the right subtree so let's see if we can reduce the search space using this we are given a target value of 6.12 we are given a target value of 6.12 we are given a target value of 6.12 the node value is 5. all the values here would be less than or equal to 5 and if we choose any value here the difference would be greater than 5. so if the target is greater than the node value we can reject all the values of the left sub tree and a search space would be reduced to the node value in the right subtree if the target value was 4.12 which is if the target value was 4.12 which is if the target value was 4.12 which is less than the node value by this similar logic we can reject all the values of the right subtree and reduce our search space to the node value and the left subtree if the target value was 5 we could have terminate our search at the node value itself because the absolute difference would be greater than equal to zero and it cannot be less than zero so we don't need to traverse in any direction the time complexity would be o log n base two because we are trying to reduce the search space by half at every step and the space complexity will be over because we'll follow an iterative approach now let's see how we'll alter template one as we discussed earlier if the node value is equal to the target value we can break from the loop and return the node value that is the target else if the target is less than the node value we can shift our search range to the left else we can shift it to the right here we have typecasted the node value to a double because here we are trying to compare a node value which was initially an integer to a double value now that we have a basic understanding of what's going on let's try to write in our code we initialize the answer to root value that is 5 here we have a pointer called node pointing to the root node i'll represent it using n since the node pointer does not point to null we'll go inside the loop we'll initiate the node value to 5.0 we'll initiate the node value to 5.0 we'll initiate the node value to 5.0 since 5.0 is not equal to 6.12 we will since 5.0 is not equal to 6.12 we will since 5.0 is not equal to 6.12 we will not enter here absolute of target minus node value is equal to 6.2 minus 5.0 is equal to 6.2 minus 5.0 is equal to 6.2 minus 5.0 which is equal to 1.2 which is equal to 1.2 which is equal to 1.2 the target minus answer is also 1.12 the target minus answer is also 1.12 the target minus answer is also 1.12 will not update answer and answer will still remain 5. since target 6.12 is greater than the since target 6.12 is greater than the since target 6.12 is greater than the node value that is 5.0 node value that is 5.0 node value that is 5.0 we'll compare the target value to the north value add a 6.2 to 5.0 north value add a 6.2 to 5.0 north value add a 6.2 to 5.0 since the target value is greater we'll shift our search range to the right and the node pointer will now point to 9. since the node pointer does not point to null we'll go inside again we'll update the node value to 9.0 we'll update the node value to 9.0 we'll update the node value to 9.0 since 9.0 is not equal to 6.12 will not since 9.0 is not equal to 6.12 will not since 9.0 is not equal to 6.12 will not enter here target minus node value that is the absolute of 6.2 minus 9 absolute of 6.2 minus 9 absolute of 6.2 minus 9 which is 2.82 which is 2.82 which is 2.82 is greater than 1.2 so we'll not update is greater than 1.2 so we'll not update is greater than 1.2 so we'll not update our answer candidate we'll come here since the target value is less than node value we'll shift our search range to the left that is now the node pointer points to it since the node pointer does not point to null it will go again inside it will update the node value to 8.0 it will update the node value to 8.0 it will update the node value to 8.0 since 6.2 is not equal to 8 it will not since 6.2 is not equal to 8 it will not since 6.2 is not equal to 8 it will not go inside absolute of target minus node value that is 8 minus 6.2 that is 8 minus 6.2 that is 8 minus 6.2 is equal to 1.82 is equal to 1.82 is equal to 1.82 which is still greater than 1.2 so which is still greater than 1.2 so which is still greater than 1.2 so answer won't be updated target is less than the node value so our search space will move to the left now node will point to a null value since node is equal to null we won't enter here and return the answer value which was 5 so the output is 5 that's all for this video if you like the video please hit the like and subscribe button if you have any questions please leave in the comment section below thanks for watching till the end
|
Closest Binary Search Tree Value
|
closest-binary-search-tree-value
|
Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest.
**Example 1:**
**Input:** root = \[4,2,5,1,3\], target = 3.714286
**Output:** 4
**Example 2:**
**Input:** root = \[1\], target = 4.428571
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 109`
* `-109 <= target <= 109`
| null |
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
222,272,783
|
1,010 |
hello everyone hope you all are doing well so i am back with another latecode daily challenge and it is late call number 1010 pair of songs with total duration divided by 60 and it is a medium level question and i also feel the same so you are given a list of song with where the ayat song has a duration of time i second return the number of pair of song for which the total duration in second is divisible by 60 uh formally we want the number of indices i j such that i is less than j with time of i plus time of j mod 60 will equals to zero okay so i will explain this part or example part in the explanation part so let's see that what is the constant so the constant is uh time dot length can be from 1 to 6 into 10 to the power 4 and time of i is from 1 to 500 okay so let's go through the explanation so this is the first example and this is sufficient to understand you all the conditions okay so first of all you can see there you are given some times like 30 20 1540 and the output is three okay so you have to take two you have to pair up this all numbers such that uh like a plus b modulo of 60 should be equally equals to zero okay so how can you solve it if you see the example you can see that uh that 30 150 give 120 and 180 and one it is divisible by 60 then 20 100 so it is 120 it is also divisible by 60 and 20 and 40 is 60 also divisible by 60 okay and if you notice it you can see that here uh the first elements position is always less than the second element position okay and you cannot take same element you have to always take the different elements like i should be always less than j is the specifically shut there so how you solve it so what they said now like you have to take two number and sum them so that it is divisible by 60 okay so if i take 140 so 100 plus 40 is 140 and demander will be like 20 okay so it is not divisible so you have to take all the pair which is divisible first of all you need to find out the module of all this value okay so our new array will look something like 30 20 then 150 modulus 60 is uh 30 again then it is of 40 and again it is 40 okay now if i map them like earlier this is 30 this is 20 this is 150 this is 100 and this is 40 okay so if we map them you can see that um one is this 30 and 30 okay these two let me change the color one is this and this one pair then you can see this and this again this and this okay so there are three pair so by doing this you can find out all the pair and how we'll find it we can take a map okay we can take a map and i just store it as key value pair then i will travel from left to right and i just look like here it is 30 okay so i just take a variable let's say it is t and we just do 60 minus 30 okay because we have 30 and we need another of another 30 so it will give 30 so we have earlier we have one number is 30 and we need another this number okay so this is this can be b and this can be a okay so we just search it for in the map if it is there we can uh count the variable like we can increment our cnt account variable and initially it is zero so we can increment it okay so first i take 30 and i just minus it and i get at 30 so i will search in the map okay is the 30 is present so there is no 30 present so what will i do i just put this uh this value here so 30 and i increment it to 1 okay now next i just come here and i just took 20 so next is 60 minus 20 so it will give 40 then i will search for 40 is there 40 percent no so i will not increase increment the account variable and i just put it here for this with this variable so i can put here 20 and again one then i go to 30 again here then it will be 30 sorry it will be 60 minus 30 and i just take 30 okay so i will search and i get a 30 year so it's its count is currently one so i what i do i just simply increment the count by this number okay this number means here currently it is one so it will be one okay increment by it one so the count variable change to one now i again increment i again put this value so it will increment the one to two okay then i just uh go through the 40 okay so then here 40 then 63 minus 40 will give you 20 then i will search it for 20 search 20 here so i get a 20 and it its value is one so i again increment the count variable by one and it will be now two okay now again i just put 40 inside okay then again after this i will go here and again 40 then i again for 60 minus what is 20 so i again search for 20 and 20 is one okay so i just again increment the count by this value and it will be three okay then i just increment 40 you can get three here and the answer is also three and here the important step is to take the modulo first okay this part is very important this is the code here i just simply mod all the element by 60 okay as i told you here to mod all the element by 60 then again i take a count variable and i take a map okay then i just uh do the same thing i just take a f variable and just minus the current element with it and if f is equal to equals to 60 it is just a base case like something if it is 16 so you have to find zero because when you when we mod 60 if there is a variable 60 and we just mod it with 60 so it will give you zero okay so that's why we just found 0 other than this 60 if there is any element okay so just we just simply try to find it out okay so you have to add the frequency you don't have to increment the count you just have to increment the frequency if the current frequency of that element is three then you have to increment it by three okay then i just simply put all the element in the map one by one okay means uh after processing i just put uh that element in the map as i show you here okay then i just return the count value okay so let's submit it i will provide my solution link and the question link in the description box so if you need you can check it out and so see you tomorrow bye
|
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 |
143 |
ex girl give it to ya wait for you to get it on your own and stole the liver yo what's up nerds welcome back to tee time with your favorite software engineer if you guys haven't already check out my channel subscribe smash that like button because i know you guys are gonna like this video you're gonna learn something so um today i'm going to reorder lists medium problem leak code i know there's other youtubers who ever already done videos on this but i'm going to show you guys a different solution that maybe you haven't thought of it's not as efficient but it's easier it's a lot less code i think it's easier to understand so let's jump right into the description given a singly linked list l0 through ln reorder it so to l0 ln l1 ln minus 1. so basically we're doing first last and then the next one and then the one before the last so we have one four two three so pretty simple that's the problem i'm going to go over on this whiteboard so let me move this out of the way a little so um what we're going to want to do is we're going to want to somehow reach the last and the second class we're going to want to have pointers there so that we can move them while we maintain our pointers at the beginning so if we put say second last here and last and then we just move them along eventually last we'll end up here and second last we'll end up here and then we can just adjust the pointers so we know that we're just going to have one at first and then we're going to have last we have last so we just put um head.next equals last we just put um head.next equals last we just put um head.next equals last um i'm going to label that differently head.next equals last um but the first we want to set a like a temporary pointer to the head to head.next so we're going to do temp to head.next so we're going to do temp to head.next so we're going to do temp equals head dot next and we need to do this before we change head.next before we change head.next before we change head.next so technically we're doing head.next so technically we're doing head.next so technically we're doing head.next um equals temp but i was just showing you guys it in the diagram up here um so head.next or temp um so head.next or temp um so head.next or temp is right here is temp is right here so we have temp so then we can just do uh last.next and this is getting sloppy last.next and this is getting sloppy last.next and this is getting sloppy sorry guys last.next last.next last.next equals temp and then um so we still have three here but we're going to want to do second dot second last dot next set next equals temp so i believe that so we have head.next so i believe that so we have head.next so i believe that so we have head.next equals last you know let's just go right to the way uh coding um i started to get messy but i hope you guys understand the main concept so our base cases is if head equals null or head.next equals no or head.next equals no or head.next equals no or head dot next equals null then we're just going to return let me zoom out because we don't need to change anything so let's go ahead and create our pointers so we have last equals head.next last equals head.next last equals head.next and we have second last equals head and so then we're just going to loop through while last until we get to the end so while last.next last.next last.next does not equal null we're just going to iterate both of those so last equals last dot next and second last equals second last dot next okay so now let's go ahead and do what i was writing before so snow temp equals head.next temp equals head.next temp equals head.next head.next equals um head.next equals um head.next equals um so head.next so head.next so head.next equals last so we're doing head this is head.next and we're going head this is head.next and we're going head this is head.next and we're going to set it equal to last which is what we want and then we need to do head.next equals and then we need to do head.next equals and then we need to do head.next equals temp oh no head dot next temp equals head dot next so i did that oh i did that so and then head dot next equals not temp it's last this is last that's why i was confused so then second um it's not second last.next it's head.next last.next it's head.next last.next it's head.next so i was really no last dot next equals temp since this is the last so we're doing last.next is the last so we're doing last.next is the last so we're doing last.next equals temp i had it on the freaking diagram too last.next equals temp diagram too last.next equals temp diagram too last.next equals temp and then we just want to set um secondlast.next secondlast.next secondlast.next so second last dot next we want to point it there's nothing after it anymore because we moved last to the after head so we're gonna set it equal to null and second last dot next equals no and then so temp is now our new head because we already did one and four um so now we just need to do these three imagine if the list continued um the new head is right here at temp so we just this is basically a recursive solution so reorder list temp sweet and it works oh so it's really slow um run time-wise i'm so it's really slow um run time-wise i'm so it's really slow um run time-wise i'm actually not sure we're just looping through the list once so technically it's still o of n i believe the solution they provided is also o of n um i'm not sure why it's so much slower um and we didn't use any more data structures and that other than you know list nodes we don't those are just those are not data structures those are just nodes list nodes we need those anyways
|
Reorder List
|
reorder-list
|
You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000`
| null |
Linked List,Two Pointers,Stack,Recursion
|
Medium
|
2216
|
336 |
hello everyone welcome to learn overflow in this video we will discuss another little problem this is a palindrome pairs so this is a heart type problem and i'll say a really interesting one okay so uh we'll understand what this question is asking us to do and how we can easily solve uh this question okay i'll explain it to you okay so before moving on if you haven't subscribed to learn my vlog make sure to subscribe to learn how flow for regular netcode videos like the this says we are given a list of unique words okay make sure the words are given to us in our words array okay that's all of them are unique there's no repetition so that's our list of unique words and we need to return all the pairs of distinct indices i j so we need to written a pair of distinct indices that's the i and j this ing should be distinct not same okay in the given list uh so that the concatenation of the two words like quad i plus word j so this should be the format like quad i plus one g okay first word i then words j so if you concrete them this should be a palindrome that's the question we have so simply means uh simply means let's say there's like if i look into example two there's bat there's tab fine and there's cat so you find a bat and tab look here bat is uh back and then tab so if you write something like a b a t and then followed by t a b see you will see a palindrome being formed right this is a paranormal and in the reverse way if you find tab first and then write bat that would be also a paragraph so that's why the answer becomes uh like 0 1 like index 0 then index 1 followed by this one and the reverse case that is index one followed by index zero so index zero forward in this one and in this one followed by zero so this is the case that's uh answer but with the respect to cat like the third word given to us we cannot find uh any um any length to it like we cannot find any uh palindrome to it or any part of paladin to it okay so we know that cat cannot be fitted into any of those so that's not possible fine no that's the idea this is the idea we went ahead with and as i v a t a b and then t a b a these are the two parameters possible so this is the kind of uh expression they are asking us to find out so we need to return the indexes of the indices of them that is the zero one and one zero so the reverse is if possible we'll add all that also so uh there is a small case there's a small uh bike yes in this the case is the example three we should note into this if we find a single letter okay if i find a word of length one fine and then we should also look for if there's any empty character right there like words having zero length is also there or not if such cases are also there then we know that both of them is a uh palindrome okay we should look for that so that is the case we should keep in mind then uh if we look for the normalized case numbers of everything now see you will not find everything in this format directly you need to uh do some other operations so let's look into that so in example one you will find that case what's that it's like abcd and you find dcba so abcd and dcb you find like that's a case something like this then zero one and one zero if you just reverse uh dcba that's abcd so they define zero one and one zero right so there's the two cases that you can uh come across from them but look here look into this uh this three we have in this three we have a lls and then s for l and s if i put the singular s in uh front okay we find that this is an uh palindrome that's a palindrome being created right so that's why what we put left three uh like zero or like zero one uh two and then three fine and then four so there's the five elements that's zero one two three four and then so if i first put three then put two so that's why if see three two is the resultant uh in the in our outputs and then we found two four means starting with lls and then we find ssl so that's this one okay so that's from the palette we see that now the question is how we should uh look into this how we should find the solution to this now uh what you can continuously do is like take uh take any two different uh like keep on taking two different uh values or two different words uh just conquer them and check if there if those are palindrome or not but if you keep on doing that will be a huge thing why like if you just uh take two words like abcd and dcba and you want to you concarnate or you concatenate them and then you just put in a function of each palindrome function a different function in that you just find out whether it's a parent or not if you're doing that then you need to remember you there's a white line of 5000 so for each word okay there's 4 900 times maximum can go a check fine that check will go on so that should be huge cases and also while you are finding a palindrome you need to check for like a maximum 300 so maximum 300 and the other world being 300 calorie percent so maximum 600 can be the like the cases uh length you need to traverse but what is the case i'm trying to say it's like you took two words okay you took two words and then you concatenate them okay and then you put this whole new string into our new function is valid and then check whether this concentration is a paragraph or not so if you can do that but that's not the best way you can uh solve it like that's not the fastest way you can solve it now once you've got an idea that you need to do a fastest way now what you can do is like uh use some kind of uh corrections framework a hard presses if we use a hash map and store this strings all the word string we have okay and store these strings in our uh hash map what we'll do what will the idea is like we'll map each of the string which are indexes in the essence of that particular string so what will happen we'll take each of the string uh from the that hash map or from the word list and then we'll break it into uh parts what i mean let me just clear this thing say we got ssl yes uh like three ss are there and then ll right that's the thing now what we'll do we will find a substring of it will be doing a substring surface like uh first the whole thing then we'll uh through four of them there will be two three of them and once we took three of them okay so idea is not in the drake the idea is going in the reverse order remember sorry this i will go for ll then ssns fine so this is the idea now we'll take the reverse and we'll take that once we find an uh substring like lls so is that present in our like is that present in our particular uh word list and like if it is how we'll find out we'll directly find out based on the hashmap will give us the string easily okay so if this one is present in our particular word list then it will be like whatever the current position of this there is the i equation followed by like previously followed by the position we get from a hash map say uh by the gate method whatever we get so this comma i that gives our current result like we just do a substring like sll and then we find that's uh also present so this forms a substring for us so we need to check a few things in the beginning a few things is like without the substring is the rest uh like what we need to check is like without the substring is lls right without the substring is the rest is our uh palindrome if the rest is our palindrome that is in this case or the two s 2s is our tandem right so if uh see like our check for valentine is so less why without this uh lls we just subtracted all the long form like the huge elements and then check like only these two elements only the two elements are calendar yes they are fair enough so we just checked whether this rest is present in our uh wordless or not if death is present then we will put uh the word list value in the front and then put the rest in our end and the reverse is also true we need to check in the reverse way as it is say we got lls in the beginning right uh so in if we got a ll is only the other value in the beginning right so in that we will check uh like if this s is present in our substring or not okay if we find this is present then we will check if alias is present if i know ls is not present then we'll find lls is present or not no we find all the three are not present uh like the equal copy is not present so we once we find this s is present and we find that the rest of the string is sub palindrome we're just taking for the rest okay with shifting a like part of it different and we're just checking for the rest uh this is the whenever you're checking for the palindrome the amount is getting so less it's not checking for the all 300 the word length if there's a 300 watt length so you're not checking for the whole but with rather checking smaller values to get whether this is the parent of or not and if this is a calendar then we find the rest of the part this part whether this part is present not uh wired list or not if this is filled into a word list put that part in the beginning and then uh it should end with or this button so this is the whole idea of our question fine so i hope this is understandable so what do i'll quickly write a code for it just remember this formula what we're doing i will quickly write a quote for this and i'll again explain it to you based on the code how this idea that we are discussing over here how this idea works in our code okay you will see how fast this code can run okay let's write this code first and there you see this is like uh to 276 ms but if i just read on it if it will take much like it's around or 250 270 around that so this is kind of the fastest solution you can get so let's understand what exactly we did with the solution or not with the speed uh so first of all what it took we took a hash map uh this is storing a string an integer so all those words uh so we are doing something over here i'll discuss it and then we took a string a set the set is a three set okay that's why it's reset the three set is by default reset gives us a sorted order okay from lower values to the higher values by default as any got assorted whatever we are storing it is a story but and we are storing an integer okay and then we took n being word's length what is the string array that's given to us okay now what exactly we did over here we ran through all the words okay we ran through all the words i zero to till n and what we did uh we put in a word map that is words of i right and we just put uh i so that's like we just map with the word with this index in our hash map fine that's the name we by name we gave it a word map fine and then what is the state we are doing we just added the that particular word length okay whatever word is there that length is being added within our set so what it helps us in it will help us over here it will be helpful to helping us so what it will do what about the length of this say we're at this word so with this one got a length okay and we'll check for words that are length less than this right because we are doing the substring as i say we will be doing the substring and breaking it into the values so uh here it will be helping us check values less than this and what will be the benefit of that benefit will be like here there are five letters right uh five letters are there uh five characters in there but uh do we need to check all the characters we need to check for s that the of length one then we need to check a character of length uh three do you need to check for length two no because length 2 is obviously there not there in our words array right so there's a waste of time for checking uh that value so say there's a five data one and the next letter word are of like all the letters are length 300 so what's the point in like one letter is the five one the other letter is of 300 left okay i'm talking about each of the words okay so in that case if you keep on checking for all the values that will take a huge time right that will be questions of all the timing like all the times we have so in that case what we'll do we'll simply uh having a length like all the lengths we store in a state and that's it is storing in an order uh ordered man like in the lower values to get our values fine so what will happen in that way we will uh get so like equal value like where only those values our set will be going through only those values our substring will be going through all the only those values whose length or whose type values are already there in our words right so that's our point of taking a set over here next we took our answer this is our 2d list to release the final answer that we were supposed to return fine so that's the point we took our today list uh that's the answer now here we are starting at uh follow this follow is giving us the exact answer the whole fault so follow one follow order of it what we are doing in this we are simply running from i equal to 0 till n so 8 is the length of the word so we are taking one of the words each one by one and we're just going through that word fine first thing once you've got us going through it we just got the length of our current word what's right.length current word what's right.length current word what's right.length right and we're checking if our eye length is one okay if in case our words are length is one then what to do right if our eye length is one then we simply are battling of this condition so here you saw that the code gave some kind of wrong answers i'll tell you what happened so if i island this one we're checking uh that if our word map contains an empty string or not we got an a length one okay and we're checking for empty string so empty string is of length zero remember that so we got length one and we are checking for length zero okay then we find that if uh if it is the world map has such value then you get uh that the two indexes should be added that is the current i position uh like the current i whatever the fellow and the word map i value like one web dot get this value and the reverse one what not that get this value and the i equation so this is what we did and then we just say continue because we don't want to uh check this two values again and again right because the other key is it will be like uh this will come up and then it will uh written us this a right so we don't want to do this like in the else case if we don't find us empty string and the current length is 1 then we want to continue with we don't want to check because uh previously i didn't write this and you were getting an error based on that because the same thing was added two times right so that's the idea that's the way we just built it now what we need to do over here further if the length is not one we are moving further now simply we just reversed our string whatever the current word we have towards i we just converted into a string builder object and then string wind under reverse and then converted that to a two string that's being reversed to a string so string builder is much faster than reversing our strings fine so we're using string wheeler to the step time for that next comes an interesting part next part is we are considering if our word map contains this reverse the way is abcd is the current word and we reversed it and exactly we find that bcba is also there right if our wordpress contains the reverse then we are just and we are checking the word map.gate reverse is not i that the map.gate reverse is not i that the map.gate reverse is not i that the current value is not the same value like i mean uh what the point is they say there's exactly a value like uh a b and then c right uh ignore that a but anyways so uh if you have pointer uh something like a b and a right let's take something like that uh we got a and then we got b and then we got a so that's a word being in our array what's that fine so in that case what the reverse of this is also a b a right so we are just ignoring that part what we are doing what might not get reverse not equals i so that's index is not i if that is this is equally i then we are not getting uh like the uh palindrome pairs that's the palinder of the word itself is a paragraph right so we are considering that this is not the i and if that is not then you are doing answer dot add i and the what dot get refers our current position and the reverse firewall we got you may say why we are not adding the reverse as well as we are doing over here there's no need over here because the next time we got this uh dcba we'll do a reverse again fine the next one will be dcp and we'll do a reverse second and then we will uh find abcd and then we'll add that to our uh list fine so that's that is the idea that is the whole idea because we are not doing a replacement right next uh next what we're doing we moved on now this is the basic case of whether if the exact reverse is present now we need to break through this format like how we are doing it we are just moving through each of the sets uh each of the set in the integer so it's giving us uh like say currently there are lls fine currently the lls is the third string okay in the third string we got uh what we'll do we'll go for each in k instead so k instead has a one then three then four and then five right so we just have a check if k is equals length bring the current voltage for the current on the current one is three so we'll uh break that case so first we will come across one in our set so we come across yes right now if aluminum is printed with the function that is checking for the palindrome we took the reverse what is the lls reverse sll that's the reverse of this sll and you were checking if reverb if the reverse of this is uh palindrome like first of all what we're doing first of all we're doing length minus one is like length is uh returning three so length minus one is zero one two so that's what we got length minus one minus k is k we got one as the uh set value we got so whatever we're doing exactly is we are simply saying you have uh a reverse that is s l and then l fine so it's like zero one and two okay understand carefully what are you doing we are taking the palindrome of uh like zero okay we're thinking left zero and length minus one minus k that is three minus one that is a two so the whole thing and then we are doing uh minus k is one okay we got this and if uh if the thing is if we got uh this to be equal like uh zero one and two now three minus one minus two is like one fine so we got 0 till 1 so if we just uh check uh our palindrome function you will see it's like uh it's like left less than right so we got 0 till 1. so less than right is we are only checking for this one right only to checking for this s over here uh in our palindrome okay we're only checking for this in our parameter that's what we are doing in the final number if left less than right so uh we are checking for this s is this a paragraph yes so we are storing the rest that is the string one in reverse or substring length minus k so what is length minus the length is 3 minus k is 1 5 and are storing in it what we are storing 3 minus 1 that is 2 what is the substring 2 substring two is only this part okay so is it contains in on s1 no this is not containing our s1 right so we cannot uh find that uh like l is not there you know as uh like uh word map so this is not done fine now what do we need to do we will see the other way down other way around is see uh other way around is the reverse way the reversal is we took our uh same thing as uh ll so this is the word we have and we are checking for the palindrome in our k to l minus 1 k is our 1 okay 0 1 and then 2 so we are checking for the parallel from 1 till what is that l minus length minus 1 left minus 1 is 2 fine so we are checking for this values fine exactly we're checking for this part okay now what happening what's happening in this part uh if this is the palindrome yes zero l is a paragraph now what are we doing we are checking uh like this s2 is creating and reversed or substring because the substring is like doing what 0 till k is at this moment 1 right case at this point 1 so 0 till k is what exactly we are getting 0 till 1 that is this part is only we are getting so that's the s to the substring we got this part okay now we're checking if word map contains our s yes this is true what my conjunction is so what we did is implemented one dot gate s2 right so gate is to get this two is returning uh three right this is the third position value we got so what method gate is to returning three and what is the current i we have is two five so that's what we are getting what my dot get is three comma i that is two so what is the value three comma 2 is the value let's get array so first 3 then the i is 2 so that's what we are adding over here see this is the way the whole thing is work fine and the next time after k length increases to the next value it will be like a three is that because the length of the lls three and spine where k is length is three so we'll break it to it no a point going through it right so this is the way we are just finding the solution okay so i hope this is understandable of how we are finding a solution to this and how this particular method is working for us fine uh i hope this is exactly understandable and you know this is a pretty much faster solution as i said to 276 if i just try to submit again it might reduce because uh that liquid just so this is the particular way this uh c this went down to 149 is like the hundred percent faster you see the solution you see that what the type of solution is so this is one for ms and like fastest solution we have over here right so uh this is the way we are solving this question okay and that's how we are like uh storing the like we are actually getting through this problem i hope this is understandable and if you have any doubts related to this still you have any doubts make sure to comment them down i'll be happy to help you out in the comments as well and like this video and share it with your friends who are doing today's little problem and facing problems understanding this question i hope that will be helpful for them as well also subscribe to this channel for regular lit code videos like this hope to see you soon in my next video as well thank you all for watching this video thank you
|
Palindrome Pairs
|
palindrome-pairs
|
You are given a **0-indexed** array of **unique** strings `words`.
A **palindrome pair** is a pair of integers `(i, j)` such that:
* `0 <= i, j < words.length`,
* `i != j`, and
* `words[i] + words[j]` (the concatenation of the two strings) is a palindrome.
Return _an array of all the **palindrome pairs** of_ `words`.
**Example 1:**
**Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\]
**Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\]
**Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\]
**Example 2:**
**Input:** words = \[ "bat ", "tab ", "cat "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "battab ", "tabbat "\]
**Example 3:**
**Input:** words = \[ "a ", " "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "a ", "a "\]
**Constraints:**
* `1 <= words.length <= 5000`
* `0 <= words[i].length <= 300`
* `words[i]` consists of lowercase English letters.
| null |
Array,Hash Table,String,Trie
|
Hard
|
5,214,2237
|
775 |
hey everybody this is larry this is day five of the april eco dairy challenge hit the like button to subscribe and join me in discord let me know what you think about today's farm uh and yes i did get a haircut thanks for noticing with the two of you uh today's farm is global and local versions and keep in mind that i usually saw these lives i was a little bit slow just fast forward or watch it in a faster speed or whatever so okay so you have some permutations uh what so what are we trying to do okay the number of global inversion is just okay that and logon version is easy it seems like it's just next to it okay so we try to figure out whether this is actually this seems like it's easier maybe it wants you to return true if and only if the number of global inversion is equal to the number of local inversions um well so the thing is that yeah so the thing is that the number of logo inversion as this is the first thing i notice is that the number of logo inversions will always be equal to or bigger than the number of global inversion so in this problem the only thing i have to do is try to find an example of one case where i wait i don't know why this time limit have to be reduced but um because from my guess is that and this is maybe a little bit greedy is that we just have to find one instant in which there's a global inversion that is not local and then you're done because is it even more than that is it even yeah i mean and what i was also going to say is that if the two logo inversions that then that's already done um because if they're two local inversions you know let's say you have three two one uh that's two logo inversions but you can also say there's an extra global inversion in which uh the three is bigger than one right so there's actually only a very limited case um because now there's you know there's two logo and an additional three bigger than one for three global right so that means that it's already not true so we could even simplify or narrow down the problem a little bit further in that there's only one logo inversion it has to be in the answer so as long as there's two local inversion where we're um we're done and that could be done before loop and then my other question is can there be two global inversion without two logo inversions right because then that would be really easy um and i don't think so well yeah uh because one thing to also notice is that every number is unique because it's a permutation of o2 and minus one so because they're unique um you know there's some pigeonhole thing there where you know let's say there's something like no that's not true okay so i think this is a case where there's one logo but there's two gobo okay so then from then we just have to yeah i mean i think it's sufficient to do some sort of greedy in one but i mean it would have been well so yeah the couple of ways you can do it the uh well but you need other things one is just see if there's uh if there are two local inversions then you're done because the two low conversions in price at least three global inversions but in the case of one logo inversion um just to figure out this case is a little bit of a suffix minimum because for here i'm asking is the what is this is there a version that's at least uh two steps away right what's another possibility um well let's just say all right let's say this is maybe something like that um i'm just right now i'm just trying to think about the counter cases in my head and what my statement was and sometimes proofs are hard and what i do is try to as much as i can exhaustively come up with all the cases in which you know that may be countercases and you know almost like a proof by exhaustion if you will um and here i'm trying to think if this is this statement is correct where um where this problem reduces to is there an inversion of length of at least two right because in this case there's an inversion of length of at least two and let's say this is you know five for now there's an inversion of link's case of at least two well then no because then we can have this in which there's only one local new version no that's still good well so this has a length of two so then there's two possibilities right one is that this number is smaller than four which is a one say then that means that there's two logos as well or whether there's one logo but two global right at least two global and then the other case is if this is a three which i guess we ignore this for now um well then obviously there's already you know what we said earlier um and then the other cases if this is a five those are the three possibilities right it's more than both numbers it's in the middle between two numbers and then they're bigger than two numbers and there's also two global right because they both use this number so if any number that's bigger than two there's at least two global and if there's a number that's between them well there's a already you know this one adds one and it doesn't matter what this is um because if this is smaller this adds an additional one that is not a logo this one is the logo it's what it you know this gives you some sort of local inversion and then this gives you an additional one so i think that is a good enough answer um so then here we can just use the suffix min for that reason um again i'm a you know if this video is a the phone is a little bit weird to you i am trying to go for my thought process as i solve for a problem as i would during a contest or something like that or maybe even an interview so i hope that this is useful even if it's a little bit awkward and it's not explanationy because sometimes for me like i said for these sort of um sort of problems maybe it's a little greedy i don't know if this is discounts as greedy but let me try to figure out the property of these numbers and how it could fit together uh sometimes i just do exhaustive search uh manual search of like all the scenarios and how to break them up um so yeah so hopefully that makes sense so then now we can go n is equal to length of a for index in range sub um let's just say n minus one we go to zero which is very awkward in python looking but okay so then let's just say min is equal to infinity for now i just choose a big numbers should be okay um and then we go for it one by one um if index is greater than min we return true right otherwise we'll return first oh sorry is it which way does it go if it's okay so this is return force otherwise we may return true we might have to double check on this for one versus now because we definitely know that this is true what happens if it is not that means that if there's no that should be i think the contra this is the center of the country positive would be supposed to i think that should be okay um if index plus two is less than n we do mean is equal to min of the current min and a of index plus two um actually i guess we do this first that was kind of a useless taste oh um and as we said something like uh four one two three four five say um and in this case the answer should be yes well actually i think this will give me a yes but i think this is a wrong answer so i think i might have to um adjust it a little bit because there's one logo oh and then two global now that this should be right still um and then what we said about um having this as one and then let's just say this kind of okay uh whoops i forget the zeros always and we're going to fix that just by adding zero because that should not change the result uh okay wow that is not great so this is the third answer this is i return true because one is greater than zero but there's only one local one there's one local one and two global ones right oh yeah so that's hmm that's just an implementation error i guess do i have an off by one somewhere i guess so if this is zero they should look at two and then yeah oh whoops wow how does this even pass anything what i meant is this of course lately my mind has just been a little bit off like i'm saying the right things but even then uh okay so this is where i expect um it's a little bit awkward because i feel like i mean i've been doing this in contests too so it's a little bit uh discerning but uh okay so this looks okay let's give it a submit um to be honest i may be 60 confident before i look at the results but you know let's take a look oh cool um because sometimes because for me greedy problems are like that and that like i just have a higher degree of uncertainties i'm not sure um so this is actually a kind of a cute problem as a result um but you know hopefully you know if you watch other videos um they might just tell you the answer but hopefully me you know taking the time to actually go for my thought process as i would solve them i mean obviously if i was in the contest i might be much faster but i'm trying to explain it or have a way to articulate it um so hopefully this is a little bit more useful um i mean i don't think i have to go over the complexity too much this is linear uh because of the for loop and just checks and constant time oh sorry constant space because we just have like a couple of variables um yeah that's all i have let's look at the hint i want to save uh where can zero be placed in the ideal permutation what about the one um maybe there's another way to represent this um but i think maybe that's you know like i think probably we're expressing the same thing um i don't know why the time limit has to be reduced i guess n squared kind of works for this one if you're in java or something but yeah uh let me know what you think hit the like button to subscribe and drum and discord hope y'all have a great rest of the week uh yeah take care of yourself take your riders to good health and to good mental health i'll see you tomorrow bye
|
Global and Local Inversions
|
n-ary-tree-preorder-traversal
|
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`.
The number of **global inversions** is the number of the different pairs `(i, j)` where:
* `0 <= i < j < n`
* `nums[i] > nums[j]`
The number of **local inversions** is the number of indices `i` where:
* `0 <= i < n - 1`
* `nums[i] > nums[i + 1]`
Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_.
**Example 1:**
**Input:** nums = \[1,0,2\]
**Output:** true
**Explanation:** There is 1 global inversion and 1 local inversion.
**Example 2:**
**Input:** nums = \[1,2,0\]
**Output:** false
**Explanation:** There are 2 global inversions and 1 local inversion.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `0 <= nums[i] < n`
* All the integers of `nums` are **unique**.
* `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
| null |
Stack,Tree,Depth-First Search
|
Easy
|
144,764,776
|
790 |
problem I'm making a video and audio filing this is 790 Domino intramino tiling you have two types of tiles an end by a two by one Domino shape in a trauma shape you may rotate these shapes okay so you have this Domino shape like this of course the idea is you can rotate this little guy right so even though the shape is like this it could also be oriented like so and then you have this traumino complicated shape that can be rotated you know four ways you could have it like that you could have it like this what am I missing here and you could have it like this right so these are the four ways that you could have a traumino right so there's really four five six different shapes if you want to think about it in terms of like the grid cells that they occupy right of course these bottom four shapes are created from this traumino and these top two shapes are created from the Domino okay given an integer n return the number of ways to tile a two by end board since the answer may be very large return it modulo 10 to the nine plus seven okay in a tiling every Square must be covered by a tile two tilings are different if and only if there are two four directionally adjacent cells in the board so I said exactly one of these Thailand says both squares occupied by top okay so essentially all that's saying is we basically want to have a grid like we're gonna have this grid so for example one when n equals three that's basically saying you have this grid like so and it has link three and we just want to know how many unique ways can you populate this grid with every cell filled so there's no holes such that uh um each orientation is unique What's the total number of ways that you can do that right so for example I could put um you know I could put one of the horizontal tilings here and another horizontal tiling here and a vertical heart tiling here so that's one way right I could put two vertical tilings here I could put three I guess I could put three tilings here I could put uh two on the other side horizontally and put a vertical tile in here right and that's everything just exhausting the these uh two by one pieces sorry and then finally right I could use these trauminos by kind of attaching them like this right and oh what am I doing I'm not drawing a gun all right like that like this excuse that sloppy joint so those are five ways right so there's five ways to uh take this three system write this initial blue grid and populate it with the tomino traumino and Domino uh pieces so it seems simple enough now this problem seems very confusing right because this drama no piece is like so strangely shaped um I think the most intuitive thing right would be dynamic programming because we're talking about total number of orientations right because like what's really happening is if you thought about this in terms of you know dynamic programming you see sub problems here right there's an N equals two sub problem um which is a different color there's an N equals two sub problem here right what I'm saying is like I can attach a piece like this right at the nth value and then there's a system there's an N minus 1 System that we've already solved for that we can attach ourselves to and it'll still work that's already completed so I'm saying is for n equals 2 right that what I'm trying to get at essentially is like for n equals 2 the ways that you can do it are these two systems right for n equals two you have dominoes two dominoes like this foreign or you have two dominoes like this so then when you have n equals three well then I can just attach I can attach the third Domino to the tooth case right so I can attach this new Domino to each of the two cases right so in the two cases I have these things here so for n equals 3 I can take the two cases and I can attach a domino like so I can attach my Domino here and I can attach it here right so I get two more cases that way now of course those aren't the only cases but you can see how this kind of works right for n equals three I can take the N equal two cases and attach this Domino right so and any generic example if I have the nth Domino I can attach it to the N minus 1 set of dominoes if I put it in this orientation right but there's multiple orientations for this Domino right the other one is well you know so I guess what we see here right if we want to say so far what we see is for the nth case we can always attach ourselves to the nth minus one case right so this is kind of one system right if I wanted to talk about uh this dynamic programming problem sorry if I want to talk about this dynamic programming problem in terms of the previous iteration right well if I called it my Dana I'll call it full just F or full of n right well for full of n let's erase this stuff I'm gonna get full of n equals full of n minus one plus something we're going to determine what that is right because this right here is full of n minus one right that's what this yellow system represents so this is basically saying this corresponds to adding one of these babies as the nth one two one of these a full system here which is n minus one the nth minus one system here so that's what this basically is saying here so the number that I can get at the I can just attach a vertical one and then I can get the total number that I would get an N minus one right which happened in the three case right when I attached a three I could get all the ones from two right and the ones and two are this uh the horizontal one stacked on each other and the vertical one side by side so that's basically the idea of using dynamic programming right what I can get here well I can attach this thing so then I can just add in everything that I can get before but of course that isn't the only thing that I can do what I can also do is well what is n equals one well n equals one equals just this the only thing you could do is put a vertical system like so right because n equals one means that it's a you know the length is one so the only thing that you could put there is a two by one right and you'll see n equals one here in this system right so I can always attach my I can always attach two grid cells like so two on top of each other like this if this is the nth index well then now I can't use the solution at the N minus one because I just place these tiles here but I can use the solution at n equals n minus two right so I can get the solution from n minus one and I can also get this a solution at n minus two right because I would just attach side by side uh stacked on top of each other um for the solution that's n minus two to the left right whatever the complete solution is here well I can just attach myself to that right so then we also have full of n minus two now this would be the entire problem if there wasn't traumino pieces right the terminal piece is kind of complicate things because it's no longer just you know a domino like this or Domino like this there's this weird idea of holes um but you see this so far but this isn't it right because we haven't even considered the additional pieces but I'm hoping that this point at this point you at least understand the dynamic programming aspect of this problem right you've already got the whole full system for n minus two so we already have that whole full system so I'll just attach uh two dominoes stacked on top of each other and that'll give me a whole new set of solutions right where it's all the ones that I got before attached to this one plus all the ones I got before up until n minus one attaching a new vertical Domino right and doing that alone you capture you know these three solutions are already captured with this one right because this is n and this would be n minus one so you would add in F of n minus one right to get these two solutions here and then you'd add in F of n minus two to get this solution here right so for f of three you can just use f of n minus one F of two and you'd get these two and then you do F of n minus two which is this one to get this one and so we just have to account for this idea of these trauminos and what that does to our solution okay well you know this comes down to what if we added a vertical um Domino what if we added horizontal dominoes what would happen if we wanted to add a Domino like so right because what we're trying to do is we're trying to fill out the last note right because we want to make it full so in order to make it full the nth column right has to be full so it has to be covered so this is one way to cover it but the problem is this isn't n minus 1 because this piece is already covered here so we can't have overlap right they can't overlap each other so it's not full of n minus one um it's also not full of n minus two because if it was full of n minus 2 then this piece would be missing so what it needs to be based on is something slightly different right which is we need the top to be empty in the previous solution right we need a solution where there's something missing at the top so that we can attach our piece right we need a piece where it's like it's stacked up like this that way I can put in a piece that's shaped like this right that way they can fit into each other right so the only way I can add this traumino piece to fill out the end is if there's I have to find the number of solutions where there's n minus 1 where the top piece is missing so we'll call this uh what should we call it we'll just call it top missing I guess it's fine top missing so this would be top missing n minus one so this is n minus 1 here right so we'll call this uh top missing n minus one so that means that we can add in this top missing case let's delete this stuff so we have a little bit more space here because space is real estate is important so we can add in the top missing part of n minus one if we attach this piece to fill it up so let's do that but that means now we have a new thing that we're going to need to account for somehow so this is top missing n minus 1 and then what's the last way that you could fill it out well let's look at our original pieces right so this one fills it out two of these stacked fill it out this fills it out we just did that one and this one fills it out right if we try to attach this piece at the end there would be an empty spot if we attach this piece at the end we get an empty spot but you know that will become important in a moment okay so the last way we can think about this is well we can add the one remaining Feast that piece that fills it out right we can add a piece like this at the end right so at the end system it's all full now right the nth column is full we're covering it but that would mean that it would need to attach to a system where the bottom was missing sorry it's so confusing right because I need a piece where there's nothing here that way I can you know push in my new piece into this slot and fill it up right so I need the bottom missing at this case and of course this is still n minus one so the final example then would be oh I guess I would be that it's the ah the final piece would then be that the top uh the bottom is missing at n minus one at M minus one so this is the whole recurrence relationship right the way I can fill it up here is I can put a vertical one and then that would mean that it's all the systems that are full up into n minus one I could put two horizontal ones so that's all the full system at n minus two or I could put some uh one of the terminal pieces like this but that means there has to be I have to keep track of the top missing at n minus one and then I could put a L-shaped piece backwards I could put a L-shaped piece backwards I could put a L-shaped piece backwards like this but that means the bottom piece is n minus one and of course we don't add these new ones like this because you know this wouldn't fill up the system because there'd be an empty spot here but then what does that mean in terms of what we need to find well now we need to find top missing and bottom missing right because the issue is now is well I can if I need full in terms of top missing and bottom missing I needed to know what top missing and bottom missing are so what are the ways that I could how many solutions can I make it such that there's top missing at n so now that just kind of adds another thing that we're going to need to calculate okay so how do we find top missing at n well how would we get a top missing so a top could be missing if I put a piece on the bottom like so and there's a previous system like so right because you can see here there's obviously a top missing here so in terms of the systems what would that be well that would be a bottom uh right so this is n and then what is this piece is just the bottom missing right this is the this is n minus one bottom missing so we'll call that bottom missing of n minus one okay how else could I get a top missing I could get a top missing if I put one of these backward L shapes right if I put a backward L shape you'll notice that the top is missing but then I need this whole system to be full so if this is n this would be what this would be full of n minus two so that's full of n minus two is there any other way to get a top missing um I don't think so no okay so then let's figure out what bottom missing is in terms of previous thing so bottom missing equals well to get the bottom missing I could put um let's move this over so it's cleaner to get a bottom missing I can put a piece at the top but there's just one bottom missing so then I would need to attach it to something where the Top's missing and then you'll notice here that you know the obviously the bottom is missing so that's for the nth one so I think you're starting to see where this is going so I'll kind of go through this quicker so this is where the top is missing or I can add a piece like this to get the bottom missing again and then that's just the same thing that's full of n minus 2. and that's kind of it right now I have everything in terms of everything else right I know how to find full because full is just based on well if I wanted to fill out an N I'm going to have to put pieces at the end what are the pieces that I could put at the end to fill it out meaning that I cover the last column well I could cover the last column like this I can cover the last column like this or I can cover the last column like this if I cover the last column like that well then if I cover last column like this it's based on the full system at the previous end value if I cover the whole system like this it's based on the nvap it's based on the um full system at the N minus two values because I filled out the last two if I do it like this well then there's there has to be a top missing in order for me to attach this piece and then if I want to attach a piece like this it fills out the last column fill the last column I need to attach it somewhere where the bottom is missing well then that means that I need to figure out what the top missing and the bottom missing are right what's the top missing for this well I can create a top missing by attaching a horizontal piece at the bottom to a system where the bottom is missing or I can attach a backwards L-shaped to a full system and backwards L-shaped to a full system and backwards L-shaped to a full system and now the top is missing same situation here with the bottom missing okay so these are just our recurrence relationships so we can just run through this system and we should be able to find the solution so let's go ahead and do that so this is just a classic dynamic programming problem um with just you know some trickery so let's see what we can do to make this one okay so we'll have full we'll have top missing and we'll have bottom missing right I'm just going to call them this so it's a little bit easier for me to figure out how it works um so I'm trying to think about what the so full of zero is there anything I'm trying to think of what's based on what so full is based on N minus two so we should start at two full of one is one full of zero was one top missing is only ever based on top missing before top missing of one is zero I'm trying to think about Okay so if you had a I'm trying to think about the base case right because when you do uh a recurrence relationship you need an initial value to start propagating forward right so what's the base case if I had a system that looked like this how many ways can I make the top missing zero right because there's no way I can't like since the system's like this I can't attach a piece like this I'm saying that this blue system is the grid right it's an N it's a one system so I can't attach a piece like that right the only thing I can do is fill it up by putting a piece in here like a just one vertical Domino but I can't make the top missing so that'll mean that the value there is zero so for full zero is one and one is one for top one is zero and for bottom one is also zero because there's no way that you can make a bottom empty with just one grid cell because how are you gonna put something in there so then what we can do is we can look at each value I in range um so we've already populated zero one and two so two and N plus one because we want to look at all n values and we'd say okay now we just run through this recurrence relationship so full of n equals full of n minus 1 n minus two top missing n minus one bottom missing a minus one okay so full of I ah equals full of I minus one plus full of I minus 2 plus top missing I minus 1. plus bottom missing I minus 1. and then we just need to populate top missing of I minus one and bottom missing y minus one so top missing of I equals bottom missing M minus one full n minus two okay so top missing of I equals bottom missing I minus one plus full of I minus two bottom missing of I equals top missing of I minus one plus four I minus two now this doesn't make sense right the thing is sometimes the best way to approach these problems at least for me is to separate the logic from the code in terms of what things mean so I've already convinced myself of these recurrence relationships so now it's just about you know robotically taking it and putting into the code and not really thinking about it too much because I don't want to be thinking about the logic of what I'm doing in terms of like the complexity of their current relationship while I'm writing the code I just want to focus on making the code work using what I wrote right I'm just translating I'm translating my ideas into code I'm not thinking of my ideas as I code right I'm just translating so bottom missing of n minus one top missing four and minus two but you know of course you have to do a little bit of thinking because you think about base cases and stuff like that so then at the end we would just return what's full at n and we cry because it's wrong no I'm joking all right so we'll try to submit that see what happens and I forgot to uh to mod it by 10 to the nine plus seven that's my uh very common error Okay cool so this is pretty much good right um one thing we can fix is that you'll notice right that this system is only based on two previous things right F of I minus one F of I minus two t of I minus one B of I minus one this is only based on two previous things the idea is like we don't need to keep track of the whole system we just need to keep track of the whole system up to the previous two things right we just need to keep track of the total number of things we can do up to the two previous things we don't need to keep track of everything we've ever done for the whole system it's kind of a waste of memory so what I'm going to do is I'm going to convert these things just into single constants that we update and then return and the idea is there is that we can just update those constants and we don't need to keep track of everything we've ever done to take the run time from o of n down to O of one or constant okay but in order to do that I'm just basically going to force replace all of the variables and hope that it works that's usually the easiest way of doing this you write it in O of N and then you figure out okay this becomes that like you just replace variables and it'll get you to O to one right so I'll have what F was previously and then I just keep track of top and keep track of B so F previously would be one F would be one t starts at zero and since the value here is zero then t b also starts at zero and then I just update these things accordingly so F becomes what F was before plus what F was before that plus what T was plus what B was T becomes what B was before and what F was two times before B becomes what T was before plus what FF was before now of course now all these variables need to be updated at the same time and of course you want to take f and set it to what f was before after you're done so that the next iteration has access to that information so then in order to make this work we need to put it all on one line or we could do a series of swaps that I'm not interested in doing okay this is a very risky way of programming because I'm basically just saying these are the things that I'm trying to do to make this work and it may be it's confusing right but it's constant time and I've already written a solution that isn't confusing so maybe you know you'll get some uh leniency it's not gonna work because it's yeah I've attempted too soon cool all right there you go three-line solution so what is this in three-line solution so what is this in three-line solution so what is this in terms of space and runtime complexity all right we'll say that n equal n is n okay good so time well we populate these three these four variables right that's constant time and then we just have to look at all n would look at all n columns in order to update them and for all n columns we just do something constant right we update this variable we add these things together whatever and at the end we just mod it 10 to the 9.7 so no operation ever get 10 to the 9.7 so no operation ever get 10 to the 9.7 so no operation ever get bigger than 10 to the nine plus seven so that's a constant operation in terms of 10 to the 9.7 so it's for N Things We Do 10 to the 9.7 so it's for N Things We Do 10 to the 9.7 so it's for N Things We Do Something constant so we do n constant things so that's n times constant 11. okay and then before our space when it was easier to read was end space right because we had to keep track of each column but since we only need to keep track of the two previous columns we just have these four variables and then we update these four variables accordingly we never have to deal with uh anything else so even if there's 10 million variables or there's only if there's if n is 10 million or n is one or n is 400 000 we only have to keep track of these four variables so it's constant space all right guys fun problem I skipped this one a few times I'm glad I came back and really just walked through how this is supposed to work um never a bad idea to go back to problems you can solve before because who knows maybe you've your skills have improved or maybe you're just having a better day and you got better sleep I don't know peace out
|
Domino and Tromino Tiling
|
global-and-local-inversions
|
You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Explanation:** The five different ways are show above.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 1000`
|
Where can the 0 be placed in an ideal permutation? What about the 1?
|
Array,Math
|
Medium
| null |
231 |
Hello guys welcome to my channel today is the day 8 and problem is the power of two flexed problem statement and tried to understand to give examples for giving may or write a function to remind that press the power switch interior is the power of two and not It's true for example wave tower 2004 646 does not the power of two the number is 900 let me love you all like this here let me explain little baby approach of mathematical approach automatically is who is the number is the power of two 100MB Can be divided number device number is power in the check the number resort V ee day first number one that hand can continue being real divide divided by two i till the number reduced to one teller number reduced to a reduced and subscribe and e will give It's Very Simple Subscribe 10 Will Return subscribe and subscribe the Video then subscribe to the and Scottish Compiling Edison More than 60 Subscribe Examples Similar Passing Notes Solid on Cigarette Time Tower Solution First Video Solution 210 Examples in Mathematics and the Complexity of This Is Like You Every Time Dividing Number 34 Long and Complexity of Dissolution Is the Heart of Benefit and 202 Been Left Right Implemented Recursively If It Try First Yourself for the Video and If You Are Not Able to Figure Out Bench a Mic Solution So Let Me Implement Developed Solution Comment This Code Effective Way That I Had to Travel Half an Hour A Tiny Told Her Voice Mail Message Narrate for the Record Solution What We Can Do Vijay Simply Return Inch 11 Number From Switzerland 04 00 One End Difficult Is Equal Is Power Of Do How To Gestures Even so android2 is given withdrawal from one place and behaviors one status reduced we have to return proof with condition with extracts from pearl court developed solution 98100 compiled and where getting expected answer for the subscribe our developed code that nitish accepted for this Is Amazing Spider-Man A Solution Like Comment Subscribe For The Mission Is Incomplete That Is I Write Down The Number In The Representation Space I Left Right Down The Number Is Not A Winery Representation So What Will Happen Left Number One And I Am Writing This In The Representation subscribe for More Video Subscribe to 1080 600 800 to 1000 12345 with us the issue carefully officer da number beech is power of to have only one side tweet bhi side effect and he also hair oil se mobile number which is not the power of which has More Than One Should Quite Say Nothing Will Reduce One Our Number From Left Right Side - 09 2009 2013 For Three Left Right In The Representation Of 10 To And Lakshmi Copy Paste Se News For More Rate Test Cases Will Zee From Thursday Media Subscribe to the number to the like and minus one according to what will get let's see who will get 08 similarly a for the sky for this many software will get 0 that and for this treat me copy only spot and Other part will calculate 34 Idu wide end after 1000 and here again for this acid 000 to 0512 for it is the power of the approach of solving a very simple Subscribe Twitter The one pan device and with and minus one and wise and with Jain - One is sure wise and with Jain - One is sure wise and with Jain - One is sure subscribe to the code hua hai nitesh compiled and were getting distressed and answer for and custom input subsidy supreme court in this accepted and decided like it was also spoken like this number is power to disturb executive who can also another with the fourth way School Problem Comment This Thank You Got His Behavior Lut Yes To Dogs Comment Hai Yaar Again So This Is For Third Option Of Market Going To Implement Floor Solution Here Which Will Us Account Of Mid Using This Alone In This N That Is Crater The And Content With intention and good thought with dance class mercedes-benz and good thought with dance class mercedes-benz and good thought with dance class mercedes-benz pen straight power of two cities will return subscribe to a fetish compiling and were getting back translate same and the satisfaction of this total four solution explain why will basically posted at times time you can visit is What ever you want all you want to watch for you can watch video thank you like please subscribe my channel for my upcoming videos
|
Power of Two
|
power-of-two
|
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_.
An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** 20 = 1
**Example 2:**
**Input:** n = 16
**Output:** true
**Explanation:** 24 = 16
**Example 3:**
**Input:** n = 3
**Output:** false
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Bit Manipulation,Recursion
|
Easy
|
191,326,342
|
1,255 |
Shri Ram Londo, how are you, everything is fine, he scored a fast century, Rajya Sabha, but its name is ' scored a fast century, Rajya Sabha, but its name is ' scored a fast century, Rajya Sabha, but its name is ' Maximum' in words from letters, which Maximum' in words from letters, which Maximum' in words from letters, which means that you should, you have been subscribing, what is there in it, which gives you the first question, he is a poetic preventer, he is an American. Also, from Amazon which is till Zinc, it is okay, so what you have to do is that we have given you this word, meaning it has given you a distant traffic, it is close to you with this word, we have given you this letter, the latest Kepler space is being made, as if this is yours, how much is it? It is coming once or twice, it is coming again, it is coming once again, it is coming three times, yes, you have to make one, there again you have to maintain the limit of these latest and you have to use this form to see this word. If it is happening or not, then absolutely if that word is coming from these latest, then it is the cat soil of our skirt which is set, this is not the latest, you people will never do this, understand that he can become a don or he can become a dedication. What we have to do is basically it is written in a presentation with a and we have to maintain this thing, is this word within its limit or not, does it have character and is not doing a seat in the case like the dog has given its life, don't you? I can't give you G in jaggery because you want only one, without you would have given it to two districts, but if I have one, you will give it in the log, I will give it on time in the good night too. Okay, by doing this, you will see ghee, you can fill the form with word, from the set and The one who is the president in this and his time is the person who is in the representative of Sambhaal characters like keep DK there are five on the side OK how much is there in different this city there will be a rally here and on the left side of G A B C D E F G Three is wooden, if it becomes 1551, then it gives you 11 of the sea, it is okay and what can it become good, can it become should, at this time my brother, what has happened that tell me such nirguna, brother, there is mention of da in it, that is, 515 can be added and Don't pluck in the list of dandruff too, they can become clogged and reduce them. If you explain them then basically this is the story, something is fine, let's do it with BT, we will do back cutting, we will decorate, it is the most beautiful thing because meaning, that's why it tells you about life. That is, whenever you do any work in life and keep moving forward on the path and you are not getting success, okay you are not achieving your goal, you have to take 12 steps back, track that thing and reach there. As far as the maximum benefit from the second pass is in the container, this is the backtracking, okay, that means do the work, no more work, success, unmute that a bit, then the second thing is that if we want this back, then we will pack the power. First of all, what do we need, okay? Let's see some general knowledge quiz on hot problem, there is no red in the mind, okay, and no protein, okay, everyone gets it with practice, let's practice, what is the first thing that comes to mind, one thing is certain for us. That these are the characters, these things are used to make sales from the account itself, mostly increase an account, ok subscribe, definitely you have u, this is a very good thing, while doing backstreet, we can see whether its limit is reached at that time or not, but we will discuss later. Earlier, we were definitely working on this work that Jo and tempo stand si which is inside your latest, na brother, all the hungry people can subscribe account letter of i-safe witch letter for Indian inside the memorial account now. If we can subscribe account letter of i-safe witch letter for Indian inside the memorial account now. If we can subscribe account letter of i-safe witch letter for Indian inside the memorial account now. If we want a final answer, then it's okay, let's write the networking function, this is back track, okay, pass it to Jitendra, pass it this year, there is no need to pass anyone's latest, we can pass the account deficit and this is If we have to pass then either we pass the account made from the same, okay now the thing is that we people can pass this thing, we can pass the start and we can pass the reaction of Star Plus, we have passed it and hello, what can we talk about? It's a decade, it's okay, it's not there yet, but we'll see when we see it. Okay, let's talk about this for now, then I'll write further, and I have to do 200 satires. Hey brother, I can take that. I'm on the track that it's both half. Copy the minute, why did you do it like this, we will delay it in the middle, there is a need to edit A in it, create this point, now you click on it, okay, thank you, we have appointed till today, okay, that's the design, you will see any. Back function one is to get them terminated as well. Suburbs condition Hussain is required. In this condition, she says that our Matrimonial Jhappi account becomes bigger than any of our words. From whom does this account become ours? Then we will remind you. Okay, either she is pregnant or there is 20% of it in the world that is 20% of it in the world that is 20% of it in the world that is not among us, then we can make another person for trimming her. I am writing a letter to you, what name should I keep, her name was account, its name is hua hai. Extra oil account ticket counter is given and the account has been kept that now if ever there is gas actual and if the I becomes bigger than the normal account of I then you have to terminate this function and run the clove which is good till 26 Okay, yes, it is absolutely right. MLA is talking about the campaign solution to find a termite. What has to be done is that we have to generate all the meanings of this, first of all, this word is there and then inside it also. All this means every character, I am thinking, we do it for and so which apps are there on AIIMS, we take it is tremendous that we do it, the word is fine, it is a saiya satirical gift, how it is called birthday and auto serum percentage is a. Forum to Temples Page for Word What to do at this time Now what is our account Excel less playing in it Is the account equal to the secretary account What is the access account of Serious - 20121 So comment It is increased and increased It sure seems right that If you want a good and good answer at once, if you also want a temporary answer, then let's take the white answer passed in the silencer, if not then please click the subscribe button, then finally do Bigg Boss, do the championship. A temporary answer - If you are championship. A temporary answer - If you are championship. A temporary answer - If you are 15th, then you will hit this side of the position and end. The temporary correct answer is A Temple Singh Rajput and the answer which is WhatsApp maximum will be covered inside it. The temporary answer is that it is necessary that I am right that it has come, what can we do, what has happened is that Akbar is a temperature and we can play in it. Can temporary is equal to that friends, you is our school, take which one - 6a ok in which one - 6a ok in which one - 6a ok in this way this area were then again avoid work and put the country in enter then second one in back us This position will help torch light bill s band whatsapp this width plus chicken does important work now we call it for track tractor is what to do near but to pass and call to pass Have to do and what have to pass We have to pass excel law Okay okay and have to talk about new positions near I plus one key and temporary answer Android person in this championship Now if we don't get it ours then do it Singh Mute the world 250, he is wow, it's foursome, WhatsApp came to him, now you should reduce the Akshar account because you did not get the answer from him, then don't say - keep decreasing and this is the then don't say - keep decreasing and this is the then don't say - keep decreasing and this is the temperature to match that, what is a text? Send a message, what is the problem and immediately put a request for MP3, sorry, nothing will remain on the phone, okay, I will check once, if it is running from 10 to 14, then I will return. I am setting the maximum answer. People have been tracking WhatsApp till the police award, temperature is fine, this child has been made his serial e-want, time has been made maximum on the ground, so he had e-want, time has been made maximum on the ground, so he had e-want, time has been made maximum on the ground, so he had made the luck of running off to create an account on Facebook, it is fine from zero, that after Ballia and account. Were passing the image Emperor is now and Kashmir shows 68 Write in comments Whenever the meter is fine, ready, keep submitting, my tablet is happening, so this is the question to you, is it fine and big cities and maximum sum of and then maximum school Words from the lips do
|
Maximum Score Words Formed by Letters
|
reverse-subarray-to-maximize-array-value
|
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character.
Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times).
It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively.
**Example 1:**
**Input:** words = \[ "dog ", "cat ", "dad ", "good "\], letters = \[ "a ", "a ", "c ", "d ", "d ", "d ", "g ", "o ", "o "\], score = \[1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0\]
**Output:** 23
**Explanation:**
Score a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad " (5+1+5) and "good " (3+2+2+5) with a score of 23.
Words "dad " and "dog " only get a score of 21.
**Example 2:**
**Input:** words = \[ "xxxz ", "ax ", "bx ", "cx "\], letters = \[ "z ", "a ", "b ", "c ", "x ", "x ", "x "\], score = \[4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10\]
**Output:** 27
**Explanation:**
Score a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax " (4+5), "bx " (4+5) and "cx " (4+5) with a score of 27.
Word "xxxz " only get a score of 25.
**Example 3:**
**Input:** words = \[ "leetcode "\], letters = \[ "l ", "e ", "t ", "c ", "o ", "d "\], score = \[0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0\]
**Output:** 0
**Explanation:**
Letter "e " can only be used once.
**Constraints:**
* `1 <= words.length <= 14`
* `1 <= words[i].length <= 15`
* `1 <= letters.length <= 100`
* `letters[i].length == 1`
* `score.length == 26`
* `0 <= score[i] <= 10`
* `words[i]`, `letters[i]` contains only lower case English letters.
|
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases.
|
Array,Math,Greedy
|
Hard
| null |
503 |
foreign part two I hope you have seen the part one for this one because that's the prerequisite for this question and you'll understand that better if you have seen that video okay so let us read a description what it says so given a circular integer array okay that is nums okay the next element the next uh the next element of nums 0 which means at the last the next element is now so because it is circular here it is not actually circular but it is behaving like a circular okay Enter the next great element for every element in the numbers okay and the next element of the x is the first greater element to its traversing order next in the array which means if you could Circle if you could search circularly to 5x next element if it doesn't exist it is minus 1 for this number okay so I hope you've seen that uh numbers one in a next great element part one in that we have discussed like for the um in a simple array if we are given some values at the initial so that will be having the ratio element towards the right but for this one for this problem we can have that the last element's data element will be towards the very beginning of the array it will also happen right so that is the basic difference here in this case example here is one to one okay so for one which is the next element which is two here and for the two we don't have any extra element that is we are putting -1 element that is we are putting -1 element that is we are putting -1 because in Array there is no in Num sorry there is no element which is greater than 2 so that's why it is for sure that it is going to be having minus 1 but for the one in the last question we have seen that it will be minus 1 but here in this case it is not minus 1 it is going to be doing again to the initial position which is 0 and then our starting position is 0 and then it will check for the two so you can see we have next element is 2 for this one behaving like a circular and for this example one two three a four three four two we for one we have two for two we have three for three we have four for four we have minus one because for the greatest element here for the three we have again four correct because if you go three and you will go like one two three four it will check and four is the greatest element name so let us see how we can uh solve this problem okay I will explain this problem on the white dot let's go there so let us try to discuss the uh approach here so in this we'll be solving this problem into two ways okay first way is the pre-processing of our stack the pre-processing of our stack the pre-processing of our stack okay pre-processing the array basically pre-processing the array basically pre-processing the array basically and the second part is comparing okay and doing the three observations and doing three operations so what are the three operations first is the pop operation which we normally do then we'll be having our uh answer creation okay and then we will be having pushing into our stack okay so these are the three operations so let's see what we are going to be how we are going to be doing so first thing is pre-processing the array so for the is pre-processing the array so for the is pre-processing the array so for the uh how will preprocess it so before we will be doing this so we'll start our iteration from here okay for this last one so nums minus two basic nonstop length minus two we'll push our Dash value as 4 okay so this is again the three steps Pop answer creation will skip for the first part okay for the first part this is uh like um steps so we will call that as one step and the second step for the first step we'll skip the answer creation we'll just pop and push it okay depending upon the values so first value we have 4 will put stat into our values okay now we are going to be checking for the three so three we can see that 3 is smaller than this 2 will not be able to pop this 4 we'll just put three above this and we will be having two so two also will be pushing about this for the one also will be having one other top so we have already this and we have created this stack we are going to be using for our normal way which we do okay so now this is the step two in step two we'll be again doing the three operations now we'll be starting from num start length minus two only from here we'll start num minus one basically okay so this is num short length minus one and we'll start from here basically not from here because for the three also we need to check in the last in the part one what we did we'll start from here because we are sure that for this minus 1 will be the answer but for this we are not sure minus 1 is not mad bear might not be answer if it is the greatest element like eight or something it can be minus 1 but for the other cases it will be some other element from the beginning of the array so for the three we'll start our uh we'll start doing the looking here so for the three we'll check you know is there any uh top of the stack if three is there so three we'll see for one two three and four is the right so for one for three we will see that value is at the top of the stack is smaller than three so we'll pop it so we'll pop this and we'll even pop this so 4 is remaining so 4 will be uh will be the answer for this okay so for the three you'll be having the answer I'll be writing your answers one two three four and three and this is our answer okay and which will be having nothing but for the three we'll be having the value as 4 which is the top of the stack so first we will be having pop operation we did and we'll be having answer creation is four and pushing the element will be pushing three again here on the top of this okay so that we have done now for the next part we'll go and search for the fourth one for the four if we have any greater element towards the right so first we'll do the pop operation so pop operation means three will be popping out for 4 also will be popping out that is in B that 4 is equals to the top okay because for when we pop uh operation basically we do when we have the at the top of the stack this element is smaller than our current element so current element is four smaller or equal okay so four is the red so 3 is smaller than that and four is equals to 4 so we'll be popping both of the element so popping is done answer creation will do four if so if stack is empty we'll put minus one okay and our answer creation and pop pushing will be doing like again we'll be pushing the 4 at the top of the step so only I have here 4 at the top of the stack these elements are not there in this now again we'll go and do this for three so three we'll see the operation 4 is the right four element is the four which is greater than this three so we'll not pop it we'll just push the will not do the pushing operation but pop will not happen answer creation will see for answer question we will be having 4 and for the pushing operation we'll be having this three at the top of this four okay that is done for the two we'll be seeing again the value at the top of the stack is greater than that so we not be able to pop anything for the creation part we'll be having three okay and then pushing operation will be having two for the one will again be doing not be able to pop anything because other girls are greater than that so first is the proper Element no not doing anything unsaturation will be putting which is two okay and that is this pushing operation will do push that is done stack will be having some values like all those values are there but answer we have created so let us cross verify so for the one we have two element is greater so the two is there so the two will be having three is there or three we have four for four we have minus one because nothing is greater than for the 3 will be having the 4 okay it goes and check here it is the fourth is greater than this three so that's why 4 is the real so this is just correct answer so this is the pro that we are going to be using uh let us try to write the code for this in our quota data so let us write the part for code for this so first we are going to be finding the length Okay that is nums dot length okay and the first thing we are going to be doing is making the stack because that is where we are going to be storing the values so stack will be pushing the integer values let us call that a stack as St equals to new stack okay so this we have created our stack here okay now first thing is that we need to preprocess it and how we are going to be pre-processing so for that first we are pre-processing so for that first we are pre-processing so for that first we are going to be iterating from n minus 2 okay and numbers minus 2 to the very beginning of this code okay very beginning of this array so we'll start our iteration from n equals to uh n minus 2 okay I greater than equals to 0 okay I minus okay and then what we're going to be doing for we'll be doing a two or two operations only that is popping and pushing so we'll be having this one if St dot size is greater than 0 which means we have something in element to pop it as if something goes something wrong and I will be writing St dot Peak element if the top element is smaller than our current element okay if it is current element is num stored number type if it is the case then we'll be pushing uh that will be popping our element so St dot pop character it because at the top of the stack the value should be greater if it is smaller than that then we'll be popping it that's the current approach then we and after that what we'll be doing will be simply pushing that values so s t dot push or values will be nums of I okay this is the pre-processing now we okay this is the pre-processing now we okay this is the pre-processing now we are going to be again doing the same thing but here in this case we'll be starting from very end which is num start minus one not two okay and I greater than equals to 0 okay I plus not I minus and then again we will do three operations this time first operation is same only that will be checking this thing that I'll just copy paste it so I'll be checking if SD dot empty um if a stack is empty it is not empty then we will be seeing this operation non-stop I then we'll be popping it and non-stop I then we'll be popping it and non-stop I then we'll be popping it and the second part is okay so yeah so we'll put in this operation now here we are also make need to make an answer array we can make like this and Sir array equals to new end of size n okay and then we'll be doing the answer creation step which is answer of I equals to if our stack is empty so we will write something like if stack is empty okay or we can write something as T Dot size if equals to 0 then we will push minus 1 else what will push Peak element okay that is it and pushing operation will be done that is for sure and once it is this is done we'll just return that answer from here written answer okay so that is it now let us try to run the code it is successfully accepted let us try to submit the code as well now so this is successfully accepted the solution so that's it for this video I hope you got the basic idea of both of the problems okay uh part one and part two so that's it for this video we'll be connected to the search problems thank you for watching foreign
|
Next Greater Element II
|
next-greater-element-ii
|
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[2,-1,2\]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
**Example 2:**
**Input:** nums = \[1,2,3,4,3\]
**Output:** \[2,3,4,-1,4\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Stack,Monotonic Stack
|
Medium
|
496,556
|
1,684 |
okay welcome back uh today 1684 count the number of consistent strings uh so we're given a string aloud uh consisting of distinct characters and an array of string words uh a string is consistent if all the characters in the string appear in the string allowed so you have to return the number of consistent strings in the array words uh okay so you have a string which uh are the allowed characters and an array words with lots of strings here and through each element you can only use these characters that is the problem uh so you just have to loop and check if it has different characters if it has the different characters from what is here it's not consistent if it doesn't then you increase the counter by one yeah let's see so here's a b a d is not present in a b so no b d is not present to no a and b are present so yes be a yes and here it's not because of the d so you have a counter of two example two alone is abc so a you have yes b you have yes c you have here yes a b you have here yes a c b c and a b c so all of them are consistent increase the counter by seven right uh example three c a d so c you have here so yes a c d yes b you don't have b to f here you have and d you also have so increase by four uh yeah it should be like do you need a counter you know that you need a counter uh we also need to go through every words so you use a 4-h so you use a 4-h so you use a 4-h oops so for each words as word uh here you need to compare uh if this is if this has all the elements from the allowed however working with strings can be a little bit messy uh so i'll transform them in an array because it's easier to compare values in an array so in this case word equals str split so i transform this into an array and now i see oh yeah and i also need the allowed it's going to be also an array so it's easy don't just compare if they have a difference in them if they have different uh character or different element in this case uh it's not consistent here i compare the word and allowed so if there's no difference you increase the counter by one and after the forage you just return the counter i tried a couple times yes so we got it so remember that when you're working with strings sometimes it's a good trick is to transform them into an array and there will be like building functions or it will be easier to work and solve the problem yeah
|
Count the Number of Consistent Strings
|
find-latest-group-of-size-m
|
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters.
|
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
|
Array,Binary Search,Simulation
|
Medium
| null |
858 |
hey what's up guys this is john here again so let's take a look at today's daily challenge problem number 858 mineral reflection i mean this is more like i would say it's like more like a math problem but let's just take a look you know there's a special square room with mirrors on each of the four walls except for the south west corner which is the bottom left corner and there are like receptors on the remaining corners numbered from zero one and two so as you guys and the beam and there's a laser ray from the bottom left corner first it will first meet the wall at the distance of the east wall at this of q something like this right and then it asks you to return the num which receptor the ray will meet first and it's guaranteed that the ray will meet a receptor eventually so for example right we have a so the laser always starts from the bottom left corners and then it will always hit the east wall first with like a distance with a with the distance from zero to q right so this is a q and then the length of the square is p and i just ask you which receptor it will meet first so for example we have zero one and two so for this one right i mean the first receptor it will meet is two here and then there's a p it's a one thousand and the q is like always equal smaller than the then the p okay so let's draw some examples here right i mean the this is the i actually the first one is always the easy one let's try to see when it will reach the uh the receptor two here right so the first one is just like this right i mean this is the this receptor 2 1 0 and this is p this is q so in so this way we can reach the receptor two right and we can another way it's like this right we can do this and then basically we reflect it like four times right one two three four and then we reach two here and how many queues we have here we have one so we have a one queue and then we have two q three q and four q's here and then so the first observation is that you know as long as the q is even number the number of q's is even we know it will definitely reach the receptor two here all right so that's the observation and let's take a look at a more difficult one you know so now how about the receptor zero and one right so for those ones you know we have to draw some like different squares here let's say we have this one let's say the length out of p is three and then the q is two how about this right so the q is two which means something like this right so the beam the laser will first reach this two here and then what nade will reflect to here right we need to reflect to here if we're only checking this one squared it will go down and somewhere go back here right but that will make it hard harder for us to i mean to observe so what we can do is we can extend this square by one here so we which means that you know since you know this thing will reflect to this side first right so this will identical to what to this line here right and then this one will go to here right and just like this one will go back to here right as you guys can see here so actually we're transforming the problems within one square into two squares now right and now as you guys can see here so this one so this time the receptor is it's zero so yeah this is zero in the in this case so when it is zero what do we have here so we already know that so how many cubes do we have one q two q and the three q right and so then the second observation we have here is that you know as long as the q the number of q's is it's odd numbers then we know it will either reach the receptor one or receptor zero and to get how many cubes we have here is that you know so as you guys can see here so actually we are trying to calculate like we have a p here right so there's a p here how many p's we have two p's and we have three q's so essentially what we're trying to calculate is that we're trying to calculate the p times m equals to q times n it means that we need basically how many q p's and how many q's will make them even and when they're even then it means that i mean they are the laser has reached one of the receptors either on the left side or on the right side right because when they reach the same when they are the same it means that you know the laser has reached one of those two corners right and by the time those two the p times m and q times n are the same then we can check which receptor it has reached right so okay so like i said you know when the uh if the queue uh if and if n is odd sorry it's even right we know it must reach the receptor too right we return to else i mean if n is odd based on how many cubes we have right then we know okay that it might it may reach the uh the receptor zero or one because in this case you know the ones we are we're drawing here the m is odd sorry it's even so the m because we have two m here right and i'm even when the m's even then we know okay based on this like trajectory here we're reaching the what we're returning we're reaching zero here because as you guys can see here you can see here so we are going this way and then go up then we are going down and down so that's why we're reaching zero so another scenario is that you know we have one here and scenario is that like this so we have one two and three so in this case as you guys can see we are reaching the number one the receptor one here so in this case we have one p and we have three q's here right we have three q's so which means that when m is even right and then we know okay it's zero and m is odd then we know it's one that's the uh and that's the uh the conditions here now the only problem the only question is how can we calculate this m and n here right so to calculate that you know let me try to start coding here it's just uh similar at like as what we calculated the gcd which is the com the greatest common divider so we do this while you know well p times m is not equal to the q times n right because we're starting from m starting for from one for both m and n here and then we increase the m plot by one and then we get m equals to the what the q times n divided by p right that's how we uh try to get closer get close to this pn and the queue here you know we will eventually get the answer here and the answer has to be an integer so why is that because it doesn't really matter as even for like 13 and 2 right i mean we can always get the answer by what by the uh by this times 2 and 2 times 3 13. we can always get that right that's why it's guaranteeing that we can get we have an integer answer for both the m and n here and then the way we're calculating is we're trying to increase the ends because the n should always be greater than m right because q is smaller than p that's why we try to increase the n here every time we increase the n here we're trying to get the m by uh by doing this right and now once we have the m and n here we can simply check basically you know the first thing if the n is even right so when is even we know okay we return two right we return this receptor lcf right as if means that n is odd and then we check if the m is even or not so if the m is even we return one right so one is this one and else the last one is else m is odd when m is odd then we return one return zero yep so i think that's it all right run the code all right cool submit yeah so accept it i mean oh and time complexity right so i think the time complexity will be something the only time we were using we are spending here is trying to get this element in here and we have a p to 1000 so this thing is actually the time compresses similar like the uh the time complexity to get the gcd which is the uh the o of log p right yep all right i think cool i think that's it for this problem you know it i know why it got a lot of downloads because this is like more like a math problem i don't think it's you it's very likely you will get this kind of problem in the interview but it's always fun you know to take a look at this kind of math problem and i think that's it all right cool guys i'll stop here thank you so much for watching this video and stay tuned see you guys soon bye
|
Mirror Reflection
|
masking-personal-information
|
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`.
The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor.
Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_.
The test cases are guaranteed so that the ray will meet a receptor eventually.
**Example 1:**
**Input:** p = 2, q = 1
**Output:** 2
**Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall.
**Example 2:**
**Input:** p = 3, q = 1
**Output:** 1
**Constraints:**
* `1 <= q <= p <= 1000`
| null |
String
|
Medium
| null |
510 |
morning everyone um today i'm actually really happy because i passed my first round with pony ai and i'm thinking to set up my final round about two weeks later but um that's all that and i'm going to do a bunch of tree problems just to get me familiar with manipulating those pointers today we're going to look at problem 510 in order successor in binary search tree 2. and there is actually an in order successor in binary search tree one which i also plan to make a video but since i haven't done this one so let's get started so we are given a node in a binary search tree and we want to return its in order successor of that node in the binary tree and if that node have no in order successor it should just return now so on the definition of in order successor is that if we do a in order triversal is the node right after this node for example if for this tree the order traversal will give us 1 to 3. if we're given node one the node after that will be two and in this example the order traversal will give us one two three four five six if we're given a node six we'll find out this is already the right most node so it will return a now pointer let's look at another example in this tree the inorder traversal is 2 3 4 6 blah and we are given node 15 so the order traversal will be if it does have a right child it will be the leftmost node of the right child of the right subtree 13 so it will be 15 so there are two cases case one if we have a right subtree then it's we need to find the left most node of right subtree case two is we if we don't have a right sub tree for example 13 here we need to find its parent node such that this node is not its right child need to find a parent node such that the node is the left child okay cool and the time complexity for this would actually be o long n where n is the height of the binary sub tree and the space complexity will just be 01 since we're just manipulating these pointers and retrieve information within that i guess we can get started with the coding so if not node otherwise if we do have a right pointer then i'll just return find left most node else we return find first parent node okay now let's actually define those two helper function node right cool so the first one is we still need to return a node and to find the leftmost we just do if it still have a left node we just make it equals to left and then at the end our return node another helper function is find first parent node pointer node in order to find the parent we can do while node parent still have value and if this node is the right child i should go one level up only after for example if 13 we did find its parent but we found that the 13 is the right side of this node that's not going to be our successor we have to go one level up and we find this is again nice on the right hand side it's not their successor either so we have to go one level up then we find that the whole part is on the left side then this 15 is going to be our successor of the 13 and at the end i actually should return node parent cool let's try and run and i think that's pretty much it let's submit it perfect cool um i will also do so this scheme not only for work for binary search trees it also work for binary trees i'll also do the first problem of in order successor in binary surgery which basically have the same time complexity and space complexity but instead of we are given a point a parent pointer we're given the root of the tree but the whole framework is the same we have two different cases and for the first case is exactly the same for the second case instead of going from the parent we actually can start from the root but yeah i will make those videos and stay tuned
|
Inorder Successor in BST II
|
count-subarrays-with-more-ones-than-zeros
|
Given a `node` in a binary search tree, return _the in-order successor of that node in the BST_. If that node has no in-order successor, return `null`.
The successor of a `node` is the node with the smallest key greater than `node.val`.
You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for `Node`:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
**Example 1:**
**Input:** tree = \[2,1,3\], node = 1
**Output:** 2
**Explanation:** 1's in-order successor node is 2. Note that both the node and the return value is of Node type.
**Example 2:**
**Input:** tree = \[5,3,6,2,4,null,null,1\], node = 6
**Output:** null
**Explanation:** There is no in-order successor of the current node, so the answer is null.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
* All Nodes will have unique values.
**Follow up:** Could you solve it without looking up any of the node's values?
|
Change the zeros in nums to -1 and create a prefix sum array prefixSum using the new nums. If prefixSum[i] for any index i in the range 0 <= i < prefixSum.length is positive, that means that there are more ones than zeros in the prefix ending at index i. If prefixSum[j] > prefixSum[i] for two indexes i and j such that 0 <= i < j < prefixSum.length, that means that there are more ones than zeros in nums in the range [i + 1 : j] (inclusive)
|
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Medium
|
474,1999,2261
|
5 |
so hello everyone how are you uh in this video i will be explaining the problem longest palindromic substring and this problem is a medium level problem and a good question and the idea to solve this problem is not that difficult to understand but it may uh like it may take you some time before it finally hits you when you are doing the problem for the first time so let's uh the video format will be first i will be explaining the approach the idea to solve this problem through uh the visual doing a dry run and then i will be coding it so the problem basically says that you have been given a string s and i have to return the longest palindromic substring and you know what a palindrome is so for example in babad the longest paranormic substring will be bab uh so aba is also valid but we have to return the first one i guess or you can return any one so let's understand how to solve this problem the idea so for example this problem is mostly based on the expansion approach what the expansion approach is that uh since i have to find the palindrome there can be two cases either the palindrome is odd by order i mean for example if the palindrome is b a b okay and the palindrome can be even so the palindrome can be even b a p okay so what i will basically do is that uh since if i take the center of a palindrome and go on to expand from there i will see that things are matching so if things are it will match because it is a palindrome so i will keep on moving forward so it will always match so using that observation what i will do here is that i will take a center for example i will uh traverse through my string and i will say okay here let's stay let's assume if a is my center of my palindrome then what i will do is that i will expand from a i will go to b then again i will go to b here these are matching so i mean that uh i will know that okay three can be the best length and then i will explore further i will go to z and a and here i will say see that these are not matching it means that my best match was bab only so in this way i will get it so for example in this example uh test case ba bab is going to be the parent room so what will happen here is that i will go to b and then i will see okay b is matching so it is since it is the center then i will go to a and a from on the left and the right side i will see okay a's are matching well and good let's explore further so i will go to b bbs are matching okay that is really good then i will go further so what can happen is that it will not match either this can happen or if the string was only like this then what will happen is that i will go out of bounds so these two can be the termination cases so i will know that okay these things are not working out so i will go back step one step back and then realize that my answer is b a b so this is the case for uh if the substring palindrome paragraphic substring is of length art now what if it was length even you will be thinking okay if i am at a then i will go at a and i will go at b these two are not matching uh then basically i won't get any substring more than of length one so in case of even substring what was happening here is that if the sub paragramic substring is even it won't have one center it will have two centers so those two centers will be the center left and the center right so what will the everything will be exactly same but in this case what will happen happening is that i will be expanding from these two variables a's and a these two letters so i will just go beyond this and explore so for example if i am at a i will the my even paranormic sub paranormic substring expansion will be start from these two letters i will go one step ahead i will see these are matching and then i will go again one step ahead and these two are not matching so i will recognize that okay uh like if this was to be my palindrome then my best left uh letter and the best write letter would have been these indexes so that is the idea to solve this problem pretty easy to understand now let's code it quickly and it will be more clear to you so i hope and if you have understood the idea please like the video and subscribe the channel it really motivates me so let's begin so what i will do here is that i will make two variables int let's go full screen and the font is also 16 pixels great so what i will be doing is that i will make the two variables int best left is equal to zero and in best right is equal to zero uh these this is nothing but uh the best left and right i can get for the best longest palindrome these two indexes so i will it will help me return the palindromic substrate substring now what i will do is that i will make a for loop for int i is equal to 0 i less than what s dot size i plus and then in the for loop i will say i said that there can be two cases either the palindrome can be even or the odd or it can be odd so in case of odd what will happen is that i will call a function expand and i will say okay expand function here is your string s and this is your indexes i comma i so by i comma i what i mean is that uh in case of odd my uh like my left center and right center both will be pointing to the same letter okay that is what i mean by passing i comma i and also i will pass my variables best left comma best right so that i can store the i will pass them with reference so that i can store the best left and the best right and the second case can be even palindrome okay so in second case what will happen is that i will call the exact same function control c ctrl v and i will say this function hey your left center is i and your right center is i plus 1 so this is what here it was so for example i am at 2 i am assuming the palindrome is even so i will pass this as my second center so that's it and now let's write the expand function so expand function is going to be a void function void expand string s comma int l comma into r so l and r is going to be basically my left and right of indexes and then in ampersand best left comma int ampersand best all right i am using this ampersand because it will make it pass the through reference so that whatever changes i make in this function will be reflected here also so now what i will do is that first of all important thing i will set my boundary condition while as l is greater than equal to zero and then r is less than what s dot size and uh what s l is equal to s r as long as these conditions are valid so what i will do is that l minus and r plus what this means is that l is greater than 0 and r less than 0 is basically my these the pointers that i'm moving is basically a part of the string it is not going beyond before and after so this it is important that you place these conditions before this condition because uh it may it will definitely give error if this condition was in the beginning okay so after this what will happen is that my string will break after it breaks what i will do is that i will increase my l plus and i will decrease my r minus the reason for that is basically if i will be uh my string will end and then my l will be here and my r will be here in this case so i need to go back one step and from both the sides so that i am at the right place so aft after i am this what i will do is that i will update my best left and best right if this palindromic substring is the longest so if what i will do is that r minus l plus 1 is greater than what best write minus best left plus one then i will update my best left is equal to what best left will be equal to l and best write is equal to r so i have updated my stuff and then the problem is over now after this for loop i will have my best left and best right and then i only have to return the parandomic substring that will be s dot substring substitute so to use the substring function i need to write the starting position of my substring that will be best left and the total length of the string so the total length of the string will be basically this thing uh ctrl c ctrl v and that's it now let's run it something is missing uh s dot substitute best uh what no member sorry it was it should be suv substitute substring now let's run it again uh sorry it happens it is running now let's submit it okay so it has been submitted so that is the approach the time complexity for this will be big o of n square because one for this and one n for this because every time i'm calling this the worst case time complexity will be n square so that's the problem guys so if you have understood the problem please do like the video and subscribe the channel so thank you and have a nice day stay safe goodbye
|
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
|
590 |
be good here hey guys what's up it's Nick here and yeah I do a lot of twitch and tech stuff on YouTube whit sorry I do a lot of tech encoding stuff on YouTube and twitch so check the description you can find out anything about me but I'm doing a lot of elite I'm doing a leak code series where i go through every problem and explain it as i learn them and just do them in general so this is one of those videos so this one is an eerie tree post order traversal right and there's a lot of tree problems I've been doing and I think tree problems really easy if you go on leak code you can just go through them all really quickly there's only like 20 or something like that there's barely on each may be like 40 but should be pretty easy so there are a few known traversals for trees and some of the main ones are in order post order and pre-order and I just post order and pre-order and I just post order and pre-order and I just learned about this a minute ago and what pre-order post order and in order pre-order post order and in order pre-order post order and in order traversal really mean or the order which the left-to-right and route the left-to-right and route the left-to-right and route the left sub-tree the right subtree and the route sub-tree the right subtree and the route sub-tree the right subtree and the route are you know traversed right so in a post order traversal the route will be traversed last so the routes gonna be the last thing you know I'll put it here right so we see one is the last thing in a pre-order traversal the route would be a pre-order traversal the route would be a pre-order traversal the route would be at the front of this list and in an inorder traversal would be in the middle that you know the route would be processed in the middle traversed in the middle of this you know I don't know if that makes sense you should look it up on your own your to really understand and we just went over it but so if you see what it's you know in post order it should we should see you know we have 5 6 3 right 5 6 3 2 4 1 so we got left subtree right subtree and then the route I think the I don't remember it was a minute ago but I think the right subtree is always after the left subtree and we're traversing and either inorder preorder a post order but I think post order I think it's just depending on where the route gets traversed right so this algorithm is not too bad all we have to really do here is implement a stack right a stack of nodes we have a node and the node has children right so one's children would be three to four threes children would be five six right makes sense right so we're gonna have a link list to implement our stack here so a linked list of notes and we'll have linked list equals new linked list right and this is gonna be called stack because we're gonna use a linked list implement a stack there's a few ways to make a stack but this is the one we're gonna do and our output is going to be a link to list of integers right this one's gonna be called output array for now equals new linked list shouldn't be too bad here and then the first thing we're obviously going to want to do you do this in almost all algorithm problems in some way shape or form you're going to want to check if something's equal to null in this case we all we get as a root node which is our tree and then we're just gonna you know obviously if the rows equal no we have no tree so we have no output really so we have an output array that's initialized to an empty linked list here so we'll just return well just return our output a pretty standard next thing we're going to want to do is add our root node to the stack because we know that the root node is not null and that's good enough for us so we'll add it to the stack we will now loop through the stack by checking whether the stack is empty or not so while stack is not empty this exclamation point means not and we're doing this in job obviously we'll pull the van owed from the stack right so all we have to do that is you know no node equals stack top poll last right there and then we will add the nodes value to the output array and we're not going to add it to the end of the output array we're gonna add it to the first part of the output erases output array dot add first there's a method in the linked list called add first in which we can add the value which is an integer value to the beginning of our output array right so as you can see one is going to get added first to our array right and I can explain how this works in a second in stack top hole last that's how we you know actually have our link to list called stack turn into a stack because pull last is gonna pull the top the you know the top of the stack basically right so I you know I don't know if I'm explaining this very well but let me just finish implementing this and then we'll try and do a final explanation here right then we're gonna loop through the node dot children right child this just loops through all the children so if we were at 3 this would loop through five and six the five and six value nodes and then we're gonna add these to the stack and it'll repeat the process until we've traversed the whole tree right stack dot add just child right very easy and then all we have to do is actually just return our output array and our output array is gonna look exactly like this if we run the code it should work should be great here yeah I just give it a second sorry my Wi-Fi is just give it a second sorry my Wi-Fi is just give it a second sorry my Wi-Fi is pretty bad yep there we go output is expected just as we wanted and then we will submit it and we'll you know will see accepted here twenty two point five three percent leak code for some reason basis it's run times sometimes on Wi-Fi so we might see up sometimes on Wi-Fi so we might see up sometimes on Wi-Fi so we might see up different percentage here so don't always be discouraged by you know the faster than percentage here because it's not really they're very accurate so we let me just explain this one more time so we have two linked list and one of them will be implemented as a stack one of them will be just a list of integers we add the first we have the root if it's not equal to null and then well stack is not empty which it won't be until we traverse the entire tree we pull the last element of the array which is just gonna pull the top of the array you know basically the last element in the array is the top of the stack that's why it's a stack because as we put things into the array you know the last element would be like the top of the stack right and then we're going to be adding the value of the that's we pull from the stack to the first element of the array each time so in the first case it would be one would be a root because if we look at the description one would be our root we add root to the stack right here so the stack is literally just a node with the value of one you know no when we pull last the only element is 1 so we pull 1 is equal to node then we add 1 to the array so ones get added into the array so the output array is just an array of 1 and then we go through the children 3 to 4 right 3 to 4 we animal it's the stack the top of the stack is now going to be 4 and then we pull 4 da-da-da-da-dah keep going for his next da-da-da-da-dah keep going for his next da-da-da-da-dah keep going for his next element two three five six five that's pretty much it I'm gonna do pre-order pretty much it I'm gonna do pre-order pretty much it I'm gonna do pre-order and inorder to so if you guys want to see those check it out but hopefully I did an okay job at explaining and you kind of understand how it works a little bit I highly recommend going through all the true problems I think you'll get a really good idea about true problems if you just go through them all I'm still learning as I go and I'm still trying to get better at explaining these so thank you guys for watching please subscribe please follow me on Twitch on whatever and just you know check out the description and see what else if you thought this video was good if you thought the video sucked comment below and you know maybe I'll take your advice into consideration maybe not thanks for watching really appreciate it have a good one
|
N-ary Tree Postorder Traversal
|
n-ary-tree-postorder-traversal
|
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[5,6,3,2,4,1\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The height of the n-ary tree is less than or equal to `1000`.
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null | null |
Easy
| null |
946 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem validate stack sequences we're given two integer arrays pushed and popped pushed is supposed to represent the sequence of elements that we are pushing onto a stack so this is the order that we would push elements onto a stack like this so like one two three four five but it's not just that simple because actually we do have some popped operations as well so in this case we are going to pop the fourth element first that's going to be our first pop operation So based on that let me ask you should this pop be executed before or after we add this Five Element probably before because we can't really pop the four if the five is in the way we only pop from the top of a stack so just running through the simulation here we're gonna add one we're gonna push two we're gonna push three we're gonna push four we pushed all four these but now we're gonna pop four so we pop that now we are looking to pop five but five isn't here it's not at the top of the stack so the only way we can pop it now is if we go ahead and push it and thankfully there is a five here available for us but let me ask you what would happen if this five did not exist popped is supposed to pop a five but clearly it doesn't exist here and there's no more elements left for us to push so that brings us to the ultimate question that we're trying to answer here are these sequence of operations valid for a stack we're told that we have to push these elements in this order and we're told that we have to pop elements in this order and after all of these operations we should be left with an empty stack well technically in the prompt they tell us the stack is initially empty but they also below the problem clarify that pushed and popped should be of equal length therefore by the end of this we should be left with an empty stack that's kind of why it's important to read the constraints at the bottom of the problem that's a little Pro tip and in this example if we did not have this 5 over here let's assume to make these two arrays equal we also didn't have an element over here this would be impossible but for the real example where we do have this five we push this 5 and then we are looking to pop it so we pop the five then we're looking to pop a three thankfully that is at the top of our stack so we pop the three we then pop the two we then pop the one and then we are left with an empty stack so in this case these are valid operations for a stack so we can return true in the other case we would have returned false one last Edge case you might be thinking of is what if we got to a point Let's ignore this but let's say we pushed a 4 onto the stack that's great we can go ahead and pop from the top of our stack the four but what if we had a sequence where we pushed then a three and then we pushed another four how do you know whether we're supposed to pop this four or we're supposed to pop this four with this operation thankfully this case will never happen because they do clarify for us that each of the values in each of these arrays is going to be distinct that's why this problem is possible if they ask you to solve it without this constraint it would not really be possible at least not without a little bit of backtracking I think but in this case we are able to solve this problem with a single data structure where the memory complexity is going to be o of n we are pushing and popping each of the elements so the time complexity is also going to be Big O of n so let's code it up now so I'm going to first initialize the stack well it's going to be empty we're going to go through every number in our pushed array we know for each number we are just gonna push it to the end of the stack in Python you can do append so of course we're going to push before we try to pop but after each element is pushed this could be the element that we are looking to pop how do we know if it is well we look at the beginning of our popped array so probably we should keep track of what position we're at in the popped array let's use a pointer for that I'm going to go ahead and call it I so what are we looking to check we're looking to check if the element in popped at index I is equal to the last element in our stack in Python you can take negative one to check the last element or you can do the length minus one and if this is the case then we are looking to pop from this stack there's a couple edge cases here though we might not just want to pop a single element we might want to pop multiple consecutive elements in a row so instead of making this an if statement let's make it a while loop but now that we've made it a while loop and I actually forgot to mention this we also after we pop the element from this index we probably want to increment our eye pointer as well but what happens if we increment this so much that it goes out of bounds then this is going to give us an index out of bounds error to ensure that doesn't happen let's make sure to check that I is less than the length of pop and let's do that before we even check this because if this evaluates to false this won't even execute there's actually one more Edge case here can you spot it what happens if our stack becomes empty then this would throw an index out of bounds error so before we do this let's also check that our stack is non-empty you can just that our stack is non-empty you can just that our stack is non-empty you can just check that like this in Python at least now we won't get any errors and this will do exactly what we want it to do but by the end of this Loop how do we know if this was valid or not well our stack should be empty so we can actually just return not stack if our stack is empty this evaluates to false the opposite of that is going to be true so we return true if it's non-empty we will we return true if it's non-empty we will we return true if it's non-empty we will end up returning false so let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Validate Stack Sequences
|
smallest-range-ii
|
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._
**Example 1:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\]
**Output:** true
**Explanation:** We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
**Example 2:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\]
**Output:** false
**Explanation:** 1 cannot be popped before 2.
**Constraints:**
* `1 <= pushed.length <= 1000`
* `0 <= pushed[i] <= 1000`
* All the elements of `pushed` are **unique**.
* `popped.length == pushed.length`
* `popped` is a permutation of `pushed`.
| null |
Array,Math,Greedy,Sorting
|
Medium
| null |
363 |
today we're gonna be working on neat code question number 363 maximum sum of rectangle no larger than k it's very similar to the other one where we actually found out the sum of any sub array inside the 2d array but this time the only difference is that the sum should not exceed uh k so you have to find the maximum one which is no larger than k and it is guaranteed that there will be at least one rectangle with the sum no larger than k okay so the way we're gonna be doing it is uh is basically we're gonna uh like divide the problem into a sub problem uh in order to find it so there's going to be some iterations in there so we first in the so again our one loop is gonna go cover all the rows and then the other loop is gonna be uh going from uh so basically when we have selected one element on the left side we're gonna be uh we're gonna have one pointer going uh through every single one of it and again in the third loop we're going to be incrementing the columns too so uh what we're going to be making use of is the so when we are finding the uh we're gonna be making use of the tree set uh like a binary searched uh tree uh so that we can find the least uh key which is greater than or equal to uh like the right minus left like the pointer pointing to the uh forward location in the row and the point the left was going to be the pointer point into the previous location in that so we actually want the ceiling function of the binary search tree and that's how we're gonna be doing it so let's just put our loops in place so m is the matrix.length number of rows matrix.length number of rows matrix.length number of rows and n is the number of columns okay and initially our answer is going to be a minimum number integer dot min underscore value okay now for and i have our row one it's gonna start with zero and our row one is gonna be go up to our total number of rows right and then r1 plus okay now then we're gonna have uh basically we're gonna keep a sum uh from like the uh from one row to another row so we gonna say end array is equal to new end and the length is going to be equal to n which is the total number of columns okay our the next loop r2 is gonna start from r1 and it's gonna go up to again total number of rows we have r2 plus okay and then we're gonna have we also need to increment our uh our columns so for and uh c it's gonna start from zero and see it's gonna cover all the columns and c plus okay and what we're going to be doing is like inside that area c which we uh created to calc uh to keep like the uh to keep the accumulated results so far so for that one we're gonna say r2 and c and then our answer is gonna be we're gonna make use of math dot uh max we're gonna make use of um like uh a helper function here answer we're gonna call it max um sub array we're gonna be sending our uh array uh total number of uh columns and the k which we should not exceed okay and once we come out of these loops we can just return our answer so the way this function is gonna work is like it will be returning uh it will be returning an end and it's called max sub uh sum sub array and end at a and n and okay we're gonna have a tree set of an integer as we said we're gonna be using the bind research tree uh to basically find the least key greater than uh like the greater than the accumulated result which would be the right minus uh so far my right minus uh our next uh our forward pointer minus and the k so we're gonna call it bst it's a new preset bsd dot add okay we're gonna start with the zero and then we're gonna say our answer is basically equal to a minimum value and then we're gonna loop through so we're gonna loop uh through the array so uh we're gonna say that for and i equals zero right is equal to zero right so we're gonna have two pointers one is i is equal to zero the other one is the right is equal to zero and then we're gonna say we're gonna keep going until the i as long as the i is less than equal to n i plus okay what the right is gonna do is to accumulate the result of the array up to i and then we're gonna have integer left which is basically equal to vst dot ceiling uh right minus k yeah because we want to make sure that the right minus left is always a less than or equal to k so that's why we are saying that the that left is basically the ceiling of right minus okay and then if the left is not equal to null right if it is not equal to null that's the reason we are using it uh we declared it as an integer so uh if that is the case we're gonna update our answer which is the math.max update our answer which is the math.max update our answer which is the math.max between the answer and the right minus left and then once we are done with the slope we can return we can have to do two things actually uh once over here we have to update our pst with uh with the right and then once we are done we can just return the answer okay looking good and it works
|
Max Sum of Rectangle No Larger Than K
|
max-sum-of-rectangle-no-larger-than-k
|
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.
It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.
**Example 1:**
**Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2
**Output:** 2
**Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2).
**Example 2:**
**Input:** matrix = \[\[2,2,-1\]\], k = 3
**Output:** 3
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-100 <= matrix[i][j] <= 100`
* `-105 <= k <= 105`
**Follow up:** What if the number of rows is much larger than the number of columns?
| null |
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
|
Hard
| null |
269 |
hello there a few weeks ago I talked about this question 1953 verifying a alien dictionary which is that we've been given the ordering of the characters for some alien language and also a list of the words that is supposed to read to be sorted based on not ordering and we want to where to find that so I'm working on the example we have hello and Lee code we just compare the characters in these two words in the adjacent two words location by location we find the first difference which is H and L since that hello comes before Lee code we kind of want to verify that H it's coming before L and according to the ordering it's indeed the case so it's fine that these lists of words are sorted based on this ordering so it's given the ordering and the list of words we want to do this verification so it's relatively simple the question I want to talk about today is called its 269 alien dictionary it's kind of the opposite of that so given the list of words that supposed to leave the piece or database or some unknown ordering of the characters in the language and we want to derive that deduce the ordering so some big notes before we look into the detail of the examples is that there might be multiple valid ordering of the letters so we can return any one of them that's fine so it's basically that what I'm guessing is that the code correctness checking system here is just going to take your take the ordering that your function returned and the world list of words being given to you and just directly call this solution from 953 if that passes see you're fine that's for this so when there can be multiple valid orderings quick example is that if we have something like a C and a B we can derive that a see how spam has to come before B in ordering in this alien language but that does not see anything about a suppose so we can actually just insert a other possible locations here you know a CP or CBA or even see a B all this race should be fine because all we need to know all we need for the list was this two words to be sorted is that the C has to come before a B if that's the case the ordering of the location of a doesn't really matter so that's what the numbers the notes care says the other notice that if there is no valid ordering to satisfy the two to make sure that the words being sorted in the list then we can return an empty string indicating I guess indicating that there is no ibadat or during a quick example is that zxz so when we compare Z and X we find that Z has to count before X but when we compare X and Z the second pair we find that the Z has to come after the XS so it's a immediately we have a contradiction there so that's indicating that there's no possible ordering for this case to work so let's look at the example one it's a little bit more generous so we can use that have to I guess I'm more insight about this question what this person is really about so let's look at that example so this is now input so we compare this word by word and try to kind of deduce the orderings when we compare our wrt and wrf what we can find is that T has to come before F we compare the second pair wrf and ER we can determine that W has to come before e when we compare e-r has to come before e when we compare e-r has to come before e when we compare e-r and ett what we can see is that R has to count the 40 and we'll compare the rare lost a pair ET t and our ft t we can see that the e has to count before R so that gives us the pairwise kind of hovering all we need to do is to rearrange this in a line so it's kind of like you should be w 2e e to R and R 2 T to F so it's a linear sequence strictly linear sequence of ordering of this Phi 5 nodes so 5 characters also no it's if you treat this like a linked list or a graph a directed graph so the carpet has become notes and we basically doubler derive the path of traversal in the graph if you want so this is the ordering w e RTF which is see the be also here so for this question we actually only have one valid or it has to be this any kind of adjustment to the orderings here will cause this list of words to be the relatively ordering to be violated so we now see it's a it's pretty much a graph traversal a trough graph question the technical term i guess for this question is called topological sort I'm not sure if you learned this in CS fundamental courses but even if you don't you kind of say it's not for this particular question this particular one we want to start the traversal with W we can you know you feel just kind of rotating it you will become a tree the W is like the root node here the reason it be that W is the root notice that it has no incoming links so we just the scans through this view graph here and we find the node with no incoming edge it has to be the root so we start from there and either we do BFS or DFS we're gonna traverse the graph with the ordering w/e RTF you know it doesn't ordering w/e RTF you know it doesn't ordering w/e RTF you know it doesn't matter whether you choose BFS or DFS in this simple example here but we just Traverse to what traverse and we can get the ordering so that's that tells us that we wanted to traverse in the graph to come up with the ordering so let me actually just write a little bit more complex the example because this is kind of like a degraded version of graph it's more likely singly linked list so I'm gonna create some more complexity in there so that we might be able to compare the difference between BFS and DFS in solving this problem just by the way both of those can work just fine let's say that we have a graph that kind of a like splitted in three ways in the rarest kind of position I'm just randomly saw some characters in there maybe a queue here and back to them so I'm use arrows to indicating the edge here I'm gonna do is that this good enough closing up anyway here's just a slightly more complicated graph that let's say that we kind of derived based on the sorted words here in the list whenever we do a comparison like a TN FF we draw an edge between those characters and we come up with something like this a little bit more complicated but we can arrange them by the direction of the ignored the edges to put the source node towards the left and the target node towards the right and topology it looks like you know kind of like a level two level if you just compare this tno are in the same level are is slightly later as this even further q is sort of is sandwiched in between o and M if you compare the vertical level kind of thing if you want to sync reasoning about the BFS but for DFS it's quite obvious so you just follow the links and you traverse towards the right they've the deeper the depths it's a it's more towards the right in this graph here so if we do DFS search the what kind of altering that we want to do you know when you think about the binary tree traversal the postorder pre-order in-order of the postorder pre-order in-order of the postorder pre-order in-order of course there is no I don't think in order makes any sense gear just compare a preorder and postorder we actually want to do a post order traversal so let's say that we started with W we chose to go R and as you know in the DFS kind of fashion once we process the s which there's nothing happening afterwards we do a post ordering of as and then backtracking to our we can do our add the our to the ordering so I mean let me just put anything here once we processed our we'd back to W but W has still have stuff we should visit we find T since that the stuff that T points to RN s already been processed we can do a poster ordering of T here and then back to w still have work in the bottom here so we go to o M so M has nothing there so we can put them here back 200 to Q the only stuff that Q have pointing to has already been processed so we put Q here and O and back to W so that way we derive be the kind of like the reverse ordering of the characters so topological orderings if you know the technical term for this order so if we do DFS we are gonna end up with the reversed order if we do post order traversal on this graph post order DFS traversal on this graph and also we can do BFS when we look at the nose gear W is gonna be on the first level so the first level is going to be W the second level is gonna be at the nose that just the one link away from W it's gonna be our T and O know that we can directly put T onto the T and O onto the ordering those are fine because it only has one in order incoming links from W if we you know pretty much process to all the nodes that comes before it you know in the in case that in the kind of a BFS search when we process W we decrement the in order being incoming edges to T and O by one and there then we can know that there are no notes that should come before T or so we can put them onto the order here but for our it's not the case because R has two incoming edges once we process the W there are still one more node s that needs to be processed before our in order to make us we are be able to put our onto the ordering so once we process the T we can actually put our there so we will come up with some kind of ordering like Q and n here that's the ordering we're going to derive if we do BFS so shown on this graph so both are valid then try to reverse this to do a comparison I guess W o Q and keep our s so looks yeah but both are fine just the foot DFS it's w oq m and w TR is it's more like it's the DFS fashion but for the second ordering it's a wot r SQ and it's more like the level wise BFS search results but both are the valid results so we can do either DFS or BFS the good thing about BFS is that you have this incoming links kind of like criteria for help us to determine whether we should put the node on to the ordering if there are loops which can be because the case here the xD she tells us there could be loops so when we look at the graph tier Z and ax will process the X we decrement we will find that it's actually the you know we couldn't even find a starting node to process this graph in the BFS kind of fashion because every node has exactly one incoming links we're not gonna be able to find the route to start the traversal so that's obviously not a good sign for this question in the very beginning so what if we have something like this here Z ok so day 2 X and there are a cycle here X 2 y so when we process the Z we decrement the in edges 2 X so it's a decorated decrease the front to 2 then we still couldn't put this on the ordering and things that there are we process pretty much everything towards this left and this thing has a in order that's larger than 0 that's not a 0 meaning that there must be a cycle so we can put our should terminate early on so based on the in you know the Inc degrees for every vertices in the graph if we do BFS search we can actually turn it in early on based on we can automatically terminate it early on the ordering I'm not going to be filled up because there's no chance we're going to put X onto ordering if the if there is cycle here so in the end we just look at the length of the ordering that which that we generate compared to the vocabulary size and we can know whether we finish the BFS search on the not for DFS we have to have explicit code to handling the cycles so for that reason I'm gonna code up the BFS search code first and then do the DFS so just a little bit of summary here DFS is going to with his four BFS we want the adjacency list and in degrees tack decremented in degrees for four notes when it reached zero means we before you so that at the time we can be safely to put that the note on to the ordering and if we do DFS the only thing that we need is a Jason C list so we do this postal order so it's gonna be something like for next note and a DJ list of this particular node we're gonna call the DFS function so after we process all the notes that's done after that and in the ordering then we can put the push back we can put this the node onto the order so that's kind of the post order kind of a ordering then we just reverse the ordering to get the final result what one note is that we need to have code in DFS to handle cycle so that's pretty much the fuel line summary of the difference between the BFS and DFS it's required inputs and how the demand logic in there so yeah let's code up but the BFS version first so first thing first is to construct the graph so well aníbal is the in degrees of the nodes and the adjacency list so I'm gonna just look up in my notes here so that I don't spend a lot of time writing mistakes so this is to convert the character get the unique characters for each words and then do a union to reduce that to the total unique nodes characters in this vocabulary so that's coming up with the total vocabulary their vocabulary being the no it's the alphabets total alphabets for this language here that's not getting up from this line here then we initialize this hash map to store the all edges which is Steve from no.28 Steve from no.28 Steve from no.28 to notes and we're gonna populate this in the inner for loop afterwards and then is the in degrees in here every note has a zero in degree incoming edges in the beginning and we're gonna have the array to store the ordering list two-story order in the ordering list two-story order in the ordering list two-story order in which initially to be empty so the graph processing here is for the pair of words we're going to check the character part of a character in the corresponding align the locations in the word if we find them to be equal we just continue otherwise we will that's indicating there is a difference so that we can form the edge between the two nodes so that's if they are equal we can continue otherwise we would do c2 will have an incoming edge from C 1 so we just increment the in degrees for C 2 and they're going to be our edge from c1 to c2 so that's the populating the adjacency list and that the in degrees statistics when we handle the first in equal equality there we pretty much can be done because compared the stuff afterwards doesn't make any sense if we have a break throughout the full loop we won't actually compare the lens of these two words so that's to handle the case when we have something like a B C and a B if that's in the ordering is totally wrong because ABC has to come after a B in whatever ordering so just to catch that we can put an analysis statement here so this is a when we doing the graph processing part we can already terminate if we find the case like ABC to a B in the word list so it's a it could potentially save a lot of unnecessary in traversal afterwards if the graph is not valid to be big to begin with so to do BFS we're gonna use a queue so what's going to be on the queue in the beginning is the nodes like W which has no incoming links so that's K we get that funny taking a difference between nodes and the key is in the in degrees which is the nodes that has no in degree that's exactly what the notes like W are they has to be towards the red left in the ordering so that's our starting point is deed BFS search just pop a note from the queue and we can add that to the ordering so that's pretty much that we added app W to the ordering then we want app and T ou R to the queue so when we add the node to the queue we want to decrement they're in degrees because we pretty much you use the edge there so we can decrement the in degrees and if the node has no the in degrees becomes zero we can actually put them onto the queue so this requirements checks prevents the cycles being leaked into the be getting into the traversal so otherwise we will end up with I guess kind of like a infinity looping here so the this guards into in that and since that we don't put that the cycle into the queue onto the queue we actually save a lot of time that if that actually happened so this is a BFS search nothing special popping off a node added to the ordering and documented the degree because we actually utilized to the edge so we can determine the degree for the next node when we actually processed all the nodes that's before this next node that's indicated by that knows in degree drop to zero we can put the next node onto the queue so that the next time it pops up you will be added to the ordering so in the end we just returned the ordering in the string format and that's when there's no cycle so if there are cycle the ordering gonna be only including those were those nodes that's not in the cycle so it's gonna be short you know because the notes that involved in a cycle are not going to be put onto the queue based on this criteria so the if cycle exists the lens of the Audrey is going to be smaller than the number of total nodes so this is the code for this DFS solution let me quickly check looks okay nope okay so I should have returned false I should return there is exactly one case clear ABC and they be exactly like the one that I think it's a thought about okay so in that case we can we should have turned the empty ordering so it's a empty stream there that makes sense so yeah it's working just relatively quite slow and so that's BFS let's cut up at the modify this into a DFS solution so for DFS we don't need the in degrees that's just quickly summarize go over the summarization here again we're going to process the note traversal the nodes in DFS fashion you know postal order kind of manner so we do DFS first after we processed all the nodes that after the current node we then put the note on to the order so as a result it's in the reverse order so in the end we have to return the order reversed and that will be code to handle the cycles in there the graph processing part is the same except that we can chop off the in degree processing there because we no longer need that but the adjacency list is the same then we're gonna use a hash map to keep track of the nodes being visited that we have visited and the fact it's a hash map and it's indicating that whether the node will cause a cycle or not so let's just quickly note here so the DFS function is going to be just taking a note and if note is we have our is it other already visited we let me actually code put the man logic here first and then deal with the detail of the DFS so we gonna do this well we still have notes we want to explore the in the DFS kind of fashion will pop it off pop a note off the I think I will use a set here this is a set it's a union it's a set we're gonna call this DFS function and it will populate the orderings it will put the note on to the orderings in the inside the function but this DFS should return whether it has detected or psychonaut so that we can actually terminate early long if we indeed find a cycle there if we has a cycle we're gonna return them to string early stopping otherwise you're gonna pretty much remove the notes from visited front notes and take a difference between notes and the visited so that pretty much means that we have done DFS search in this portion then we can remove all the notes in there from the total number of notes that we won't explore in the end we just return the string representation of the ordering which is reversed so then it's the detail for DFS before the if the notice visit so that we can just return the because we want to grab whether it has cycle or not we will look into their hash mark to return the note otherwise we would just before we go further into the graph we are not going to be able to tell whether this node is or caused a cycle so the way to determine it is basically you know if we do DFS we find T and go to R and go to s and if s has a link to T which we already processed in this particular DFS call then we know that there is a cycle so we can check the hash map to find out whether we have a cycle or not so in the beginning we just put the note in there and say you know as far as we know so far there's not going to be any kind of cycle cost about this node we go about the Explorer deeper when we find really fine a cycle will definitely mark this to be true in the so for the notes that's after this particular node the next node after the node we're going to recursively call DFS to explore that part if there is a cycle there or just a call it's the same story for the node here we know that the front node we will definitely leads to a cycle so we mark this visited node to be a cycle to be true actually we can just return through here just to terminate even earlier so once we processed all the nodes in and you know the graph that's towards the right for this given node here let's say W if we process all the notes there that's the final time we push the node onto the ordering so that's the postorder here and if it can succeed you know there's no breaking in intermediate here then we know that this node will not cause a well not cause the cycle so yeah actually I made a mistake here it should be true in the beginning we assume that you will cost cycle but if we can successfully explore the graph in DFS fashion without finding a cycle then we can declare that it's being verified that there is no cycle there so yeah I shouldn't I should think about this a little bit more carefully I talked about this earlier so we just returned this so how do we modify this to assist that in this case we also return that how do we modify this to be a little bit more concrete compact and I just do this but this will cause a little everything to be indented by one I don't like the look of that but I think it should be equivalent to two to the previous code either so if that's in there we don't even trigger this part we just directly return that otherwise we will try to populate the first then return that so it should be this set okay so this is pretty much the DFS code do we have arrows this is a graph processing all we dropped out is the in degree processing everything else is the same so when we process the graphing DFS version we use this visited a hash table to keep track of whether the nodes will call cycle or not and also whether it's being visited in the DFS search or not in doing the search there we just for the nodes that we haven't started the other search yet we're gonna grab a node there and initiate the DFS search if we have cycle we terminate early otherwise we mark all those nodes we visited in the DFS search to be visited and remove them from the nodes that we want to explore so that the next iteration of this while loop we end up with a smaller target to search this is a slightly inefficient because if we populate this visited by two consecutive DFS searches if we do the difference it doesn't matter because this it's gonna be upper bounded by the number of characters in the vocabulary which is likely to be constant so the time here is okay yeah so I think the code should work let's just run it III hard-coded this example there III hard-coded this example there III hard-coded this example there because I was when I was only testing it okay I guess I should try to submit this it's a slightly faster so I guess going back to the time and space analysis the graph processing here the worst case is the total number of characters in here so let's say that we have the strings to be the words to be pretty much or share the same prefix river loan prefix was just the one last a lot letters being different across the board then we pretty much the exam all the number of characters in the proportional to all the number of characters in the input so that's just an order of total characters in the input that's for time and for space it's a the nose here are the alphabet size the all the outer edges is upper bounded by the square of the nodes if we have in the crazy case if we have all the pairwise nodes there so it's the alphabet where the in degree edges is obviously alphabet size us again for the graph traversal part is it's the number of edge plus number of nodes in the imposed e FS ntfs so that's some very crude and also some time in this space I don't think you can go better than then this I think a DFS is definitely gonna be a little bit more space efficient not necessarily because we have a dis hash map here which is pretty much just doing the job for the in degrees so yeah so BFS you know it's a pre-order you BFS you know it's a pre-order you BFS you know it's a pre-order you come up with a pre-order so that come up with a pre-order so that come up with a pre-order so that why don't reverse that before DFS it's a post order in BFS you use the integrase to make sure that you process all the nodes that have an other smaller than you before we appended that character own to the ordering so it's pretty hard but for DFS esposo order we process all the nodes afterward after us then once that once those notes are had taken care of we put in ourself onto the ordering so yeah the visits here is doing the same job as in degree 2 to certain extent in two aspects one is to determine where we can put a note on to the ordering the other thing is to detect cycles yeah so that's the two solutions yeah I know it's being a little bit rough when I talk through this I like this question I think it's the level of difficulty is even it's hard it's even if you don't know topological sort you might still be able to work through the graph processing part and at least the partially finished the DFS or BFS if I'm interviewing I think I will go with the BFS because it's you know you pretty much a sinking from left to right and you have things taken care of before you actually put this on to the ordering so you don't have to do reverse so the reasoning I think it's a little bit more streamlined alright so that's it that's pretty much it
|
Alien Dictionary
|
alien-dictionary
|
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.
Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.
**Example 1:**
**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:** "wertf "
**Example 2:**
**Input:** words = \[ "z ", "x "\]
**Output:** "zx "
**Example 3:**
**Input:** words = \[ "z ", "x ", "z "\]
**Output:** " "
**Explanation:** The order is invalid, so return ` " "`.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.
| null |
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Hard
|
210
|
557 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem reverse words in a string of three even though this is an easy problem I think it's still a good problem to practice if you're a beginner it's definitely a good problem and even if you're not a beginner I would encourage you to maybe with easy problems like this try to time yourself try to do it as quickly as you can without having mistakes like try to get the problem submitted on your first pass and try to do it under 10 minutes maybe even under five minutes if you think you're good enough so we're given a string s we want to reverse the order of characters in each word within a sentence while preserving white space and initial order so it's kind of an extension of just reversing a typical string you can see here we're given a string that looks like this we're not just doing a naive reversal of this entire string notice how this word is actually this word just in reverse order so actually we're what we're doing is taking each one of these words and reversing it and how do we identify a word well you can see that in between each of them is a space character and we're guaranteed that there's going to be one space in between each word and there's not going to be any leading spaces or trailing spaces so that's the delimiter the space character is the delimiter that's simple enough now conceptually we want to iterate over this array we want to identify each word we might even be able to take this input and you know theoretically just call like a function called split it into their words reverse the words then join the words with a space character in between now that's kind of cheating at least in my opinion if you're just using a bunch of helper methods you're probably not tackling like the essence of the problem but who knows maybe if it's okay with your interviewer go ahead and do it this way but doing it the more Trading additional way we would basically iterate over each character until we reach the space character and at that point we would want to just reverse this and ideally we can do it in place now depending on the language you're using strings are immutable so at least in Python what I'm gonna do is convert this string into an array of characters or an array of strings and then we can actually do this in place and at the end we can go ahead and actually take that array and then convert it back into a string that should be pretty easy to do but here with this how do we want to reverse it well the easiest way is using two pointers we'd have one pointer at the left one pointer at the right and then we just swap these and then we shift the pointers inward so simple enough now one thing to keep in mind though is as we're iterating we're going to have a pointer we can call it I or we can call it the right pointer it's is going to keep going until we get to the space character okay that's easy so we know there's a space here so then we're going to start our right pointer here like one to the left of that now where do we start our left pointer well for that we have to keep track like for the first word it's simple of course it's going to be at the beginning of the string there's not going to be any leading spaces over here but what about the next word like over here now we have a second word called take well one thing we should remember is this is the last spot our space was so we can put the left pointer here or we could just take the left corner and set it to one plus this because we know there's going to be a new word starting over here and then maybe there's another space character over there and then we have our right pointer here and once again we solve the sub problem now this is the part where I said try to get the problem solved in your first pass because actually there are some edge cases before you press that submit button you always want to think about the edge cases that you might be missing think about it when we get to the end of the word what's going to happen there's no space there right but we still want to reverse this if we are only looking for space characters we're going to end up not reversing this word so we're not only looking for space characters but by the time we reach out of bounds we also at that point we want to say or actually not even out of bounds like by the time we reach the last character which we would know because it's going to be at the index length minus one by the time we reach here we know that this is also a word we got to reverse that as well but it's a little bit different than when we reach the space because remember what I said when we reached the space our right pointer is going to be one to the left of that we're going to initialize it here but by the time we reach the end of the string there's no need to take the right point and shift it to the left because the right pointer is here we don't want to shift it by one over here we want to keep it where it is so that's just another Edge case it's not super complicated but you don't know it until you actually dry run through the problem or at least walk through it in your head and yeah eventually you can get good and enough at this that probably you'd be able to solve this problem within five minutes and hopefully without having any bugs as well though I think like 10 minutes would be pretty good as well but here we would do the same thing just reverse this and by the time we're done with that we can go ahead and return the output so time complexity wise we're really just iterating over the input we might have to do it a couple times technically because we're iterating over and then we're reversing each substring but either way the Big O time complexity is going to be linear where n is the length of the input string technically if we are converting this into a list we technically are using extra memory but generally we don't count the output as memory now technically the list is actually not necessary but if you don't use the list you still end up having to use extra memory by just like the string manipulation by like taking substrings and then manipulating like this entire string so you know depending on how you see it technically we're using extra memory we're just kind of getting around the constraints of the language okay now let's code it up so the first thing I'm going to do like I said is just take the string and actually convert it into an array AKA a list and this is just because if we want to like take some index and reassign it to like another character we can't really do that with a regular string but we can do that with an array so that's why I'm doing this and when we return we do want to return in the form of a string so how do we get around that well assuming s can as an array it contains everything we need we can do this so this is going to look kind of weird at first but basically this is taking each character or each string inside of this list combining them together and this is going to be the delimiter notice it's an empty string because we're basically just joining all of these together without any new delimiter introduced but now we want to do the two pointer technique well I'm going to initialize the left pointer at the beginning of the string and then I'm going to take a right pointer and just iterate over the length of the array using a for Loop and we don't really want to do anything most of the time we're not going to do anything but when we reach a space character we gotta do something then or when we reach the end of the array meaning our index is at length minus one then we gotta do something what are we doing here we're going to reverse the string and we're going to use two pointers to do that but we don't want to mess up this pointer and this pointer so I'm actually going to take a couple helper variables temporary left and temporary right and I'm going to initialize them temp left is going to be at left temp right is going to be at right minus one remember because if we reach a space then we want to actually take the right corner and decrement it by one before we start reversing the string but also there was actually technically a case where if R is actually at the end of the string then we don't want temp right to be at R minus one we actually want to be at right or in other words we could increment it by one I don't know what's more readable if this is more readable or this is more readable but that's kind of what we're doing like depending on which one of these is true we want to assign temp right to the right pointer or right minus one we could have even initialized this with a ternary operator but I don't think that's necessary I think that would have been less readable but uh it's you know your opinion you can do it the way you want okay now at this point our pointers are initialized all we're doing here is just solving the problem reverse string I think that's its own leak code problem believe it or not and if you struggle with this problem I would recommend trying that problem first but here we're just going to iterate or be reversing the string while the pointers have not crossed each other and it's pretty easy in Python you can do that without a temporary variable so here we're just going to be swapping the characters in these respective positions and when we do that we take the left pointer increment it by one we take the right pointer and decrement it by one and that's pretty much it now the last thing don't forget we did talk about it in the drawing explanation but it's easy to forget what do we want to do now next time we find a string we want to be able to reverse it the right pointer is fine it's going to be iterating through the string what about the left pointer though we do have to update it we don't want to keep it at the beginning of the string so at this point we're going to set left equal to right plus one y right plus one well if right was pointing at the space character we want left to be after that space character we want it to be at the beginning of the next word what if right was at the end of the string well then this Loop would probably stop anyway and then we'd return the result so it works in both cases now let's go ahead and run this to make sure that it works and as you can see yes it does and it doesn't look like it's super efficient here and that's probably because a lot of people probably solve this problem just by using like the built-in functions that I using like the built-in functions that I using like the built-in functions that I mentioned earlier so don't let that like percentage confuse you this is a relatively efficient solution thanks for watching if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io thanks for watching and out neatcode.io thanks for watching and out neatcode.io thanks for watching and I'll see you soon
|
Reverse Words in a String III
|
reverse-words-in-a-string-iii
|
Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
**Example 1:**
**Input:** s = "Let's take LeetCode contest"
**Output:** "s'teL ekat edoCteeL tsetnoc"
**Example 2:**
**Input:** s = "God Ding"
**Output:** "doG gniD"
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `s` contains printable **ASCII** characters.
* `s` does not contain any leading or trailing spaces.
* There is **at least one** word in `s`.
* All the words in `s` are separated by a single space.
| null |
Two Pointers,String
|
Easy
|
541
|
464 |
hi guys welcome back to my channel so I hope you're already doing well in this video we are going to solve the problem can I will and the problem is very much interesting because it includes three concept uh bit fast Game Theory and diamond from with all these concepts are so much interesting and they are not too easy to gasp so these kind of problems are usually seen completely running not in typical DSC but if we are tackling these then we should definitely solve these random problems so I suggest you to write this problem on your own so let me first explain this problem after that you should go and try this problem on your own to solve it so the problem is saying that we are having a game the that is 100 game and we have to play us T1 and P2 and we have to return if the player one can win the win or not so let's discuss the rules of this game you are given to win teachers the first one is Max suitable and teacher and the second one is desired portal so what are these integers at each chance every chance you can choose any integer between one to Max visible and teaser of the history is from zero to maximum integer and you have to reach to desired total if any of the player reaches to desired return then he will win so we have to also assume that both players are playing optimally so let's discuss one test here so that you will get its idea so we have the maximum suitability that is 10 year and these are total is 11. So the player one will start the game and if he chooses any of the number like to three anything then uh the second player will choose like the first one next to this two the second one will choose nine so he will reach the desired total so he will win the match if the first one two is one then the second one will choose 10. then he will also reach the target if the first one chooses nine then the second one chooses two then also second one wins so there is no way you can uh yeah there is no way so that the play and one can win the match so we will return false here and uh here on the second test here is the maximum suitability is a stand and the desired total is zero so if player one it doesn't chooses NN teaser or chooses zero instance then he will reach the Target and then we can return true because player one can win the match and uh so I hope you guys tried this question on your own so let's move forward and see how to approach these kind of problems so uh what we can do at each chance we have options to choose the integers between 0 to Max visibilities we can select any number between 0 to Max visible and teaser and it is also mentioned in the problem that if we choose end user then we can't use it again so we can use a number only once now let's suppose the solve function will return true or false for a chance if the player can win the game or not so we will Define a function sort which will return true if the parent uh playing the player which is currently playing wins the game or if he doesn't wins the game then it will return false so what are the possibilities at its each chance so for at each chance we have we can select any integer from 0 to maximum T Cell so we will run simply a formula for that at each chance so what do you do if we can choose Bayer 20 so we if we can choose I therefore choosing that integer if the opponent loses the game then we will return to and we will try this for every eye that is if uh if I select suppose I select 0 and I don't win and I will try by selecting one I will then I will our type by selecting two and selecting 3 and selecting four so I will try each possibilities and where if anywhere I win the game then I will return true otherwise finally I will return false after this for Loop but now there is a problem that how we will keep track of the new integers which has already chosen so for that we can use bitmask kind of thing so if you are not familiar with bitmask it will uh will be a little bit free for you but I will try my best to uh let you understand the concept plus we need to solve this problem so uh let's suppose we have initially a number K and it will be called bitmask and we use this number to check uh which numbers are available to use and which numbers are already chosen so we will use this K only to detect that so what we are going to do we uh just write binary representation of K and if it is 0 then it will be zero and each bit of K denotes an integer that we can choose if it is if the bit of K is 0 it means we can't we can use that intercept it is not already Susan if any bit is one it means that number of integer is already Chosen and we can't choose it anymore so uh from rightmost we can see that the zeroth bit indicates that integer 0 the first bit indicate the integer one so suppose we have chosen a sixth bit sorry the integer six so what we are going to do we are going to set this bit to 1 and we can use this formula to set a bit I believe that you will be familiar with this kind of weight manipulation formulas so this is all about weight passing and we are going to use this in our codes it will be more clear to you if you see the code so let's move forward and uh see the code for this problem so to uh so that it will be more clear to you uh so this is the code for C plus code for this problem yeah it starts from here if the desired total is zero it means we don't it's kind of a base case so if the desired total is zero means we don't need to choose anything then player one will easily win the match so we are returning to E because the player one is already one now uh we are calculating total that this total means that how much maximum sum we can create using that Max disable integer up to how much we can uh total we can get so how we can calculate that Suppose there is an integer n and we want to find the sum of all natural numbers from uh update up till n so how we can find that you can use a formula into n plus one by two so we are using that simply maximum switchable integer into maximums usable integer plus one by two so we have calculated the total that we can make with this maximum sizeable integer so if that total is less than desired total then we can't make it equal to our desired total by use by using any integer so we can't get a desired total anyo so we are going to return 0 because in that case also player one is not going to win the match if total is equals desired total then we are returning maximum suitable and teaser is odd if it is odd then we can uh the pair one will win the match otherwise it will lose and how we can check this just uh see this case if the maximum switchable integer is even then any of the players will end up at 2 this the second player will uh use his last chance to finish the game and if he finishes the game the player one will lose and if it was 11 then the player one will finish singing so the player one will win the game that's why I am returning here if the total is equals to desired total then we are returning the maximum suitable and decent modulus means if it is odd then it will return true if it is even then it will return false now we have a DFS function which is taking two numbers maximum switchable integer and desired total and we are passing here the beta mask a that I already told you about K so what we are returning yeah in DFS if the t is 0 means desired total is less than or equals to zero then uh we are simply returning 0 that no one will win the match now what happens if uh Let's ignore this line for a few sentence we are running a foreign so we are checking if that width is set or not so how we can check on the bitmask like if K and we are doing end operation if uh one left shift I if the is bit is not set means we can use that with and by using that bit uh what we are doing we are if that we can use that bit then we are running that function again DFS function since we are playing the game again with uh by setting that bit and if the player Nest player will lose means if it is not EFS is the uh indicating that it returned false so if the select player here return false name e means he uses the game and if he loses the game that means the player one will win the game so we are returning one year and for every chance if you don't get any of uh we don't satisfy the zip condition then we will return here zero that play one can cannot win the match so this is how you can write this code and this DP is nothing but we are doing memorization so we have a DP array and if that is not equal to minus one we have this returning DP of K and I believe that you will be familiar with memoization technique so it won't be sort of for you so I hope you guys understood this problem well see you in the next video bye
|
Can I Win
|
can-i-win
|
In the "100 game " two players take turns adding, to a running total, any integer from `1` to `10`. The player who first causes the running total to **reach or exceed** 100 wins.
What if we change the game so that players **cannot** re-use integers?
For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100.
Given two integers `maxChoosableInteger` and `desiredTotal`, return `true` if the first player to move can force a win, otherwise, return `false`. Assume both players play **optimally**.
**Example 1:**
**Input:** maxChoosableInteger = 10, desiredTotal = 11
**Output:** false
**Explanation:**
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
**Example 2:**
**Input:** maxChoosableInteger = 10, desiredTotal = 0
**Output:** true
**Example 3:**
**Input:** maxChoosableInteger = 10, desiredTotal = 1
**Output:** true
**Constraints:**
* `1 <= maxChoosableInteger <= 20`
* `0 <= desiredTotal <= 300`
| null |
Math,Dynamic Programming,Bit Manipulation,Memoization,Game Theory,Bitmask
|
Medium
|
294,375,486
|
809 |
okay here we go on hello everyone welcome to another video for a mocking interview on so this is a random well semi random question I pick picked up on late code I've never saw seen this questioned and it's the first time I ever read the description and I would try to make this video as short as possible but given that I've haven't prepared anything maybe like I could get stuck but I'm not gonna edit it out I'm gonna make this video as this so I can know if there's anything that I can improve this is like exactly a situation as I would be in a coding interview except for I'm not going to see whether is medium would rare or you know or easy you are hard um so let's look at a question sometimes two people repeat letters to represent extra feeling okay this is somewhat of a practical question I like it rice such as hello but they spell like hello hi become high and this strings like Hello we have groups of adjacent letters that are all the same for some given string as a query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation so extension and choose a group consisting of character C and AB some number of character C to the group seven at a size of the group is three or more okay for example starting with hello to all the station doing extension or in the group to get hello and get this but we cannot get two O's since the group O is size less than three also we could do another extension like double l extend into multiple elms to get hello okay interesting so we're gonna need to find blocks like groups of adjacent letters that are the same and perhaps count them then the querying word low would be stretchy because of these two extension operations query and hello okay cool fine okay hmm interesting okay I think I'm probably gonna need some standard library that's what I love about Python it's excellent for toting interviews because it's got a lot of you know tools it's got a lot of useful libraries import good boy so what group I can do if I remember it correctly it's going to be something like this right say h-e-l-l-o oh it's gonna be like it's say h-e-l-l-o oh it's gonna be like it's say h-e-l-l-o oh it's gonna be like it's going to return to polls like technically it returns an iterator like a generator right that can generate each time so it's gonna be like H and then usually H which is said to pull and then oh sorry ancient one page e and Tripoli I think it should be like this and Double L and D oh and a triple left right so first of all and to say group s well because the group ID returns actually a generator or a page reader it's going to be for a single use and then it would be better if I can store it in a manner like this like a to pull a list of tuples or it is like X and one Y or X Y and wrote by big ass okay so now I've converted the Y until like there so it's gonna be instead it's gonna be something like 1 3 2 click right this is going to be the group s so then I want to have a helper function basically says deafness like and stretch is a strain they can stretch like for a word right and coming a word because it's words well so all right locally I'm going to create a word goodbye well let's see yes provide word and the four enter and actors in well I don't actually need to use it I'm not going to use it more than one set okay but I'll need it index zero for the crow pass right and on the same X and equals two 3s I now it's the first one and if blent say city equals so the basic the most fundamental scenario would be the length equals to end then we do nothing right we do nothing and else we can change later and if it doesn't then F excuse me thumb hole in CC sorry if n is less than 3 right then it's not actually an extension so falses and if it is continue right else and return foot so we don't need this block or and we can change this into unequal if the length doesn't match and for n is less right or n is less than the length of CC between false exactly okay then this is the end of helper function now and right in the end Herman I okay I think there's something more to it that's returning and I need to know if the length is actually matching how can I do this I don't you know let's say return f five equals length of grade s plus 1 right listen if there's any extra groups it should be invalid exactly and then for word words huh so the result is zero stretch increment dance and turn us let's first test it whoopsie Oh the grouper has no length hmm I wonder what's it gonna be a grouper well that kind of sucks curse I'm remembered goodbye incorrectly let's say this is definitely not gonna work that's know with so what is grouper then group by oh I need to cast it wow oh wow okay I guess the grouper is also if they feel River so that's kind of sucks so okay that's alright minor setback right so Plan C cleanser first okay Dave can definitely come up with a solution for the length of an iterator right duh Python come on CeCe then they should do it come on why is this era dammit well nevermind pretend you never saw it and let's change the test case into well this pretty much tested every edge faces right I can say like something like this should also be what you can submit come on Oh bummer I forgot to check if the character matches affects the smoked save and return pops right and I forgot to test it right I forgot to test if it what if it doesn't match for something like this right a b c right what's unexpected a CCA exactly so submit yay faster than 99 Wow oh well I guess group I helped a lot and probably not a lot of people have sought this but anyways I made it thank you so very much for watching this video and well um I cannot get a length of iterator I mean of a generator so I need to power I need to cast actually converted or tested in this case is not necessarily casting right it's not typecasting actually after using this the generator is destroyed right it can only be used once so on a less copied am i right LS like I could he had a deep copy of the generator is going to be used and gone once one for all so when I convert it into a list I've destroyed properly destroying the generator if I got it right pleased to confer them on yourself like verify if I'm getting it right on your own read about it either tools it's a great library of pipeline and yeah that's everything so it's going to be the end of the video bye-bye
|
Expressive Words
|
preimage-size-of-factorial-zeroes-function
|
Sometimes people repeat letters to represent extra feeling. For example:
* `"hello " -> "heeellooo "`
* `"hi " -> "hiiii "`
In these strings like `"heeellooo "`, we have groups of adjacent letters that are all the same: `"h "`, `"eee "`, `"ll "`, `"ooo "`.
You are given a string `s` and an array of query strings `words`. A query word is **stretchy** if it can be made to be equal to `s` by any number of applications of the following extension operation: choose a group consisting of characters `c`, and add some number of characters `c` to the group so that the size of the group is **three or more**.
* For example, starting with `"hello "`, we could do an extension on the group `"o "` to get `"hellooo "`, but we cannot get `"helloo "` since the group `"oo "` has a size less than three. Also, we could do another extension like `"ll " -> "lllll "` to get `"helllllooo "`. If `s = "helllllooo "`, then the query word `"hello "` would be **stretchy** because of these two extension operations: `query = "hello " -> "hellooo " -> "helllllooo " = s`.
Return _the number of query strings that are **stretchy**_.
**Example 1:**
**Input:** s = "heeellooo ", words = \[ "hello ", "hi ", "helo "\]
**Output:** 1
**Explanation:**
We can extend "e " and "o " in the word "hello " to get "heeellooo ".
We can't extend "helo " to get "heeellooo " because the group "ll " is not size 3 or more.
**Example 2:**
**Input:** s = "zzzzzyyyyy ", words = \[ "zzyy ", "zy ", "zyy "\]
**Output:** 3
**Constraints:**
* `1 <= s.length, words.length <= 100`
* `1 <= words[i].length <= 100`
* `s` and `words[i]` consist of lowercase letters.
| null |
Math,Binary Search
|
Hard
|
172
|
1,091 |
hello everyone welcome to day 16 of lead code may challenge today we have question number 1091 shortest path in binary tree in this question they have given us n cross and binary matrix and we have to return the length of the shortest clear path in the matrix if there is no clear path we have to written minus one a clear path in a binary matrix is a path from the top left cell to the bottom right cell such that all the visited cells of the path are zero and all the adjacent cells of the path are a directionally connected that is they are different and they share an edge or a corner the length of a clear path is the number of visited cells to this path in example one they have given us two cross two grid and we have to find the way if the cell like we are on the top left corner and we have to reach the bottom right corner and we can only move in the cell if it has the if had its value zero so we have to in order to reach this we have like the direct path and the length is two that is what we have to written as an output and we can clearly understand this question from this example let me change its color in this question we have to make sure that we are on this cell and we can only move if it is zero so first thing is if this cell if the top left corner is one then we cannot move further and we cannot reach to the bottom right corner so that's why in this case we will written minus 1 similarly if in this case bottom left sorry top right is 0 then we will create like we will start finding the length to reach the bottom right of the grid but if the bottom right is one then of course our answer will again written minus one so in both these cases are right answers will be minus one so first this is the base case or the corner cases while starting the algorithm we have to check if the top left corner is one or the bottom right corner is one we just have to simply written minus one that is in no way we can reach down or if this is one there is no way we can reach if we reach till here also then again it if it is one we can't reach over here let's understand it from this example like how will we will move from top left to the bottom right so first thing is the basic approach we will use is bfs traversal we will maintain an array which will have its x and y index x and y axis it has like its x and y coordinates and with the value present in it so first we will create a queue and in the queue first we will add it's axis that is it's on like on x it's 0 on y it's 0 and its value is 0 and now as we are pushing this in the cube we will make sure that after pushing it we will make this as we will give this value as 1 so that if there is no self loop like for example from this one it can move to eight direction that is here in this cell diagonally upward downward left diagonally up and down in these direction it can move and it can only move if the cell has the value zero in it so if we just give zero and it will move in all the direction when it will come to this it will again go to this cell and there they will just have the self loop in them so to avoid that condition when we are pushing this in the queue we will mark this as one so now our this cell has become one and what we will do is and their count is one like we are on the length one so this is the count so their count is one and now we will pop them and then we will add the a direction it can move to but we can only add those cell who has the value zero so out of this it can go in this direction or in this direction but as both of these have one so it can only move to its right then we will push this that is zero comma one comma then it will go into this it slides will become two so that is the length we will push this and then we are done and then we will move this out of the queue and make it one so that the they will there will be no condition of self looping and again from this we have three ways like we can choose to go here or here but as this is one we cannot choose it so we will push other two ways in the queue so first one is zero comma two and its length will become three if this thought to move with this direction but if what if it thought to move it this direction then in the same fashion it will move it can also move from one comma two and its length will also be three and then we will move this out and make it one and it has an option to move only in this direction or in this direction but as it is one it can move only downward so what we will do is we will add its level that is one comma two and with the value it has the length till here the length is three and if it is moving downward its length will increase by one so with the value four and then this is done then we will pop out this and this is we are already over here so we will mark this as 1 and we will add this so this is our and index that is 2 comma 2 and its length is 4 that we have pushed in it and after what if we reach here we will just return the length and we reached over here and now this when we will pop out this from the queue we already know that it has the value one so nothing to do continue and if we are reaching there we will just written the answer four so what we understood is there are two ways of reaching this bottom right corner that is using this direction or but if we are using this direction its length would be one two three four five its land would be five but if we are using this direction from this and then this its length would be four so obviously we have performed the q operation and over here it's performing this way like when we are on the length four it will reach faster to the bottom right then the fifth one so that's why it's taking the minimum length and that is how we are returning it let's move to the coding but first thing what we will do is we will find its length grid dot length integer n is equals to grade of 0 dot length and then first thing is we will check if grade of comma 0 have the value 1 or grid of m minus 1 and n minus 1 have the value 1 simply we have to written -1 that is we simply we have to written -1 that is we simply we have to written -1 that is we can't find the clear path okay neither wise what we will do we will create a queue of integer array name it as q and q we will put where it is on x-axis where it is on x-axis where it is on x-axis where it is on y-axis and what it its cost y-axis and what it its cost y-axis and what it its cost and then we will make this particular 0 comma 0 as once to avoid the self-loop and the as once to avoid the self-loop and the as once to avoid the self-loop and the basic bfs function we will form if q is not empty then first thing is we will find its size while size minus is greater than zero q dot we'll pull this from the queue and what we will make sure we will after this we will create an array which will cover all the a direction then we will pull from the queue the first i mean the 0 comma 0 that we have pushed over here that is this then we will pull it and what we will do we will check if this is equals to m minus 1 if they have reached to the bottom right we will just return the length if it's not then what we will do then we will loop in all the direction and we will find the row point of zero plus direction of zero and column point of one plus direction of one and if we will check like all these points are lying between the boundary it's not out of bound so that is what we are checking over here putting the condition that's no point is going out of the grid and the most important thing the grid should have the value 0 then only we are going to push this in our queue add new integer array which will they will give the row the column and the point which it already have plus 1 because its length is increasing and then simply once we are done with this that grid value will change to 1 no self looping and then we will return if this spells all cool it's good we will get the point over here if not it will written minus one let's run it okay i have done this wrong this should not be this yeah now it will work that's submitted we are done
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
502 |
hi everyone it's all today's daily challenge that is IPO so here uh in this question we are given that lead code is starting its ipu soon and uh they need to sell a good price of its share right so they have to work on some projects to increase their Capital before this IPO they only have limited resources and they can only finish at most K distinct projects before the IPO so we have to um help lead code design the best way to maximize its total Capital after finishing at most K distinct projects right so we are given n projects and out of them we have to choose at most K distinct projects so out of these end project the I8 project has a pure profit of profits of Pi so this is Project will yield some profit right so for these end projects we are given this profit sharing and similarly we need to invest some Capital to start the project so that is given inside of this Capital sorry so we initially have W capital and when we finish a project we will obtain its pure profit right and that profit will be added to the capital right and we have to pick it most K distinct projects to maximize our final capital and we have to return the maximized Capital right so um this is the question right so let's uh see using this test case so let's come here now so here in this case k is 2 so that means we can choose at most K projects right and our initial capital is W so initial capital is zero so let's see so from the capitals array we see what we have to see right we have W here right which one uh out of this capitals we will pick one that we can afford right so right now our capital is zero so we can only afford the first project so we will choose the first project and against the first project we have we will have a profit of one so what we will do we will add this profit to our Capital so our Capital will become one now in the next iteration you will see that okay so now we have chose one project so we have we can only choose two projects so out of two we have chosen one so now we have to choose another project so let's see which project that will be so again you will come to this Capital array and you will check the optimal choices so you can see that W is one so you can choose either this second project or the third project right but if you want to maximize your Capital you need to choose the one with the maximum profit right so we have two choices so out of these choices the third project here is yielding us the maximum profit so we will choose the third project only so what will our W become 1 plus 3 that is 4 right so I hope you are getting the question right so let's see let's take another test case right let's take another test is okay now let's see so uh let's say our W was 20 right and we have a profits array as 10 uh one two five this is our profit sharing and let's say our capitals array was 20 15. um 5 and 10 right now you see uh okay and what we have to do we have to choose at most three projects K is 3 here right we have to choose at most three projects let's say only two here also so we have to choose two projects out of uh this and we have to maximize our W so let's see what we will be getting so here you see W is this so out of this Capital array what are our optimal choices so all of these are optimal choices right we can choose any of them we can invest in any of these projects because RW is 20 right and all these capitals are less than W right so we can choose any of these now but what the thing is we need to choose the one with the maximum profit so what will we do so we are seeing here that we have 20 here right and here also we have 20 so we can invest 20 here so let's say we invested 20 here so against 20 The Profit that we are getting is 10 only right so if we choose 20 The Profit we are getting is 10 so um we have to Simply add it here so we'll be getting 30 then what we have to do we have 30 inside of our W now again we can choose any of these projects what we will do we will choose the one with the maximum profit so not 10 has been deleted we have chosen this project right we have chosen this project so then we will choose the one with pi so now W will become what 35. now what do we have to do okay so we only had to choose two projects here okay so uh our answer will be 35 in this case right so what are we trying to do we are just trying to you know trying to minimize this Capital not so much but yes we are uh we are not trying to minimize this what we are checking for the optimal Capital right optimal Capital means that the capital whatever capital is present inside of this should be less than uh our current capital right should be less than a current capital and what are we trying to do with the profits array we are each and every time we are trying to take the maximum of the profit array right so how can we get the maximum each time so you will say that we have the profits array we will take it and we will sort it so now let's say we have K here so first thing is for sure that you will be iterating for k K number of times so we will be trading for K number of times and inside of this you will be you know trying to sort this profits array again and again the time complexity that you will be getting is this k n log n right so n is the length of the project the number of the projects that are given to us so this will give us tle so how can we reduce this complexity the question is easy I guess now that you have understood it I guess it has become easy for you but the thing is how will we you know take the maximum without having to increase the time complexity how do we you know take the time complexity less than k n log n right so at that time Heap comes to our rescue so he Heap will give us the maximum value now what is he Heap is a data structure like it is a binary tree so but it is a special binary tree where if you are considering Max heat its root will always be greater than its children right greater than its left and its right so this is Heap so um he is nothing but um priority queue right priority queue also does the same thing and its implementation is like Heap right so we will be using priority queue or Heap in this case right so what will how will Heap help us you will just take the top of this queue right you will just take the top of this queue and you will be getting your maximum profit right why because priority give us what it assigns a priority to each and every you know element inside of it as we said in the case of Heap right let's say we have three here and 2 here and one here right so if we have these values if you delete this will again reshape itself and it will become like this right so each and every time the top right or the root of the Heap is always maximum and in the case of mini it is always the minimum so there are functions inside right they are called Max cpify and Min heapify if you want to learn more I'll um link you uh some videos or sources to read about it right so now let's see how we'll be using it so as we said we have to take the maximum profit at each iteration so for that we will be taking these profits inside of the priority queue now how will be putting these inside of the priority queue the thing is that these capitals right that these capitals they have to be less than W right so first we will have to kind of associate these profits and capital because right now it is like it will be having a different iteration so what we will do we will pair them right so how will we pair them we will create a vector of pairs so for the first value will contain of course the capital because what we want to do is we want to you know if you want to um maximize The Profit what you will try to do right you will try to take this Capital also you will try to take the least Capital right so that is why we will be putting capital as the first element and profit as the second element so that we can sort this Vector of pair to choose the optimal Capital right so for that we will create a vector of pairs and after our Vector of pairs is created we will be creating K number of times and inside this K number of times that I will tell you when we will code it right what we will do while we are traversing inside of it okay so let's first see let's first create this uh pair right a vector of pair so what will you what will we do first let's take its uh size right that are the number of the projects here now we will create a vector of pair int comma int let's call it projects right now what we will do we will create this plus how will we create this um pair we will simply say projects Dot pushback make the pair of these two quantities that is put Capital first and profit after it so our Vector of pair is created now what do we have to do for getting the optimal um profit we need to minim we need to you know minimize this Capital so we will take a so we will sort this right you can simply sort this so when you will sort this it will be sorted according to the first value right so we will be getting projects dot begin and projects dot end right now we have sorted this Vector also now I said when we will do traversing inside of it I will tell you something right now int I is equal to zero Also let's take okay now here what we will be doing first thing is we need to create the priority queue now you may ask that while creating the priority queue right um we will be trying to you know just put the profits inside of the priority queue let's also create the priority queue here we will only be priority queue and PQ let's say right so our priority is created so what we are trying to say is if whatever the capital is if it is less than w right then we have to take it that is what we are saying so let's do that what we will do we'll say I should be less than n okay and this um Capital value right this W should be greater than the capital value that we will be currently at so what we will do we will check the projects inside of this sorry inside of this we will check the first element of this projects right we will say projects I DOT first element is the capital that we will check if it is less than equal to W then we can choose that project so what we will do we will say priority queue dot push and we will push the value of um this profit that is associated with this particular Capital right so we'll say uh projects of I Dot what we will do now um second value right second value will contain our profit right now after this we'll do I plus and now you will say that why are we creating this Loop only once and why did we not you know create this outside here why are we not creating the priority key outside that is because when you consider this case right the very first case you had the you had a capital of zero only right so you considered this particular first project but after considering first project you have gained a profit of one so now your W is has become one right so this quantity W is increasing right so we will first of all we will only go inside of this Loop only when these both conditions are true right so initially in the first iteration what happened we did not exhaust all of these values right we only exhausted the first value right and after that this condition became false so quick quite outside of it right so this is that is why we are having this while loop inside of here okay and that is why we are you know checking both of these conditions right because our W will be increasing right so we can so our number of optimal choices will be increasing at each iteration right because W is forever increasing that is for sure but for like we have to choose only at most K right we have to choose at most K so if you want to choose at most k then um then you cannot obviously choose all of them but then you have to check right the profits so that is why we have created this priority queue you have to take the maximum profit each time right then what we will uh so there will be a case when priority will become empty right so let's say right here also you started with zero let's say we are starting with zero but here the capitals are given one right if we are at such a scenario then we will not be getting any value inside of the priority queue so why will we iterate here right if we don't have anything inside of our priority queue why will we trade in this Loop so we will say that now we cannot have so this can happen at any iteration right that your W cannot be um used to invest in any of the capitals because it is less so for that we will check if our priority queue is not empty right V Q Dot empty right we will simply check that okay if it is empty then we will break out of this Loop because now we don't have any optimal choices to make otherwise do what just add whatever value is at the top right as we saw the top or the root of the Heap and do what remove this right so say p q dot remove this value because we should not use this value again right because after we choose this 10 profit we should remove it so we will remove it and after all these iterations we will simply return RW right that is our capital so let's quickly run it okay so it's accepted so that is how you have to solve this question
|
IPO
|
ipo
|
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects.
You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it.
Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_.
The answer is guaranteed to fit in a 32-bit signed integer.
**Example 1:**
**Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\]
**Output:** 4
**Explanation:** Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
**Example 2:**
**Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\]
**Output:** 6
**Constraints:**
* `1 <= k <= 105`
* `0 <= w <= 109`
* `n == profits.length`
* `n == capital.length`
* `1 <= n <= 105`
* `0 <= profits[i] <= 104`
* `0 <= capital[i] <= 109`
| null |
Array,Greedy,Sorting,Heap (Priority Queue)
|
Hard
| null |
48 |
hello all welcome to code hub today let us solve the lead force daily challenge and the problem is rotate image you are given a n cross n 2d matrix representing an image rotate the image by 90 degrees clockwise you have to rotate the image in place which means you have to modify the input to the matrix directly do not allocate another 2d matrix and do the rotation uh here they have specifically mentioned that we should not do it we should not use any extra space so we have to modify the input matrix itself so let us try to observe from the given input one two three four five six seven eight nine and if this is the input matrix then now what is the output matrix sound four one eight five two nine six three how it is formed i just think this matrix is rotated at 90 degrees this 7 4 1 becomes the first row 8 5 2 becomes the second row 9 6 3 becomes the third row that is each and every columns or each and every columns are actually my rows so actually the brute force approach will be if but it is in reverse order right one four seven is the column but it isn't reverse order seven four one should be our first row and eight by two should be a second row so if our brute force approach will be for each and every column so uh what actually we have discussed that in brute force we will be uh storing we will be going for all the columns and we will be storing it into a one vector and we have to reverse that vector and we have to insert that uh vector into uh our into our resultant matrix that is this is our first column one four seven we have to reverse this seven four one next we will add to our resultant matrix next we will go to our next column two five and eight we have to reverse this which is nothing but eight phi two and we have to i will be adding it to our resultant matrix then we will be going for your next column 3 6 9 and we have to reverse this 9 6 3 and this will be adding it to our resultant matrix so we have got the 90 degrees rotation but we have to do it in place we should not do any we should not use any extra space so what we can do is we can actually do it by using an algorithm by as uh algorithm is as follows first step will be uh taking the transpose of the matrix and the next step will be uh where you will even observe what we are doing once we transpose it actually we have order be the transpose of this input matrix the transpose will be 1 4 7 2 5 8 three six nine what you can observe is you we have for each and every rows it is in reverse fashion so we are once we are transposed the matrix if we reverse all the rows we will get the resultant 90 degree rotation matrix that is it 852 963 as you can see this first step will be transpose the matrix and second step will be reverse each rows so that's it the this will be the algorithm and what will be the time complexity for this solution the time operative will be r of n into n which is n square uh it is a square matrix and then the space complexity will be order of one since we are not using any extra space so what we can do is we can just first particular the size matrix dot size we have taken the size now how we are going to transpose this matrix is the tricky part here actually one two one three and the four five six then seven eight nine so actually when we do the transverse matrix this one will be coming to this first position itself four and two will be changing its position four will be going to the first rows second position and then the seven is going to the first rows third position then this two will be coming to this second rows first position then this five stays at this same position and the six is replaced by eight is nothing but this position this third row second position is swapped with uh the second rows last position so what we are ultimately doing is uh for each and every rows we will be traversing for in i equal to 0 i less than n i plus for each and every row we are starting i till that j is going till n and j is plus we have to just swap the matrix of i j and j i matrix of ai if we swap this we will be doing this we can just try to uh dry run so that it will be more clear uh first the i is 0 and j is also 0 and 0 then 1 is factored to its 2 himself so for the next iteration j becomes 1 so now the 0 1 is nothing but this 2 and 1 0 is nothing but 4 so two and four is getting swapped next j becomes two and uh i is zero to three is wrapped with two zero is nothing but seven so as you can see that three and seven is fab and three comes here and similarly for the next iteration the j should not start from this zeroth index j should start from the i index so that's what we have declared this j is equal starts from i so this is what literally we are doing the transpose of the matrix once we have done the transpose of the matrix we have to reverse each rows and our problem is done for reversing each rows we will do like this for auto ampersand row in my matrix we can just use an stl function reverse off row dot begin comma row dot n so this will automatically reverse us this matrix so the timeframes will be r of n square so we are we don't return anything function and we can try to run our code and see whether it is getting accepted or not let us see yeah it got accepted let us submit our code as well so what we got accepted so hope you like this solution and uh let me know in the comments if there is any suggestions to be made let us see in tomorrow's lead code daily challenge until then bye
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
1,704 |
Hello friends welcome to my channel here soled Cod problems and prepare to the Cod interview today's problem number 17 o4 determine if string Hales are alike you're given a sing s of even length sped the S into two halves and of equal lengths and uh let a be the first half and B be the second half two strings are alike if we have the same number of vowels so it's a e i o u and app case a e i o u notice that s contains uppercase and lowercase letters this isn't true if a and b are alike otherwise returned false so let's do it's easy Level Pro problem so we don't need to find some extra difficult solution first of all let's check both halves of the string and count how many Wows they have if they are the same then return true otherwise turn false so let's do it first of all let's define the length of string it's Len of s uh we don't need uh full length of string we need a half so let's find it so in our case N is a half of length next thing we need variables for count of vowels it's C1 and C2 and both of them equals to zero and now we need to check both halves and count how many vowels in each half for first half for each character in s we can check first half using this syntaxes and uh it's sub string from zero index to index n and if C in we need to write a string contains all WS so it's a e i o u and app case a EI i o u and increment C1 variable so now we have a count of WS in first half and let's define and count Fs in second half it's sub string from n to the end of string and the next thing we same except we count WS in and save it in a variable C2 and finally let's check if C1 equals to C2 that's it let's check test it's uh the simplest solution test Works permitted yes it works it pretty efficient this algorithm has a linear time complexity so it's all but uh time and uh of one memory complexity because we didn't create any variables uh depends on the length of s so that's it for today thanks for watching see you tomorrow bye
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
1,223 |
everyone will convene here so let's discuss about we click on national fifty-eight third question dinosaur on fifty-eight third question dinosaur on fifty-eight third question dinosaur on simulation so add a simulator generates a random number between one to six and there is extra constraint that saying number I cannot be generated more than roll makes I consecutive time so given an array of roll Max and an integer n that represent the number of rolls so we being asked to written the number of distinct sequence that can be generated since the number of de state sequence can be very large so we've been us to modulo it by this number here so it can be represented in the integer so let's take a look on the first example so roll mixture consecutive types of one there can be happen is only one 2 is equals to 1 also so this is like 1 2 3 4 5 6 so 6 can be generated in a 6 consecutive time at max so given an N of 2 how many distinct sequence we can produce so we know that if there is 6 value we can generate and we're only two times there are 36 combination however if the dice the first dice sorry at the value of 1 can only be generated at most one time so let's say first time we generate the 1 second time we roll we cannot generate a 1 so 1 is out of option there and 2 is also out of options so from those 34 36 so minus 2 so it's equals 34 so we know the best case is when n is equals 1 it will always be 6 right like as long as they're all max is not 0 so we see here there are all mix constraints non 0 and also problem X it will always be 6 because we are generating number between 1 to 6 and N equals 5,000 so this 1 to 6 and N equals 5,000 so this 1 to 6 and N equals 5,000 so this question can be solved by dynamic programming so how we go to the software so it's basically we made a key of the DP itself using the 10 and is the number of throw left and what is our last role and then how many times that last run fail you happen consecutively so when we see here so when n equals 0 so means no more wrong left so the there is one unit sequence which is empty so empty is a one distinct sequence right when the ends equals zero so other when the n is larger than zero we go through the number of one to six and then get our maximum consecutive role and in our DP we see here we also memorize what is the last number that happen and how many times it is already happening so here you see when we do a recursion we let's say we choose a number I so let's say is equal zero which is a failure of 1 so we read us the end by 1 and Ron Max is the fixed value so we keep passing it down or we can also make it a global variable and the last number we pick is I so this number is the number we pick and if this number is equals the last number we pick then previous consecutive row we added by 1 otherwise it we reset it to 1 okay and after that we look through all 6 we know how many solutions are there we add it up and then we put it in that catch for the yeah for the next time so when there is a recalculation like the and happened to be the same and last number and constitution from happens to be the same then we will not calculate it again but here you see we return immediately using the key so the key here is how many times roll off rolling left and what is the last number and how times the consecutive all happened and after that yeah basically we remember the model load with a number that given from the question and then yeah we written it yeah that's it for this question thank you for watching see you on the next weekly contest
|
Dice Roll Simulation
|
graph-connectivity-with-threshold
|
A die simulator generates a random number from `1` to `6` for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (**1-indexed**) consecutive times.
Given an array of integers `rollMax` and an integer `n`, return _the number of distinct sequences that can be obtained with exact_ `n` _rolls_. Since the answer may be too large, return it **modulo** `109 + 7`.
Two sequences are considered different if at least one element differs from each other.
**Example 1:**
**Input:** n = 2, rollMax = \[1,1,2,2,2,3\]
**Output:** 34
**Explanation:** There will be 2 rolls of die, if there are no constraints on the die, there are 6 \* 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
**Example 2:**
**Input:** n = 2, rollMax = \[1,1,1,1,1,1\]
**Output:** 30
**Example 3:**
**Input:** n = 3, rollMax = \[1,1,1,2,2,3\]
**Output:** 181
**Constraints:**
* `1 <= n <= 5000`
* `rollMax.length == 6`
* `1 <= rollMax[i] <= 15`
|
How to build the graph of the cities? Connect city i with all its multiples 2*i, 3*i, ... Answer the queries using union-find data structure.
|
Array,Math,Union Find
|
Hard
| null |
433 |
Hello friends today I'm going to solve liquid problem number 433 minimum genetic mutation so we are given 8 character long string which is a gene and then we could choose from a c z and T so four of these characters to form a gene which is an eighth character along we are given a start chain an end chain and an area of chain uh bank which consists of all the valid mutations so we need to find the total number of mutations to reach from start to end um and all those mutations would be valid mutations and we are also said that they start the gene may be or may not be in the bank and the end Gene is in the bank and the next thing is that if engine is not in the bank that means that we are not able to reach the mutation so we just return -1 here just return -1 here just return -1 here now one thing to um keep in mind which is not actually given in this um problem statement is that a mutation is when there is a difference of one character in a gene so here this is a gene and this is another Gene and the character different here is T so that is only one character difference right so that is one mutation so basically the problem comes down to finding the mutate the gene which is only one character difference and then if that is the case then we need to find the minimum number of mutations so we are actually using BFS because minimum number means we are always looking for the shortest path and BFS gives us the shortest path DFS gives us the longest path but the BFS is the shortest path and DFS may be um faster I'm not sure correct me if I'm wrong in the comments below but yeah so for this problem um what I'm going to do is I'm going to first gonna calculate find each um find the character difference for um okay let me just start writing the code so what we'll need so first of all in BFS what do we need a q right so let me Define a queue and now uh we need to find a mutation um so for that mutation I'm just gonna create a new function here so that my code is managed um and we need to check for each of the characters we check um if they are not equal foreign count equals to zero and we are going to increase the difference count if the count is greater than equals to 2 which means that there are more than two character differences that is not a mutation so we return a false else return to and now for the BFFs I'm just I'm gonna start with my uh basic uh like by insert by queuing um the start Gene so dot um so I'm gonna cue starts in as well as the number of mutations so for the start there is zero mutation right um so I'm gonna cure that also I need a visited um sit keep track of all the uh all the mutations that are being visited because if not then we might end up in a loop so suppose I start with this I push this in into my queue then I Traverse the Next Mutation I found is this one which is one character difference the next one I find is this one which is one character difference in the bank now for this one there are this is also one character difference and this is also one character difference right but we do not want to go back to this because then we'll be stuck in a loop um so that is why we need a visited list so here I am gonna insert the start Gene to my list and now while q that length while the length of the queue is not equals to zero I am gonna um shift I'm gonna pop the Q and check if this um value in the queue is equals to the end chain so let um Jean and M equals to shift if Gene is equal to n which means that we have reached the end we return our um steps to reach the mutation if not then we need to find a mutation for this chain so for each so we need to travel through each of the elements in the bank and check okay we need to check if v i s might visited dot has if it has this Gene then we just you just continue if not then lit um is mutant is mutation equals to idea mutation and then Bank the character bank and now if it is a mutation then I'm gonna push it to my cue um I also need to push the number of mutations so I'm adding one each time and then I add this value to my visited list I visited set um sorry I add it here because the next time again if I don't add it here the what happens is I'm looking for suppose I'm looking for a visited I'm I suppose I'm looking for mutation for this one right so I check for each of the elements I start from my equals to zero this is zero character distance so I return of false um and then this is one character different difference right so I return true and then it's added to my queue but if in case I didn't have these so I check for this one well I guess we could have that button but okay no problem so yeah so okay so now we have added um it to the visited layers now what we are gonna see is so this will just continue looping so if we did not find any of the so now we added um our elements mutations to the queue and we are looking for each of the elements in the queue but in the end if none of the mutations is equals to the N which means that we cannot reach the end chain that is when we return -1 -1 -1 let's run our code okay what is this again visited okay we need a set object great let's submit this cool
|
Minimum Genetic Mutation
|
minimum-genetic-mutation
|
A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.
Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string.
* For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation.
There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string.
Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
**Example 1:**
**Input:** startGene = "AACCGGTT ", endGene = "AACCGGTA ", bank = \[ "AACCGGTA "\]
**Output:** 1
**Example 2:**
**Input:** startGene = "AACCGGTT ", endGene = "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\]
**Output:** 2
**Constraints:**
* `0 <= bank.length <= 10`
* `startGene.length == endGene.length == bank[i].length == 8`
* `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`.
| null |
Hash Table,String,Breadth-First Search
|
Medium
|
127
|
1,047 |
hello everyone welcome to forest camp we are at 28th day of june lead code challenge and the problem we are going to cover in this video is remove all adjacent duplicates in string so we are given an input string yes as our input and we have to return the string again with after removing all the duplicate adjacent characters for example consider the first string given in the problem statement which is a bbac so now the first duplicate adjacent string is b and after removing it the string would become a c and again a is another duplicate adjacent string so after removing a also the string becomes ca and that is what we are going to return as a output so how are we going to approach this so if we are approaching this via a brute force wave then we will be finding the first adjacent duplicate string and after removing that we will be getting another string will pass on the same constructed string again to the same function recursively and find the next duplicate until we find no more duplicates in the string and that is definitely going to take quadratic time complexity so how do we approach this in a better way so we can trade in some extra memory in order to reduce our time so we are going to get the help of a stack to implement and find the duplicate strings in the given input for example if we are having a stack let's start character by character and input that to our stack until we find its duplicate so here in the given input string the first character is going to be a and let us insert that to our stack and the second character is b which is not similar to the previous character so we can put that here in the string and b enters our stack next character is again a b so in that case we have found a duplicate adjacent string that has to be removed from the input string so in that case instead of inserting that b to a stack we are going to remove the top b from our stack and next comes another a so here b is already removed so our stack is left with only a single a which means if we add that a to a stack which again forms a duplicate string so in that case we are again going to remove the top a from a stack and next comes c and a both c and a are not similar to what is the previous character in a stack so c gets into the stack and again a gets into the stack and this is left in stack after completely iterating our given input string and that is going to be our output so this is definitely going to take big o of n time complexity as we are iterating the given input string once and we go of n space complexity as we are going to implement this in stack but instead of actual implementation of stack we are going to implement the same idea in string builder and we are going to declare a string builder sb that is going to construct our output string from the input string and this is going to be added with a b and once it finds another b instead of appending it to the existing string builder it is going to remove that from our string builder which is nothing but the last occurred character in the string builder same way when it com come across another a it is gonna remove the last character from the string builder and add the rest of the characters to the string builder so this is very similar to what we have seen in the form of stack but instead of actual stack memory we are going to implement this using a string builder so hope you are understanding this approach lets go to the code now so i have declared my string builder and that is going to be my output at the last so i'm going to iterate my given string and let me take the size of my string builder so now the logic is simple we are going to check if the current character is the last occurred character in the string builder if it matches then we are going to delete that character from the string builder if not we are going to append it so yes this is it and we have to add one more condition if size is greater than zero yes let's run and try let's submit yes the solution is accepted and runs in seven milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Remove All Adjacent Duplicates In String
|
maximize-sum-of-array-after-k-negations
|
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Array,Greedy,Sorting
|
Easy
|
2204
|
1,662 |
hey everybody this is Larry this is day 24 25 of the legal daily challenge hit the like button and subscribe and join me on Discord let me know what you think about today's prom given two string a check of two string arrays are equivalent okay um they have to be in the same order so basically just checking account Asian okay I mean obviously if you can concatenate them and do it uh or whatever um but of course I think the idea of what they want you to do is just to kind of do like a two-pointer thing um except do like a two-pointer thing um except do like a two-pointer thing um except for you for each um each word or it's a way of word you have two pointers on each so uh yeah but here you can definitely just I don't know I'm gonna be a little bit lazy not gonna lie I'm in Seattle I drank a little bit so I'm gonna do this um and that's pretty much it the reason why I am I did it this way even though it's a little bit you know cheesy it's because it has the same complexity so sometimes when you use drain e functions it will uh be a little bit more expensive in some ways I don't understand but here this is linear and distant typing is linear so this is just going to be linear so I don't feel that bad about it and in fact um actually this is probably faster than it if you did it manually because a lot of these functions in Python is um I don't know how do you say it like they have a c version of it that's optimized for that reason so you know that's gonna be faster as well if you ask me probably I was wrong I mean 73 milliseconds maybe that's a thing but yeah um but signal Millennia this is how I did it last time I suppose so you can check that video you want to do it that way um it is faster but I feel like at that I don't know see this is why I did two years ago about the same thing um and that was 99 so I don't know I wouldn't worry that much about the timing with that's low of time it is definitely could uh go either way but uh yeah let me know what you think I'm lazy today I'm still in Seattle I you know whatever so um let me know if you have any questions but it is easy so maybe today is like a Best Day um so yeah stay good stay healthy took good mental health I'll see y'all later and take care bye
|
Check If Two String Arrays are Equivalent
|
minimum-numbers-of-function-calls-to-make-target-array
|
Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "\]
**Output:** true
**Explanation:**
word1 represents string "ab " + "c " -> "abc "
word2 represents string "a " + "bc " -> "abc "
The strings are the same, so return true.
**Example 2:**
**Input:** word1 = \[ "a ", "cb "\], word2 = \[ "ab ", "c "\]
**Output:** false
**Example 3:**
**Input:** word1 = \[ "abc ", "d ", "defg "\], word2 = \[ "abcddefg "\]
**Output:** true
**Constraints:**
* `1 <= word1.length, word2.length <= 103`
* `1 <= word1[i].length, word2[i].length <= 103`
* `1 <= sum(word1[i].length), sum(word2[i].length) <= 103`
* `word1[i]` and `word2[i]` consist of lowercase letters.
|
Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even.
|
Array,Greedy
|
Medium
| null |
1,641 |
200 Hi Guys Speech Was Doing Well So That Discussing This Problem Which Aims Account Soft Toys Friends From Now Onwards Will Be Discussing All The Problems Which Of Difficulty Medium And After Weeks Of Bump Into The Hard Words For Starting A New Twist Channel You Can Consider Subscribe Video Upcoming Videos So Let's Get Started Subscribe Number Of Friends And Subscribe To And Lexicographical E Software It Is The Definition Of But So Let's Get Started Is Oil Baikunth Let's Understand What Benefit Kal Order Is Basically You Can Influence Can Understand What Like Subscribe And subscribe the first increasing and decreasing subscribe in this lesson see sim for scissors lexicographical sorted in gray electronic back equal to see similar e two not like subscribe if you liked The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Length Lee Mein Aaye To And You Will See The Return Of The Length Of The Character 100 Number One To Three 500 subscribe and subscribe this Video not 2012 and Sohrab Return All Possibilities A Greater Noida Possibilities Doctor Possible For And equal to what will be singh vichar note lexicographical e should be eliminated dil hai so let's see what is starting from first exonerated amazon and liquid sismaur mist and it's coming up to date so to yash lo graphics date so to yash lo graphics date so to yash lo graphics software let's that end i do not lexicographical started similar oy idi dare not started and lost case it so let's account total a what are the number of trance subscribe affairs 4 free how to and one for the morning total b-15 so how to and one for the morning total b-15 so how to and one for the morning total b-15 so let's check the tarzan and you can Check Out All The Best Female Singers What's The Worst Thing That Can Come To Your Mind Would Like To Meet All The Length In 300 Feet For Job Carefully The Total Number Of Strings Consider Hair Return r20 5 That You Can Count Under-25 So Similarly If That You Can Count Under-25 So Similarly If That You Can Count Under-25 So Similarly If You have to write all the spelling of length and complexity will come into being the five to the power and that records you can check this little B-52 records you can check this little B-52 records you can check this little B-52 the power and so very high complexity and you will have to generate all the best results And this complexity shows and it is not possible for to David Samakya Let's understand what can be done on so but there are many types of questions you can see but servi like lose number of strength but in most questions like this and observation question you do you Will not for the length of the amazing total number of strings with no you have so in this test will be seen that the total number of restrictions were one similarly in the solar water logging in 12 test against the nh2 su which is best for veg दर r11 only की और की और इमेम्डिया रू की और की और सिमार्य पी पो है और है एक फैर कोंटंट 2 for veg दर r11 only की और की और इमेम्डिया रू की और की और सिमार्य पी पो है और है एक फैर कोंटंट 2 A number of things which are pending with this particular character is this particular practice so ambulance similarly for co four euro-5 ambulance similarly for co four euro-5 ambulance similarly for co four euro-5 ki is you tried to Absorb Samudra Things You Are You Can Easily See Debit The Answer Is The Meaning Of This Subscribe Button Here Idly Ending With Vivid To Subscribe To Quiz For Immediate Relief For A The Answer Will Be Three And Details Of All Three Lift To You Can See How Are you I show you all the strings are returned this is the bank voice and in these verses basically dec23 that I told three so you can clearly see that now what is this share like a gifted with only one and with know what we will not destroy evil Elements The Point For Example For Others Like This That Similarly The Answer Is 30 Chest And Similarly For By Its One Plus Two Plus Three Lines For Its One Plus Two Class Response Stand And Again For Is Desh Ko Kyun Abs Butt K Vijaypur Total Number Of Frames So an answer will always be the sum of all its values in three 60 all with as per 2nd test subscribe similarly for two [ two [ two yes sorry I don't know the answer will come up to five and verified similarly saving E F Coming from and so let's code top 100 I will be easy for coding oil let's let me clear this thing about a song that in the great sans piece om shri s what will be doing his job well planning there deputy approach and cleaning boy What is the role of VPN to here fifteen so are yes ifir rottweiler five stories jai hind spot vanshika is show the arrival of storing like all came to thank you number of string so here will be the requested one 123 for 45 202 bihar to be with Not For Any Court Does All The Best Reigns Way Is Similar To Food Vendors Peshi's Equal To Show The Rings Ending With Leaders Will Be See Gali Ke Dushman Only Because 24's Similar Ending With Ki Ending With Joy Jisko 2 Ending With I'd Some Awadhesh To a suite will be basically two and similarly for it will be three main aapke show and shown some will be storing raasleela e want to see em 45 and gain here will be doing the same for education and soil is but ab notice what will B the complexity of doing this like where every time taking a sum of all the previous elements 100MB directly firstly E F just ring two for lips follow on public this round I'm standing alone and column 108 will be in square and when required and Extra for loop in all detail wishes for finding a sum of previous that now only previous index and its complexity will also be chief n subah coins list will be n cross n the crops and which will b c institute that in total tweet also and cube 202 Yes that taste can still be better Vinod Arya School Certificate So let's understand what the subscribe The Video give element 2140 to the Video then subscribe to subscribe Similarly what will be doing subscribe to ke laddu that is similar ending up till the end it will be basically I one vihar to the previous also like total hair victorian total number also suite will be sicker one plus one witch will be to sleep and will be amazed will be to enter the street plus oil for 153 previous witcher 3 plus one shoes on the floor previous plus one Which is not within that to pad all these values and not just a letter this particular values and not just a letter this particular values and not just a letter this particular intent will be answer for NDA from 211 to 231 valve will always be 200 basically what will be storing reduce place will be easy for an equal to two enriched with strings Of Length Two Thoughts Pending TES Plus All The Best Things Which Will Only But Still The Also And To Explain Why I Like You Who Here For First Taste Case Has Been No The Best Foreign Incomplete All Of Them Will Be Easy For Only Similarly For Any Two It Will Be Given About Here What Will Give Me Some Of The Year Will Require Some Extra For Every Time You Will Be Required For Lu For This Subscribe Now To Receive New Updates Like This Subscribe Start Hair Loss Prevent Small World Jaayenge This Period Days one plus due to which will be three that Sofia the Tuesday total number of trends setting off with her work 2 and Yashwant plus two equal to three and verified pregnancy diet similarly what will be storing reduces will be this thriller distic which will be 6 Minute Lewis for Class 6th Standard and Poor's 500 Index To E Want Her Before Doing Is Like These Three 45 Se Zila For You For Calculating All The Best Story Hair To Get This Testing One Extra And Loot Is Remedy Subscribe Question To Three for next service from which will be and you slept yes happy answer will be town is to and soon but not withered away total number of behaving like and placid with spinach 200 in the best meanwhile consider daughter the time complexity of bird a like and Only because of this 512 500 acid complexities this and superintendent of police district 3100 35th is the richest this return 35a thanks do for dentist Louis basically a 3 is sun bath service three 500 hands with right things so they can go up till it also but acid time consuming School Bill Boxing Transfer To What Will Be Required In This Post Will Be Required ETC Are Deleted And To You That The Number Of Truth Will Be Is Equal To And 22 Followers Will Be FHD A Sop A Cup Of Sugar Slice Loot R8 Bro What Will Be Definitely With This Is Called Equal To One Should EPF 0505 Absolutely Former Vis Recently Where Worshiping This Cream Only 50 To Doing And Its Chief 0500 - Not And Its Chief 0500 - Not And Its Chief 0500 - Not A Plus One So Really Like President To Answer Hair Sweet Will Be The Previous To Plus Lineage 30 Building After Way Brock Pinpoint Like This Particularly 209 Me Bill Pay Upline Reservation Logic K Khulwana Agenda Plus Show Points Equal To 20 July Na Caffeine Z Plus Price For Roads And God Columbus 1008 Column Thes Are Yes Which Is This Columns On Every Time The Answer Is Controversy Kundli Subha Play Store 10 Back DP Of IAF Chief Is Equal To One Else Will Be Doing Physical Two Minus Plus Minus One Day - One Click Heer Voor - Plus Minus One Day - One Click Heer Voor - Plus Minus One Day - One Click Heer Voor - Subscribe The Amazing Is Improvement This World With It's Probably Too Stress Will Be Just Returning From - 4 Too Stress Will Be Just Returning From - 4 Too Stress Will Be Just Returning From - 4 Bijli subscribe and subscribe this Light See Is It Working For Sight Or Not That Teens Getting Enough Water Before Getting This 20000 Gautam Mistake Vivo Making Basically It's Not Be A Great Morning 50 Number of Columns 509 Let's Run Rate Luta CSP Marketing Right Answer and Excited to Subvert That Surya Summary Are Submitted So Let's Analyze Pain Time Complexity Show the Speech Complexities Page Number * Speech Complexities Page Number * Speech Complexities Page Number * I 2nd 250 That's Complexity It Can Be Made Butter Se Picture Wave You Can Be Done To Subscribe Complexity Of Difficulty In Understanding Problem You Can Come And Tune In Meeting Next Video
|
Count Sorted Vowel Strings
|
countries-you-can-safely-invest-in
|
Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._
A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet.
**Example 1:**
**Input:** n = 1
**Output:** 5
**Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].`
**Example 2:**
**Input:** n = 2
**Output:** 15
**Explanation:** The 15 sorted strings that consist of vowels only are
\[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\].
Note that "ea " is not a valid string since 'e' comes after 'a' in the alphabet.
**Example 3:**
**Input:** n = 33
**Output:** 66045
**Constraints:**
* `1 <= n <= 50`
| null |
Database
|
Medium
|
615
|
198 |
hi everyone today we're gonna solve one problem it's called house robbers we're gonna start off by reading the question and then I'm going to show you a graphical representation of the question and solution and then we're gonna code it okay so let's go at it you are a professional robber planning to rob a house along the street each house has a certain amount of money stashed the only constraint stopping you from robbing each of the house is the adjacent house has a security system connected to it you see how the words over here has bolded text that says it will automatically contact the police if two adjacent house were broken into on the same night that's a critical information so if you go through an interview for example and someone were to mention these points they may not highlight it but they will probably emphasize these very obvious assumptions I keep repeating on these videos but it's very important if someone gives you an assumption that is probably one of the key elements to that question cool given a list of non-negative none given a list of non-negative none given a list of non-negative none integers representing the amount of money of each house determine the maximum amount of money you can rob without alerting the police all right so I'm going to try something new we're gonna try to explain this question through a graphical representation instead of going through this over here so let's let me bring out a Photoshop alright so in this question what it's really asking is that you're given an array or that represents houses right so what you're really given is say you have like you know a street of houses right here living in here boom xxx etc and each house has a value to it so it's gonna be like this is what 2 bucks $1 $2 $1 $1 $2 $1 $1 $2 1/2 and 1/2 you get the point $1 $2 1/2 and 1/2 you get the point $1 $2 1/2 and 1/2 you get the point right so what this really represents is that anything on this element like if you were to start robbing this particular house you can't rob the one that's next to you because that's gonna alert the police right because it says anything adjacent to your first house that you robbed then you can't do so what you could do is you can skip the first one and go to the second element and rob this one right and you can do the same to the third fourth etc right or you could skip the first one altogether and start from number two and start robbing numbers that are skipping one element right so one of the quick things you might think like to do and here's like oh maybe I'll just you know check it right through this array and just check while I skipped through one to see if it's a solution or check the ones second one that and skip and see if it's a solution well there's also a little tiny catch to it if you also notice that in the question itself when we look at examples let's get that example here yeah if you actually look at the examples these are very simple examples you don't really give you too much right they still give you the same pattern of okay maybe I'll just skip one and boom I'll get that four on this one they're like okay maybe I'll just go and rob number two that and then I'll get this number right here right but it never really shows you the really edge case I'm gonna talk about right now so the edge case is like okay well what if in this particular case like can you guys determine what would be the top pattern to rob to get the maximum money well let's do some really quick representation right if you were to go from here to here and then you skip the house go here to here well your sum is only gonna be two four six and seven right so that's only gonna be seven so it's not gonna be your maximum number here right but what if you start from two boom-boom-boom-boom on this well you're boom-boom-boom-boom on this well you're boom-boom-boom-boom on this well you're only gonna get one plus one which is two and four and then six and eight right you're only getting at eight but that is not the maximum money you're gonna get right the maximum it's kind of obvious as a human you probably see it as okay I'm just gonna go from to just skip here and then but over here well hold on a minute I could actually skip two houses and get the equivalent value here but then I get to start robbing this way and I actually have more money now which is gonna be two four six eight ten dollars well we did this like visually but how can we do this programmatically right how can we know that okay as we go along this particular Street how do we know what our decision is right do we you know skip two steps or do we not skip two steps right so in our question here it actually asks us to return back the maximum money you can Rob right I never asked you specifically with which once which house at which index you should Rob so all it asks for is like what is the maximum money right so that's kind of key by knowing that means you don't really need to keep track of position of where you start robbing houses right all you really need to keep track of is the actual value so when we go back into the example here again all we really need to do is keep track of like at a particular position what my you know my maximum funds would be right so if we look at this question we might think that okay what can we do in here that can help us solve this question right to get this tent because I don't think we can start magically iterating to do things and then you know get this ten results because that's not really a common pattern right but we probably want to think about is okay well if I go and check thing every element does it actually tell me something you know maybe I could start using things that has happened before to help solve the problem moving forward so what I'm trying to get at is that maybe we could start using the logic about dynamic programming to help us solve this problem how do I come up with this type of solution it's because you can these type of questions really asks about okay you as you go all out particular step in point in time you have to make a decision right should I jump two steps or should I jump three step or stuff like that and that could be predetermined from what you did in the past right so what I mean by that is like okay well if I start it - I know like okay well if I start it - I know like okay well if I start it - I know for a fact that I need it only I can only jump to two spaces or I jump three or four but you know that's what I want to know so in position two I you know don't really need to store anything besides just like to write in position this is actually its position 0 this is position 1 so that one what do we do well I can't really do anything in the past so I'm just gonna store my number 1 because that's my if I were to start at this point that's my value it's gonna be $1 if I start at this point I'm gonna $1 if I start at this point I'm gonna $1 if I start at this point I'm gonna start at $2 but when I'm at position 2 start at $2 but when I'm at position 2 start at $2 but when I'm at position 2 what happens here well I could either take the step of going from 2 to 4 making my total being 4 or I could check whether or not you know I had some sort of like magic happening like this one over here if I could you know skip 3 steps or skip another step and that will give me a higher money right so in this one you're thinking about okay I'm going to check my position from here - 2 steps because the adjacent one will - 2 steps because the adjacent one will - 2 steps because the adjacent one will cost alarm I'm gonna check whether or not I get the maximum value from you know my standard hopping over here or I'll check the maximum standard hopping over here right so in this case when I second case this is like invalid so that won't be in my value of choice in this case I'm gonna go like 82 + 4 is my maximum great now go like 82 + 4 is my maximum great now go like 82 + 4 is my maximum great now I'm gonna move on to the next one right if I'm looking at in this context one of our possible jumps that got me to here right my possible jumps is if I weren't from one to one right which could give me a total of you know measly 2 or maybe I just jumped from here to here which gives me a total 3 right that would probably make more sense so I'm gonna make the maximum of that maximal of this particular element which is gonna be we take that 0 that's gonna be what you two or of course 3 I'm of course gonna choose 3 right that's not value here so I'm when I'm on this step for example I'm asking myself the same question all right well over here I could either take the bait the thing I had before at 4 because you know this is sequential or I could take something that is like 1 right so 1 plus 4 die equals 5 that seems like a higher number than my 1 plus 1 because that means pretty stupid I don't want $2 so means pretty stupid I don't want $2 so means pretty stupid I don't want $2 so I'm gonna use this and put 5 as my next step that corresponds to this one right so once again like I said this is only tracking your total amount of money you've robbed so far so that's this is what the dynamic programming is all about it's about tracking something that you know from your past right we know that for example when we get to over here or a historical like this is our total amount at this point in time that we've robbed it was $4 right so that's we've robbed it was $4 right so that's we've robbed it was $4 right so that's why we keep the number figure $4 right why we keep the number figure $4 right why we keep the number figure $4 right but when we get to this point we're thinking about ok well I could have kept that same pattern because I'm skipping this one step and adding here I'll have myself $5 or I could have just done a myself $5 or I could have just done a myself $5 or I could have just done a skip egde and I only get a maximum of you know $1 which is not that great you know $1 which is not that great you know $1 which is not that great right so therefore we're gonna keep 5 bucks and let's go repeat this pattern I'm looking at - right well - we look at I'm looking at - right well - we look at I'm looking at - right well - we look at whether or not it's gonna be $3 so this whether or not it's gonna be $3 so this whether or not it's gonna be $3 so this will be $5 or to you plus the 4 which is will be $5 or to you plus the 4 which is will be $5 or to you plus the 4 which is $6 so it makes sense that I'm gonna $6 so it makes sense that I'm gonna $6 so it makes sense that I'm gonna actually make that big jump here so 2 plus the 4 will give me 6 bucks cool now let's continue on which is over here 1 is gonna be either 6 bucks or gonna be 4 of course gonna be $6 and - over here - of course gonna be $6 and - over here - of course gonna be $6 and - over here - is going to either be $8 or 7 is going to either be $8 or 7 is going to either be $8 or 7 right I'm gonna make eight bucks here and one over here is gonna be either six or seven so the same thing so just can put seven and over here they're gonna be ten or eight dollars of course let me choose 10 bucks right so over here since this is only tracking effectively if I were to do skipping one house or skimming two house the thing we have to keep note that our solution can be possible any outcome of these two elements right so our final solution in this case would be this one however there is also possibility that this particular element could have been in our solution because maybe we were there was a sequence that we could skip and this is our last element we never really get to the last house right so we always have to check these two elements so our solution is pretty simple right so let me repeat the question again really or the solution cases like as we you know step through the positions or iterate through each element we know that we can either start from house number one or start from house number two right starting from the house number three kind of is kind of dumb because you know our only restraint is you know you can skip one house or I mean we're basically leaving free money on the table right so you don't want to do that so either step it's either going to start from this or start from that right and your third position is pretty much checking okay well if I start from that then this is automatically gonna be four so these three elements are pretty much set in stone this is the one when it starts getting interesting right because in here you can simply they're having options I could skip one or I could just jump all the way here right which in this case if I were to jump all the way here that's definitely more advantageous than if I were to start at two and jump all the way here right so that's a good thing now let's go into the code and see if we can solve this programming program back programmatically all right cool so first thing I like to do is write this in es6 function again format great that's just my personal preference you guys can write whatever you want you gives arrow functions you could keep the same thing that's up to you so one of the first things that I want to consider is the edge cases that with the thing about because what if we're given because nothing here nothing on this question says that we're not going to be given an empty array or an array of size only two houses or a size like that doesn't exist at all right so we can let's deal with those cases so I'm gonna check if my nums that length is equal to something that just completely doesn't exist so that one I'm just gonna return zero my next case I'm gonna check is gonna be numb so length this checks the length of the particular array if that equals to 1 what happens well that's the only house you're gonna Rob so I'm gonna go and return that value return nums comes at 0 right semicolons forget about those all right and third edge cases you don't double check is here well what if your house is there are only two houses on the block right well if there's two houses on the block then you need to return the maximum of basically position 0 gnomes at position 0 or nums at position 1 right okay now here's the real fun part right how can we start doing this iteration that I mentioned on here right how can I do that so programmatically it's actually relatively simple we're actually gonna start from the index I equals to 2 right so 4 let I equals to 2 right and I is gonna be less than nums you wanna stop length I plus great some people might ask me why is it I equals a 2 because you know Java scripts kind of fun this index here is actually going to be 0 right and this index here is gonna be 1 2 3 etc right so we're actually gonna start from this particular thing right all right so over here now there's one of two things you can do you can actually create an array here like let array equals to like a cash like a storage memory place but I'm gonna try to this is not good practice tip traditionally you probably should create another memory space but not edit the input value but in this particular case I kind of want to just because I had like to have fun with that I'm gonna modify the existing array that's being sent in so I'm gonna go say nums at position I or equal to the maximum value max oops math dot max right of numbers numbs at I minus to write plus itself numbs I or it's gonna be the map the numbs at I minus 3 plus numbs at I position right what's I minus 3 so I minus 3 it's kind of interesting when we look at it go back in here I minus 3 here is something that doesn't exist right if it doesn't exist then I'm gonna actually just say that ok well I can use this fun syntax here or just say I'm gonna check whether or not if that exists if it doesn't exist then I'm just gonna make a default value of 0 right this is kind of a little fun trick I like to do cool so what this really does is just taking the maximum value of the one of the value of the houses that you could buy in the previous or the one just before that right that's all you're really doing and then once you do this once you iterate you're gonna basically generate this array that I already given you this particular array right and you should get your solution so right here you just have to return your solution that is math acts of pretty much the number the last two numbers that I mentioned before that's nums dot length minus one right or it's give me your number length minus two all right cool so with this I believe we have the right solution so let's submit it and see the solution and great it's all alright cool so I tried a different format this time around if you guys like it you guys like me going into drawing the solution for you making it easier to understand let me know where I can improve if you like it you know subscribe hit that like button if there's something I really suck at please comment below and let me know I kind of only engage the audience and I can tell the solutions to you all right well thanks bye you
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
341 |
hello and welcome back to the cracking Fang YouTube channel today we're going to be solving lead code problem 341 flatten nested list iterator you are given a nested list of integers nested list each element is either an integer or a list whose elements may also be integers or other lists Implement an iterator to flatten it we'll need to implement this nested iterator class which will initialize our object with the nested list we need to implement a next method which Returns the next integer in the list and we also need to Implement a has next method which will return true if there are some integers in the test uh in the nested list and false otherwise this is just how the code will be executed no need to read that now and let's just look at a very basic example so if we're given our nested list is a list containing the list one the number two and then another list one we want to flatten this right so we would take this first list we'd flatten it into one then we get to the two that's already you know a number we don't need to flatten anything and then we get to the last one which is 1 one we just flatten that so our final answer is 1 one to 1 one we've essentially just flattened it which you can see is the output here okay example two we have 1 4 uh six obviously this is a list and then there's also a nested list in here so the way we process it is just do the one and then we get to this list here so we need to flatten this part so this would become a list of four and six and then we can just grab the four and then we need to flatten this six as well so we would do that and continue for oops six and there we go so those are the basic examples as you can see it's relatively straightforward just the way that we implement this can be a little bit tricky but let's kind of wipe away um all this text here and just look at one of the examples in more detail and we'll talk about the intuition here and then we can go to coding okay so we looked at our basic examples now let's look at one more in depth and figure out how we actually want to solve this problem so we have our nested list here which contains 1 4 and six right and we need to flatten this into 1 4 and six so the way that we're going to do this is we're actually going to use a que which is going to contain the elements that we need to process and we can just initialize this queue with our initial nested list and we're going to process the queue from start to finish so what we're going to do is we're going to put into our Q uh these numbers here so one and then we have our list 4 six uh can I make this bigger yeah four and six and we just want to process it item by item so what we're going to do is we're also going to have a result function here uh sorry not a function a list and we're going to pop an item from the Q so we're going to say Q we're going to pop the item at the start of the que and we're going to get it right so it's a one if this is an integer then we know that we can just put it into our result because we don't need to flatten anything so we're just going to put one in here now we go to the next item four and six so sorry this should be in a list so what we need to do is actually process these items but how do we do this so if this is a list then what we need to do is we need to actually get the items inside the list and add it back into our queue so when we call uh we pop from the queue we get this list four and six and we remember from our example that there's a method that allows us to get the items in a list so what we want to do is we basically just want to add them back into our que and this time the Q will now look like four and six so then we can continue processing and now when we pop from our Q we will um get the four which we know that we can just work with directly we'll just put it in the result so now our Q will just be six we need to get the items inside of the list and repopulate the Q so we're going to say Q equals to just six this time cuz our method will just give us the items inside of a list when we call it and then we have q equal 6 we can process it again pop the six and then we have 1 4 and six so that's basically the general thing we want to do we want to have a queue here and we want to process that queue from left to right when we actually reach an element that we've popped from our queue that is a list we need to get the values of that list using the method that's provided to us on the nested list class um it's actually already defined for us and what we want to do is we want to add back into our Q uh the result of some sort of DFS to flatten um the que right so we're going to have a function and we're just going to call it recursively so when we hit this um value here that it's a list then we would we want to flatten it and then add it back into the queue for processing and we should be done so essentially we need to set up a que and do our DFS um when we actually need to flatten something so the DFS bestest function will be the kind of Crux of this problem but it's actually really easy to implement so without further Ado let's go to the code editor and do that now test okay we're in the code editor let's type this up before we do I just want to clear away some of this autogenerated stuff by lead code I just want you to see that we actually have access to an is integer method a get integer method and a get list method um and the get is integer will turn if it's a Boolean will get the integer if it's an integer and it will get the nested list if it's an A List so I'm just going to clear this away to make it easier for you guys to see Okay cool so now we just have our kind of class skeleton so the first thing that we need to do is actually Define uh some of these methods so the easiest one that we're going to do is we're just going to do the init one first and what we want to do is we want to say self. Q so this is where we're going to be storing um our Q of items is going to be collections. deck so this is how we're going to get our Q and we're going to call a flatten function which is that DFS function we talked about and we're going to pass in the nested list so now what we need to do is actually Implement our flatten function which is really the Crux of this problem um so let's do def flatten and this is going to take in our nested list now what we want to do is we want to say the items uh for us to flatten is just going to be an empty list and what we want to do is we want to say four item in nested list uh nested list we need to check whether or not that current item is an integer or not and based on that we can continue forward so we're going to say if the current item whoops I can't type today if item do is integer if it's an integer what we want to do is we want to say items. append that item right item. getet integer so if it's an integer we can just put it into our items directly we don't need to do any sort of further processing if it's not an integer that means it must be a list and if it's a list then that means that we have to flatten it before adding it to our um values here so what we want to do is we want to say items. extend so essentially what we're going to do here is we're going to extend uh the items that we have here um by whatever the result of flattening our nested uh list is right so we're not using a pend because a pend will actually add a list literally when you want to add it to another list right so if we had a list like uh 1 2 3 4 and we wanted to add the list 2 three 4 if we did append it would actually append it as a list so it's like 2 3 4 whereas if we use extend it will flatten everything from inside and just add them uh one by one so this bit uh is necessary so we need to use extend in order to um not get the wrong answer right because we want it to be a flat list with no nested lists inside so this flatten bit here obviously we're calling it recursively so we'll recursively flatten it remember the case we had like a list of four and six we would get this list and then we need to flatten four and six and then basically what this would return is just four and six together uh in a list so we want to flatten it call it recursively to get rid of any kind of like child lists in there so that is that once this for Loop ends then we can simply return our items and we're good to go so now we need to implement the next and has next method so the next is really easy because we've put everything into our que and it's already been flattened actually so we just want to say self. q.p left and this will just get the next q.p left and this will just get the next q.p left and this will just get the next item from our iterator now what we want to do is we want to say uh return uh sorry for the has next one basically is there something else to pop we want to say if the length of our Q is actually um zero right so if there's a next then the length of the Q uh will not equal zero and that's really all we need to do so let me just run this make sure I didn't make any silly bugs judging let's see is integer did I is it called wrong oh sorry this isn't nested list this should be nested list.get list yeah should be nested list.get list yeah should be nested list.get list yeah that's the Weird thingy here now it should work has no attribute get list huh did they change the definition what happened um let's see has next in next what did they call it g okay let me reset this real quick and see what they called it is integer get list huh why is it not that nested list oh God it's item. get l okay there we go let's see now it should wrong answer great oh wow okay I am all over the place today we need to return something from here of course there we go okay well as you can see you sometimes make mistakes and now if we submit it should all be fine yeah there we go okay that was uh a bit embarrassing whatever we fixed it live sometimes you need to debug your code live good realistic uh practice so what is the time and space complexity so let's do the easiest one first which is this next function obviously all we're calling is pop left to do this from a q is always going to be Big O of one we've paid the time complexity cost UPF front by doing the flatten uh in the init function so this part is just constant time obviously checking the length of it and whether it equals to zero is going to be also constant time um so this one is constant time um and then we get to in it so the time complexity here obviously what we need to do is we're going to go through every element in our list and we need to process it so this is going to be big of N and we need to do this up front so we can basically flatten the list so however many elements we need to process will depend on the size of the list so it's going to be a big O of n operation and for the space complexity obviously we are storing everything in our Q here uh once it's flattened so this part will also be Big O of N and we play pay those costs up front so we don't have to do it later on so in the next function we can do it in constant time and has next is also uh constant time so that is how you solve this problem there are many actual uh solutions to this problem this is just one of them I quite like this one because it's really easy to follow and it's like a nice kind of DFS um doing it and doing it regressively and it's quite intuitive hopefully this um video helped you if it did why not leave a like And subscribe to the channel if you want more content like this otherwise thank you so much for watching and have a great rest of your day okay
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
1,634 |
hey everybody this is Larry this is me doing uh extra practice going to do uh actually I'm going to take off the premium because I think there are non premium questions that I haven't done yet so I'm going to just do that um the only thing that I will skip over for now is I think database and concurrency because I don't know like that's not I'm here today I'm just going to do algo so as long as it's in algo that should be fine and today we get we do get a premium prom anyway with Amazon I guess I don't know but it's 1634 at two polinomial represented as length list all right I mean that sounds pretty straightforward so far let's take a look and basically yeah I mean I think the way that I would think about these problems um or this particular problem I guess this isn't really a classic problem but the way that I think about it is kind of like a big num problem or big number or big integer problem and kind of think about it that way but really it's just about especially for this one if it's adding it should be pretty um straightforward in terms of the mathematics um it's just about um yeah cuz basically you have like multiplication you have to do like some shift things and then maybe you can get into complexity like there are a couple of um different algorithms for multiplication but addition is pretty straightforward it's just about what I would call bookkeeping and bookkeeping is not a fancy algo I know that sometimes I say and I don't explain it but bookkeeping is just you know you keep a book keeping track of where everything is and making sure that everything is updated when you update one thing and stuff like that right that's basically the idea all right let's take a look at the actual problem but I mean I imagine the title is pretty oh I didn't uh I imagine the title is pretty descriptive that's why I didn't really read the rest of it though you know there may be some nuances or edge cases that they thr you out B but yeah okay so you g a link list this is the link list node and you given the I presume the head is it sorted by power I mean okay so no coefficient zero strictly descending by power okay all right that's pretty good um I think one thing that we can think about is whether h i mean I was okay well I changed my mind a little bit but I was going to say whether you do it in place or not but given it's a link list it's kind of tricky to have it in place necessarily just because um I don't know then you mutate a lot of things um and I don't know I just keep it stupid keep it simple that's what I would say right um but yeah but I think the idea that I would have for this one so basically the way that we think about it or at least the way that I would describe it to y'all is just kind of think about instead of polinomial think about it as big integers if that helps it easier and of course for adding that then you just get one at a time right uh one digit at a time in this case one p polinomial at a time of course you have to line them up however the difference between this and a link list of digits is that um they're no placeholders for zeros right so there may be missing things but of course you still just kind of point it at one at a time and with that and of course in this case there's no carry so you can definitely go from um what's it's that the most significant digit I most significant polinomial I don't know if that's quite the way I don't huh I don't know the terminologies now I think about it but in any case yeah there's no carry right so you can just kind of add them piece me one by one or pairwise if you will um yeah and that should be good uh of course the only tricky thing is the coefficient of zero stuff that we have to care about so yeah so let's just say we answer is equal to a party node and here uh I'm going to just use what is X and Y why do they call this X and Y why do they not just call it like Co coefficient you know like why would you make code that is less readable than before you know I don't know that's just weird actually but in any case we'll use a sentinel this is not a real head it's just you know I think this is fine right and then we'll and as a result we'll return end to next because that is the Sentinel okay and then now we would we'll just do something like uh W poy one. next is not none this is another way of saying that it's not empty maybe we could put uh well I was going to say maybe we could have a helper function but also ideally maybe um maybe that's like a function in party no so I don't know uh but yeah n poy 2. next is not none then here we do some maps on the on both of them um and this is very similar to merge sword actually you know the two pointers I guess I don't know but yeah if p1. power is equal to party 2. power then basically what we want to do is. next is equal to party node of the co which one is oh uh party 1. coefficient plus party 2. coefficient the power is the same so we just take one of them and then next we don't have to care about yet right and then else I guess else we have to take the power that is greater so this is the one of them and then else the other one is po poly I like to type it out sometimes oops if I type it out sometimes I like to type it out correctly sometimes too but um but yeah right so now here the idea is still the same and maybe we could have win this in a slightly different way I don't know oh wait um we need to update so yeah hang on this isn't done even the previous stuff yet um just this is just setting up the answer uh party 1. coefficient party 1. power and then here we want to do party one do uh let you go to party 1. next maybe we can have a pointer to party one instead maybe that's it should be okay though just because this is actually by this is by value not by reference and so this actually is just a value but okay we'll just do P1 is youal to po one P2 is Party 2 maybe that's slightly um I wouldn't say this is cleaner or even more readable per se I'm just lazy about the reading or about the um I'm just lazy about the naming you could probably name it slightly better but it does offer less ambiguity with respect to pass by reference pass to value and all these things that people sometimes have concerns about so yeah you go P that next right and here we right we both and lastly we have and right are we done no because then there are cases where one of them is still not done so we have to kind of um yeah we just have to finish it off right um is this true no is this I think I'm off by one here there you go but yeah okay yeah and then now answer. next is equal to party no p1. Cici p1. power oh I did forget I'm supposed to write ERS you answer that next the reason why I didn't put it together is because I said I could put it outside but oh no this is weird this isn't it I am being silly so this is head but then we have let's just call it tail is equal to head and then now we return head down next and this is the tail maybe that's a little bit clearer huh sometimes I forget these things I haven't done it in a while like as I always say um I don't really do much lless stuff outside L outside of the code uh it comes in handy once in a while most like least recently used e kind of thing but um I don't know yeah that's pretty much it and like I said this is going to look very similar to a big int type thing or even a merge sord type thing uh but yeah can I mess this up did I miss understand this oh I renamed things and I deleted it whoops I renamed something and then I kind of left it off okay oh there is a case where the thing becomes zero okay I mean that only happens with this so yeah so we can just do a symbol um hm that's a little bit tricky I mean it's not that tricky but it's just requires a little bit D so if this is not equal to zero we do this we still have to move this but now we have to kind of move this along a little bit so I cannot generalize it this has to be here this is here remove and this is here only if we update right maybe we could have a helper function here to be honest but it's fine um and the reason why here we don't need a check is because we assume that this is already greater than zero or it is not zero actually not that it's greater than zero because otherwise it would exist presumably but yeah as I suspected there were some edge cases but luckily for us uh quite on the um input cases but yeah otherwise this is a pretty straight is this a medium yeah this is a medium sounds right it's a little bit tricky for easy but a little I mean yeah but yeah um how do I feel about this for interviews I don't know I wouldn't ask this fuse a little bit straightforward and I don't really like link list problems as an interviewer that's not to say that you won't get it but that's just me as an interviewer um you definitely should know this it's not that bad and there are a lot of other link list problems if not this one so um so and if you're you know if you're practiced on link list this shouldn't be a problem for you yeah that's I have for this one let me know what you think did I submit it I think so right yeah uh stay good stay healthy to Comm mental health I'll see yall later and take care byebye
|
Add Two Polynomials Represented as Linked Lists
|
clone-n-ary-tree
|
A polynomial linked list is a special type of linked list where every node represents a term in a polynomial expression.
Each node has three attributes:
* `coefficient`: an integer representing the number multiplier of the term. The coefficient of the term `**9**x4` is `9`.
* `power`: an integer representing the exponent. The power of the term `9x**4**` is `4`.
* `next`: a pointer to the next node in the list, or `null` if it is the last node of the list.
For example, the polynomial `5x3 + 4x - 7` is represented by the polynomial linked list illustrated below:
The polynomial linked list must be in its standard form: the polynomial must be in **strictly** descending order by its `power` value. Also, terms with a `coefficient` of `0` are omitted.
Given two polynomial linked list heads, `poly1` and `poly2`, add the polynomials together and return _the head of the sum of the polynomials_.
**`PolyNode` format:**
The input/output format is as a list of `n` nodes, where each node is represented as its `[coefficient, power]`. For example, the polynomial `5x3 + 4x - 7` would be represented as: `[[5,3],[4,1],[-7,0]]`.
**Example 1:**
**Input:** poly1 = \[\[1,1\]\], poly2 = \[\[1,0\]\]
**Output:** \[\[1,1\],\[1,0\]\]
**Explanation:** poly1 = x. poly2 = 1. The sum is x + 1.
**Example 2:**
**Input:** poly1 = \[\[2,2\],\[4,1\],\[3,0\]\], poly2 = \[\[3,2\],\[-4,1\],\[-1,0\]\]
**Output:** \[\[5,2\],\[2,0\]\]
**Explanation:** poly1 = 2x2 + 4x + 3. poly2 = 3x2 - 4x - 1. The sum is 5x2 + 2. Notice that we omit the "0x " term.
**Example 3:**
**Input:** poly1 = \[\[1,2\]\], poly2 = \[\[-1,2\]\]
**Output:** \[\]
**Explanation:** The sum is 0. We return an empty list.
**Constraints:**
* `0 <= n <= 104`
* `-109 <= PolyNode.coefficient <= 109`
* `PolyNode.coefficient != 0`
* `0 <= PolyNode.power <= 109`
* `PolyNode.power > PolyNode.next.power`
|
Traverse the tree, keep a hashtable with you and create a clone node for each node in the tree. Start traversing the original tree again and connect each child pointer 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
|
Medium
|
133,138,1624
|
231 |
hello everyone welcome to hacker heap in this quick tutorial we will look into this problem of solving power of two this is pretty simple problem it's already mentioned a easy problem so very straightforward the easiest way to do is there are two ways to do it one way is just by doing the modulus of n with two and make sure it is equal to zero and until the number becomes 2 n is equal to n by 2 so that is one way to do it but there is another way to do is the bitwise operator so let's take a number 4 and how do you represent it here in bits so it would be 1 0 let's take a number 2 it is represented as 0 1 0 and 1 as 0 1 8 as 1 0 so if you see something if it is a power of 2 there will be only 1 bit that will be turned on that will be 1 so how do we find if a given number is a power of 2 is by doing and operation between the given number and the number minus 1 if you want to know if 4 is a power of 2 what you do is we will do 4 & 3 which is you do is we will do 4 & 3 which is you do is we will do 4 & 3 which is basically 1 0 & 3 is 0 1 and this basically 1 0 & 3 is 0 1 and this basically 1 0 & 3 is 0 1 and this should be an operation should be equal to 0 that means the given number is power of 2 let's say if you take 6 which is not a power of 2 1 0 and minus 1 5 would be 1 0 1 and if you do an and operation here there is still 1 and the result will be 4 so we know if it is not equal to 0 it's not power of 2 so let's go ahead and cut it out all we need to do is return and not equal to 0 and bitwise operation n minus 1 this should be equal to zero that is it and we also need to check if n is not negative if n less than 0 we would return false all right let's see how it works submit hola it's done so this is pretty straightforward I hope you get the concept of using bitwise operators when needed it reduces a lot of complexity when you use big wave operators when it can be thank you for watching please like and subscribe to the channel
|
Power of Two
|
power-of-two
|
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_.
An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** 20 = 1
**Example 2:**
**Input:** n = 16
**Output:** true
**Explanation:** 24 = 16
**Example 3:**
**Input:** n = 3
**Output:** false
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Bit Manipulation,Recursion
|
Easy
|
191,326,342
|
704 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem binary search we're given an array of integers nums which are going to be sorted in ascending order and we're also given a target integer that we're going to look for if the target exists in the array then we can return the index of it if it does not exist then we return one the goal is to create an efficient algorithm that can run in log n time so what algorithm are we going to use well the problem pretty much tells you binary search so while this is self-explanatory search so while this is self-explanatory search so while this is self-explanatory and a pretty basic algorithm i still think it's really important because a lot of problems kind of extend the idea of binary search and then make it even harder and this is actually a pretty common interview question to be asked some variation of binary search so this is a very good problem to practice and your goal should be able to implement binary search very quickly basically as if you were doing it in your sleep so i'll try to explain this quickly but also in a beginner-friendly way so the also in a beginner-friendly way so the also in a beginner-friendly way so the input array is sorted the target value could exist anywhere in this array or it might not exist at all when we start we are considering the entire input array how are we going to do that well we're going to have two pointers one pointer is going to be at the leftmost index which is initially index zero another pointer is going to be at the rightmost index these pointers mean that we are considering the entire range now if we could only look at one of these values which one should we look at the leftmost if we do that and we see that it's not equal to the target then we've only eliminated one possibility and we still have to search all of these if we look at the rightmost similarly it's not the target so we've only eliminated one possibility we still have to look at the rest of them but if we look at the midway point and technically either of these could be the midway point the way we calculate it though is going to be literally taking the left and right indexes and dividing them by two which i think will lead us to this position but approximately the halfway point why should we look here well we can compare it to the target it's not equal to the target so what does that tell us have we only eliminated one possibility no because remember the input array is sorted so if this is not equal to the target we should also ask is it smaller than the target or is it larger than the target in this case it's smaller than the target so if this is smaller than the target then everything to the left of it is also going to be smaller than the target so this was our midway point we'll call it m and we found that it's smaller than the target so we can eliminate these three values from consideration everything over here how are we gonna you know represent that in code well we're gonna take this left pointer and then shift it to be m plus one so now our left pointer is gonna be over here this represents possible range of solutions is going to lie within you know these two pointers so at this point we're just going to repeat the algorithm repeat what i pretty much just did now if we take these two add them together divide by two the middle is going to be over here so then we're going to check is this equal to the target that we're looking for in this case yes it is so now we can return the index because that's what we were trying to do we can return m whatever it happened to be i think it's 4 in this case so that is pretty much the idea of binary search okay so now the time complexity if you know binary search you already know that it runs in log in time but let's quickly understand why so we're not considering this example anymore but suppose we had 16 values in the input array every time we go to the midway point we either find the target but if we don't find the target we know we're at least going to eliminate half of the possibilities so we would eliminate this down to a now we're only looking at eight values we still don't find the result we keep dividing it by two make it two remaining and then finally there would only be one value remaining and either that's going to be the target or it's not going to be the target and then we're pretty much done with the algorithm anyway so the question is if we have a while loop the while loop is going to run as many times as we can divide the length of the input array by two how many times can we divide it by two well if you remember from your math class that is a math equation called log base two of n this evaluates to how many times can we divide n by 2. and you know suppose it evaluates to be x that's equivalent to saying that 2 to the power of x is going to be equal to n okay but this is too much math maybe you don't even care but that's pretty much the idea that's why our loop is going to run x times which is going to be equal to log n so it's not a big o of n algorithm it's a log base 2 n algorithm which is much more efficient okay so now let's code it up and like i did in the drawing initially we're considering the entire input array as our search area so our left pointer is going to be at zero our right pointer is going to be at the last index which is just the length of the array minus 1. now we want to continue going until there's no more possibilities left or we have maybe found the result so the way to do that is to basically say that while our left pointer is less than or equal to our right pointer because i didn't show it in the drawing picture but suppose we just had a very small input array just to illustrate the example our left and right pointers would both point here our midpointer would also point here but suppose our target is actually equal to two okay we'd say okay this is too small for our target so we're gonna set our left pointer to be equal to mid plus one so that means our left pointer would be one and our right pointer would be zero that basically means our left pointer has crossed our right pointer and that's how you know that we have no more values left to search we did not find the result so that's why we're doing less than or equal if they're both equal though if they're both pointing at this value that means we haven't looked at this value yet so that's the idea so each iteration of the loop we're just going to find the midway point which we can get by taking l plus r and dividing by two if the value that this index is at is greater than the target then we want to look at all values to the left of it so we're gonna take our right pointer and set it to m minus one we wanna look at all values to the left we're basically shrinking our criteria and in the other case else if that num is smaller than our target then we're gonna do the opposite we're gonna set left equal to mid plus one just like in the drawing explanation the last case is if neither of those are true that must mean that we found the target if it's not greater and not smaller that means it must be equal that means we can return m which is the result but if we went through every iteration of the loop and we didn't find the result then outside of it we are told that we should return negative one to indicate we did not find a result so that's the solution let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient there's one more thing though that i want to mention to you which probably won't come up in your interview to be honest it's never come up in mine but there's actually one little bug here i mean technically the bug doesn't exist in python because python integers are unbounded they can pretty much be infinitely large but in most languages like java and c plus you might encounter an overflow because suppose we had a very large input array and then these two integers were very close to the 32-bit integer max which is close to the 32-bit integer max which is close to the 32-bit integer max which is something like 2 to the power of 31 suppose they were both close to that then adding them together would possibly overflow and then we would get the wrong result in this value so possibly your interviewer might ask you something about that and how would you go about fixing that well there's actually a way to do that we can still calculate the midway point between left and right without adding them together because we can take the distance between them we can get the distance between them by taking right minus left and then dividing that by two right that will give us half of the distance between them and we can take that and add it to the left index because if this is halfway of the distance between them and then this is the left index by adding these together we are getting the midway point this is just a way to do the exact same calculation but this way it will never overflow because right is always going to be greater than or equal to left and in this case we're not adding them together we're subtracting them so this will always be positive or it will be zero so i'll run it and it does work pretty much exactly the same as you can see on the left but this is just something i think a lot of people don't talk about and actually i pretty much never implement it this way people have actually mentioned that in my comments before which is kind of why i'm talking about it today but i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Binary Search
|
binary-search
|
Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 9
**Output:** 4
**Explanation:** 9 exists in nums and its index is 4
**Example 2:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 2
**Output:** -1
**Explanation:** 2 does not exist in nums so return -1
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 < nums[i], target < 104`
* All the integers in `nums` are **unique**.
* `nums` is sorted in ascending order.
| null | null |
Easy
| null |
279 |
Hey everyone, I hope people will be well, today we will see Perfect Square is a very good problem. Again on DP, the first question coming in the mind of many people is that brother, are you completing the playlist of Rickson or what is DP? I told you in the beginning that look what is the basic concept of DP, research, if you have understood the analysis, you will understand the DB and two, when have we completed the analysis, when have we completed its basic concept? I am teaching DP in such a way that you can understand that reconstruction is going on because reconstruction is a method through which you can see DP in a very butter and easy way. Because till now we are not doing anything, only the solution has to be written with great effort and concentration, which I have made very simple and converting the research solution into DP code is just a change of two lines, dates. IT After that you can record yourself, just convert the code into DP and your solution of DP is ready. People all over the world are worried that read this rule in DP, read that rule. 36 types of rules, all my mind should be empty and at the exam time. Or I am not coming even a single day at the time of interview but the approach of solution is so best, no matter what new problem comes, you will solve it and I will solve the question here on Perfect Square every time. Like I tell you friend, please whenever you watch any of my videos, don't come suddenly friend, this is not a video about solutions, now trade it for solutions, you will get a lot of solutions, try it, then watch this video. I am guaranteeing that now you will start learning a lot from yourself, what is the dog perfect square question? Again I will say again, now don't be fooled friend, while watching my video, the link of the questions is given in the description box, open it and read the questions. Attempt the list question and understand it. Do not open the video directly to me. Come on, what is the question? You have to write N in such a way that the sum of the perfect square is equal to N, which means something less than lat. 12 is ok and here 4 + 4 + 4k four is a perfect here 4 + 4 + 4k four is a perfect here 4 + 4 + 4k four is a perfect square, if we square it then four will come then foreplay again if it is four then what is the total number of perfect square, three is three, our output is now this. We could also do that OnePlus One Plus One Four Plus Four We could also do this One is also a perfect square One 's square's butt is off Basically we have to 's square's butt is off Basically we have to 's square's butt is off Basically we have to break the N in such a way that the breakdown We are doing that it should be in a perfect square and the sum of all should be equal to n. Okay, so one is also a kind of perfect square, whose square is one here, but what is the total number of perfect squares? But we have to do the background in such a way that the count of the perfect square which we are taking should be minimum to minimum, so here the minimum count is three a. If you talk about 13, then what is the minimum count of it? How four plus nine is the perfect square of four. Whose nine is the perfect square of three? I hope you have understood till now. Look, now you know that DP is not so fast. There are many varieties in DP. It takes gold and why to think. This much is required because in Reconjan we have to think because in Reconjan, what kind of method is this through which we can understand DP very easily and we know that thinking of solution is not like this, friend, a little is done, it is okay, so you have to think more. It starts appearing in varieties but actually we are increasing the compatibility of the problem through recognition, first of all I am telling you how to breakdown the concept, here N = 12 breakdown the concept, here N = 12 breakdown the concept, here N = 12 is given to you, okay that means what we have to do. Sum of perfect square is equal to n. Now whatever this number is like 4 + 4 + 9 + 16 whatever this plus one or whatever you are 4 + 4 + 9 + 16 whatever this plus one or whatever you are 4 + 4 + 9 + 16 whatever this plus one or whatever you are calculating the sum of perfect square should be equal to n. There is no problem here. And this number which has been a count, that count should always be minimum, okay, not so now but off yourself, any number like 17 has been written, any number can be written as one plus one 17 times. And if one is a perfect square then our output will be 17 A. This is the fact but we have to find the minimum number that from the minimum to the minimum perfect square and the sum A should be equal to N, it means that N - sum of perfect square is equal to means that N - sum of perfect square is equal to means that N - sum of perfect square is equal to zero. If we have minus from N then that zero should come and no this is the concept that arises, we have many sir options, the meaning of subtracting the perfect square is simple, let us have N = 17, meaning of subtracting the perfect square is simple, let us have N = 17, meaning of subtracting the perfect square is simple, let us have N = 17, okay so we Let's suppose a nine is a perfect square. How many children would have been made by nine mines. Six children. Okay, so now six children, now divide six by what force? Do mines, then what child, you child, then mines you. One to one child, then one to one. Minus one by one zero child final a gone zero a gone what does it mean what we do is min the numbers one by one from the perfect square and are reducing this N. C has reduced this N. If we have to reduce six then six from one to zero, ultimately to zero and this is a perfect square, we are doing it 9411, how much is the total count, is it four minimum or not, we will see later, but the point is to understand that N. Out of these we keep mining the perfect square and making a new N and then we have to keep reducing N towards zero only then our sum of perfect square will be equal to N. I hope you don't have any problem till now. You must be aware that the main part of the logic is this, what is the main part of the people, let it be equal, you are 18, okay and this thing is fixed in our mind that they want minimum number of square, basically perfect square, we have to get minimum number of square. Minimum percentage they have other options you subtract we have a lot of options to start from 18 what can we subtract 2n you make it zero like and make it zero this was our concept n - sum make it zero this was our concept n - sum make it zero this was our concept n - sum of Perfect square = 0. Well, that means of Perfect square = 0. Well, that means of Perfect square = 0. Well, that means sum of perfect square and will be equal to. What we do is we are selecting perfect squares one by one which can be mined by N and then we are tending N towards zero. So we have in one option, one can be mined from 18, yes, you are in option, you are squared 4 - can, yes, we squared 4 - can, yes, we squared 4 - can, yes, we can mined the square of three, yes, how much is the square of four, 16 - can Yes, yes, is the how much is the square of four, 16 - can Yes, yes, is the how much is the square of four, 16 - can Yes, yes, is the square of five equal to 25 - What square of five equal to 25 - What square of five equal to 25 - What can be done and what can't be done because 18 will be smaller than 25. Tell us a fun fact about it. This question will be literally understood by those who have done it and who have done it. People will start watching my video from the beginning and when will they be watching the list of DP and traction of this playlist. Only then will you see a video shine a little, you will be able to relate the questions through traction, otherwise it will shine only after seeing the solutions. Now people will add this thing. If you understand it on your own, then the factor of understanding the butt will be enjoyed only when you have actually attempted it yourself, so now whenever it comes to our mind that we want a perfect square, that is the minimum number. We need an off part, okay, so what can we do? Minus the biggest perfect square out of 18. So we have blue suppose 16 is the biggest one. Okay, so we will subtract 16 from 18. So what a child you are. Child, we have reduced the entire n to tu, now if we want to take tu towards zero, then we will do 2 - 1, then one child is ok, then we 2 - 1, then one child is ok, then we 2 - 1, then one child is ok, then we will mince one to zero child is ok, so ultimately we have total three steps. And this is the future step, we have just chosen the first step, so we don't know what will happen after that, what is the total number of steps, now we know that 16 - 2 went back, now how many steps 16 - 2 went back, now how many steps 16 - 2 went back, now how many steps will be taken after that. We don't know but we calculated it took three steps but this is not the optimal solution. It is not necessary that we mine the biggest number first then we will have less steps. Another step if we click on nine here. Then I get reduced in just two steps. If there is no square mean of three out of 18, then 9 children are fine and then if I square measure three out of 9, then zero child is fine. If you directly reached zero, then it means that If the optimal solution is this then the optical solution is not deciding which number can be subtracted first. Even I don't think anyone will be having problem. If it is happening then please attend the questions once, only then you can listen to me. You will be able to understand logical thinking ability, you will be able to relate it with your problem solving skills, otherwise you will not understand what is going on, I am talking about 16, why do we think first of all, we want to mine the bigger number first. So that if the smaller number is the smaller number, then the probability of getting a perfect square will be minimized, but it is not necessary, so the optimal solution is not aside, what should be done first, then the rule of one DP. Understand that whenever you are confused about what are the steps for the optimal solution, then do not take much stress. No need to stress. To choose the optical directly, try all the options and do the optimal thing in it is simple. I have written the concept here in English so that you can understand that we are not able to know that first 16th June, choose the biggest number, choose the middle number, if you choose then reduce it by one, brother, all the possible ways are being made, do everything. Let's take it and the minimum one will be our answer. Very good, there is no problem here, before that let me explain one thing to you, this is what we have to do here. If n = 18, this is what we have to do here. If n = 18, this is what we have to do here. If n = 18, then what option do we have to save? One The saving is the square of 12 and from 18 so we can't do some more subtractions. What did we say? If N = 16, we have What did we say? If N = 16, we have What did we say? If N = 16, we have chosen it. Okay, so now we have done n16 thing. What? 18 - 162 N = 2 children, we have What? 18 - 162 N = 2 children, we have What? 18 - 162 N = 2 children, we have just chosen it. By a² done that Okay now let's come to minus tu What can we do 2 - 1² means one Okay so N What 2 - 1² means one Okay so N What 2 - 1² means one Okay so N What kid one We have a squared here and done that Okay then it comes N = 1 - 1 done that Okay then it comes N = 1 - 1 done that Okay then it comes N = 1 - 1 = 0 find it's zero came a's square = 0 find it's zero came a's square = 0 find it's zero came a's square here and did that so total we have three star a's this is understand how this type a's very good now we come here if solve our There is a recursive function in it, if you pass 18 then what is the option to min the number of 18? What is the square of one? So what is the child 70? Now what is the total number of minimum number of perfect squares required to write 17 in the sum of perfect square, it will reduce our I don't know how it will perform the function on its own, I don't know, its life is going to be less, this is the advantage of Recong, it has to last only for one year, after that, a subsequent consecutive head will run, it will run on its own, then what other option do we have, what is the saving in 18 years? From this you can also mine the square of 4. You can also mine the square of 2. If you mine the square of 2 from 18 then what will be left? 40 ok then 14 will be left then 14 can be written as the minimum number of squares. He will also give us our calculation. Let's come again. If we can do the subtraction from the square of three, then it is good 9. So when there is a child of nine, then why nine now? What is the minimum number of squares that we can write? Who will bring that record and give only the answer? 18 - 4² Who will bring that record and give only the answer? 18 - 4² Who will bring that record and give only the answer? 18 - 4² Child, can you now write tu in how many numbers, that too will be given by bringing the function from the record, then ultimately any one of these four, we will change it, the one which will be minimum, we will change it to one and one plus, then one plus minimum. Off Solve Whatever you give us as our minimum, we will multiply it. What is this number telling? The number of square is telling the number of square. The number of square is telling this also the number of square is telling that the total minimum number. How many squares are required to make 17? What is the minimum number of squares needed to make a perfect square? It is okay to make 14. In this way, whatever comes to the minimum in all this, we will punch it and add it to one. Why one, no matter what the reason. If we let's assume this minimum has come, this one's minimum has come, then once we have done a perfect square here, it is understandable to break it till 9 or if let's assume this minimum has come, then once we have done the breakdown till 17. I told him about One, we dated, I understood the same, One Plus and this will be our answer, there is no problem, even I don't think there should be any problem, it was a very simple concept, there was no rocket science, if I talk about the solution only then its record. Our magical function is, we are passing this to our N and what is it giving in outward, number of minimum perfect square, you get even, it is equal to N, that is, how much minimum perfect square is required to make N, that will do our magical function here. Solve function: I had taken the Solve function: I had taken the Solve function: I had taken the name of research function and if you pass this equal to 12 then the output will be 3 minimum 3 perfect squares. How to make 12 is not done, it does not mean we have to write our function directly, it is ok here. I have explained to you here the logical part for writing the function, which I had explained in the first step, what is the logical part, basically how are we doing the breakdown of one and the other, now what are we doing the breakdown, basically how are we checking all the possible We are doing this, how does it become possible, why because we cannot square 18 - 5, how does it become possible, why because we cannot square 18 - 5, how does it become possible, why because we cannot square 18 - 5, why because it will become bigger, it will go into negative, okay, then whatever minimum comes out of this, the minimum number of squares will come, we will take it here. And we will do plus one because one n one, so we will make it out of this, I hope you must have understood it was not rocket science, I have been truthful, it is very easy, you must have attempted it, then you will be able to relate, I am here. Immediately I am explaining to you the base condition is nothing, friend, I always tell you that the output has to be checked on the smallest valid positive input, how in this, the function we have is just going to be N, what can be the minimum and It can be zero, it can be one, it can be three, if let's suppose is zero, then what will be the output for zero, how many numbers of zero can be written by adding them in a perfect square, for that we need zero. Thoughts a zero n = 0. Or N need zero. Thoughts a zero n = 0. Or N need zero. Thoughts a zero n = 0. Or N Lee, give it equal, you give zero, there must be no problem, I am speaking the truth, friend, recursion is not easy, you just need to understand how to move things on, now you will say, brother, I am not able to move on at all. Now the easiest code to understand is that a function called Solve was created and passed. This is our base condition IF else let it be equal to zero, give zero, no problem, understand one thing here. Now let me take the example of N = 18. Let's understand one thing here. Now let me take the example of N = 18. Let's understand one thing here. Now let me take the example of N = 18. Let's go. Okay, so if and answer is this call, I have taken max, why I have taken it max, I will tell you now, the loop is going on here, i is equal to one, i * i to one, i * i to one, i * i <= n and i plus, why did this happen? It is very <= n and i plus, why did this happen? It is very <= n and i plus, why did this happen? It is very important to understand here, first let i = 1. important to understand here, first let i = 1. important to understand here, first let i = 1. Okay, so 1 * 1. Now out of 18, what are Okay, so 1 * 1. Now out of 18, what are we doing? Are 9 - Can do 16 - Can do so let Are 9 - Can do 16 - Can do so let Are 9 - Can do 16 - Can do so let us check in advance Is one i * i us check in advance Is one i * i us check in advance Is one i * i possible Less than 18 Yes possible then if this is equal to u one then and then if i = 2 this is equal to u one then and then if i = 2 this is equal to u one then and then if i = 2 then 2 * 2 4 It is smaller than 18, it is possible, then 2 * 2 4 It is smaller than 18, it is possible, then 2 * 2 4 It is smaller than 18, it is possible, its tu three in tu three nine is small, it is possible, ok 4 * 4 16 is smaller, it is possible, ok 4 * 4 16 is smaller, it is possible, ok 4 * 4 16 is smaller, it is possible, ok than 18, then it is possible, we will move on to the next one, let us assume i = 1, if it comes then the move on to the next one, let us assume i = 1, if it comes then the move on to the next one, let us assume i = 1, if it comes then the square becomes a square. Number became square number SKN ok square number become that become one tu ke kaise mein bana 4 3 ke kaise mein bane nine and here let's suppose one become tu become four become nine become 16 ok hum kya kiya let's suppose if one we We are choosing that yes one n perfect square we have chosen the verb we are perfect its we have chosen that yes one we are counting in our summing things then we will mince n to n square number is correct and will check that this What is coming and this will store it in the count. Okay, we will do it. Let's go for four. We are choosing. Okay, so that means you were doing something. What will be the square of 4, so we will make 4 minus. What will we be left with out of this? 18 - Same - explained to you one four 18 - Same - explained to you one four 18 - Same - explained to you one four nine 16 Okay, so whatever we have remaining number child hundred - 17 child here let suppose 14 child here hundred - 17 child here let suppose 14 child here hundred - 17 child here let suppose 14 child here 9 child here you child 17 put in the form of perfect square How much total number of squares is required for this, that function will be given by taking it from our record. Whatever is given by taking it, we will add it by one, because we have done this here, then this one square and it will be stored in the account and ultimately. What we are doing is we are storing the minimum amount which came late, after supposing it again and again, then the minimum amount got stored in our answer and we returned it as answer dates. This was a simple concept, man. There was nothing else beyond this, if I explain the message to you by coding it is very simple, there is nothing rocket science here in c++, keep in nothing rocket science here in c++, keep in nothing rocket science here in c++, keep in mind, you guys, I did not do anything, I checked here that it is flat supposition and <= 0. Returned zero, okay, <= 0. Returned zero, okay, <= 0. Returned zero, okay, then checked here and answer is equal to you and max, I reduce one, okay, from one to 1234, let's see how far the perfect square can go, okay, so I * I so I * I so I * I <= N is okay square number A is good here N - will not be good here N - will not be good here N - will not be accepted okay but if I submit it here tomorrow I am doing it okay in the back so here if we have to convert the maximum constant in DP code then They have a step called memorization, okay, what do we do, nothing, they make a factor called DP, 1000 one, I have made it because I was liking the value of N, minimum 10, it is okay till D power four, 1000 a month, everyone's minus. The reason behind this is that I have already told you that what we are doing is by recalculating a function again and again, we are storing it after each calculation so that we do not have to recalculate again and again. We had to do this and where did we store it in this, so I put a check here that if DP is off and note should be equal to -1 DP is off and note should be equal to -1 DP is off and note should be equal to -1 then we will return it and what we are storing here is Har N K. For this, whatever we are calculating is fine, we store it in DP of N, dates it and we are not doing anything extra, so one change happened here and one we sliced the happened here and one we sliced the happened here and one we sliced the DP vector. We have to write 1000 sure two lines and our recursive code is converted into TV. What is the problem, it is doing it repetitively again and again What is the problem, it is doing it repetitively again and we do not want this, we want to store what is calculated once. And we have stored it in DP of N and checked it before returning. Okay, no, we will do the vector and DP 11 0 here. Submit or submit successfully. I hope you understood how to reduce the code of perfect square. I am doing this, how we have converted a record only to the court, how we have designed the solution, for those who did not understand, I have explained the truth in a very good way, please attend the video once again. Look, I guarantee you will understand, what is the problem with you get scared before even attempting, which I don't want you to be afraid of, friend, you send him, do attempt, I am telling you the truth, it was a very easy question, I am searching, this is the best. They See You Learn Thanks a Lot
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
179 |
you're doing great our today's question is largest number given a list of non-negative integers given a list of non-negative integers given a list of non-negative integers arrange them such that they form the largest number for example 10 and 2 are the given elements in the array so 210 is the output because if we place 10 before 2 it forms 102 and if you place 2 before 10 it forms 210 and since 210 is more than 100 2 the output is 210 similarly it could be this so here the largest number that can be formed from these numbers is this right so the important thing to note here is that if we just sort the array we will not get the output because for example if you sort this 3 would be the first number 5 second 9 30 and 34 which will not form the largest number 9 at the first position and then 5 3 and so on these this is the sequence that forms the largest number so simply sorting the array is not going to give us the answer the results may be very large so you need to return a string instead of an integer all right so let's have a look at the various approaches we can use to solve this question which is clearly on an unsorted array so pause the video have a look think come back ok so since this question requires us to rearrange the given array elements in a specific manner so that we get the largest number that can be formed from those numbers here we basically need to sort but we just need to sort the array in a specific way right so we need to tweak the way we sort the array or we basically need to tweak the way the comparator works for sorting the array right so it's very simple and very straightforward we need to overwrite the comparator in a way that we are able to generate this output so since the output is given and we need it to be a string what we will do is that we will first convert all these numbers into their string representations and then create a string array and then sort that string array because it's easier to like just a paint or concatenate two numbers and find out which one of the combination is bigger a plus B or B plus C so that's what we will be using and sort the string array likewise to get the output and then just append them and form a single string and that should give us the answer so let's get started so our first base case is if there's nothing in nums it's always better to handle such base cases because that gives the interviewer an idea that you're thinking and covering all aspects of the problem and you're also taking into consideration some base cases so that's always a plus point so okay so if the length is equal to 0 then the rotor on a blank string okay then as I said we just want to convert this so let's call it string array as a equals to new and the length would be the same as the length of 10 ohms okay now let's use a for loop we need I here that's why we are not using the 4-h and simply let's are not using the 4-h and simply let's are not using the 4-h and simply let's call it okay now we need to parse this so we'll use integer dot to string method from the integer class so this will convert this number into a string yes okay now the main part we need to sort it right so we use arrays dot sort and we want to sort se right and we have to overwrite the comparator so comparator will receive a string okay so we have to override the compare method which will again get two strings right E and B okay so we can have two orders right like what for example Oh one the order one equals to a plus T and the other order would be B plus a friend so instead of like finding out if one is greater than this then return this and that simply we can make use of the compare to method of string itself which will basically compare the numerical representation that is present in the string value and it will return whatever it is bigger right so what we do is we compare over nando to using the compare to method of the string class and that's what we will return another thing to note here is that since we want to arrange these in the decreasing order right because we want the largest elements we want these to be arranged so that such that the number that gives us the largest number is at the front right we have to arrange it in such an order so we will be returning or two - order so we will be returning or two - order so we will be returning or two - oh one or Oh to compare to open right so we are basically reversing the order like we have done in a lot of other problems or where we have used comparator so it's just the same logic okay so all you have to do return Oh - OH - dot compare 201 that's return Oh - OH - dot compare 201 that's return Oh - OH - dot compare 201 that's it okay now there's one important thing to note here that if all the elements of nums are zero then that would not be caught here so we need to check that after sorting if the first element of the array the sorted array is a zero then we just need to return zero okay so we just check that if this since it's the string we use the equals method okay we just return zero the string see right okay now all that's remaining to be done is just create a string builder object sorry okay and use a for each loop I do it through si which is the sorted array and just keep on appending s to the string builder and then return the string representation of SP yeah looks good let's see if trance okay let's submit yeah it works all right so the time complexity for this will be O of n log n because we are sorting the array so that is clear léo of n log N and then after that we are traversing through the array the sorted reading ones but that's of n log n plus o of n so it still gives us of n log N and the space complexity would be of n because we are creating another array of the same length to store the string representations so I hope you enjoy this and you find this helpful if you do please like share and subscribe keep coding and tickets
|
Largest Number
|
largest-number
|
Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
**Example 1:**
**Input:** nums = \[10,2\]
**Output:** "210 "
**Example 2:**
**Input:** nums = \[3,30,34,5,9\]
**Output:** "9534330 "
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 109`
| null |
String,Greedy,Sorting
|
Medium
|
2284
|
1,971 |
one now find a path exists okay so we'll go through the question there is a bi-directional graph then there is a bi-directional graph then there is a bi-directional graph then vertices where each vertex is labeled from 0 to n minus 1. and the edges in the graph are represented as a 2d integer array HS uh where each edge of I equal to uh U of I comma V of I which denotes a bi-directional edge between denotes a bi-directional edge between denotes a bi-directional edge between vertex UI and VI so every vertex pair is connected by Atmos to our one inch and no vertex has a edge to itself so there are no self edges so you want to determine if there is a valid path that exists from vertex source to vertex destination so we were given the source and the destination and we have to find out whether the path exists from source to destination in the given graph okay so that is the question so uh if you consider the test cases so we have a zero one two three four and five right so you have this as a you know test case so now uh this is a bi-directional graph so now uh this is a bi-directional graph so now uh this is a bi-directional graph that means uh if there exists are Edge between zero and one then that is also an edge for one and zero as well so okay so the input here is given as a you know 2D integer array so to simplify this problem we will convert uh the given integer array into an adjacency list so if we uh do this uh for every uh you know node so for node 0 adjacency list would be one comma and for Node 1 it would be zero and for node two it would be 0. for node 3 it would be 4 and 5. and for node 4 it would be 3 and 5. and for node 5 it would be 3 and 4 right so this is The Edge essential list so this adjacency list is nothing but the you know collection of the edges or the collection of vertices to which node 0 has Edge okay so once we convert this into an adjacency list what we have to find is we were given a source and we are getting a destination so we have to find if there exists a path between servers to destination so how we are going to do this so we can use uh you know any of the traversal techniques the graph traversal uh BFS or DFS okay so uh and I actually like uh doing in recursion so I'll choose DFS here so if you choose DFS so we have to maintain a visited array okay so this tells us whether that node is visited or not during the traversal so this is one important factor we have to consider so in DFS from where we are going to start DFS from the source because we want to find the path between source and the destination right so we are going to start the DFS from source so what we are actually going to do is we are going to perform the traversal and we will check whether in this traversal the destination node is visited or not simple check if you come across destination in the Traverse that's it right I think you understood the logic so we are starting the DFS from source that means we are going to Traverse all the connected components to the source so at one point if we reached our destination then the visited a value of that uh node would became true right will become true that means there is a path between our source and destination so this is the logic that we are going to use so let's get into the code so and one more case we have to consider is if the source equal to destination that means we are having the source and the destination at the same node then it is true right so that you have to take it off and this code is to convert the given itches into adjacency list so once we converted that we are initializing a visited Matrix and for now I'm filling it with -1 for now I'm filling it with -1 for now I'm filling it with -1 because I didn't visit any other notes and then you have the DFS function okay so we're calling the DFS we are passing the number of nodes adjacency list Source destination and wasted Matrix so at the end we are checking whether our destinations visited value is equal to -1 or not that means if it is visited or -1 or not that means if it is visited or -1 or not that means if it is visited or not so coming to the DFS function so if my adjacency list dot get of the source uh you know is zero the size is zero that means there are no nodes connected to this then there's no point in going uh you know for traversing right so we'll just return this and for each and every uh node in the adjacency list that we have for the source we're going to check whether it is visited or not if it is not visited we are going to change its value to visit it and we're going to call DFS for that node again so this is basically a recursion so after doing all this uh we'll get the uh desired output let's submit the code so yeah it's supplemented right so this is how uh you know we're going to deal with these kind of problems
|
Find if Path Exists in Graph
|
incremental-memory-leak
|
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges.
|
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
|
Simulation
|
Medium
| null |
208 |
hello welcome to sun record today we are going to solve the two zero eight lit code problem it's a implement try or prefix tree so basically if you read the problem statement saying that we need to create some data structure called try you in that structure we will going to implement three kind of method one is for inserting any what and one is the searching for what whatever we inserted earlier another one is start switch side in the start suite we are basically we will check that is there any word is exist with the given search start with string right so basically we need to implement this setting so okay let's deep dive to this uh example and let's try to uh try to make it better understanding what they want to say or what we want to develop so basically i took the same example so basically try is the kind of data structure also to for storing word and searching what right so it's an advantage that we use we used to take only order of end time for insertion and order in time for searching also right so how try works let's try to build our try tree right so this kind you if you take the name it's saying the prefix tree right so it's kind of tree only right so let's try to insert the first correct first word right so suppose we want to insert apple in our try data structure so for that i am going to i need to create one i need to design algorithm for insertion right so let us insert that so what tri data structure says each node so basically you need to consider these two nodes also that we can have only a to z small lowercase letters only and we should we will not get any non empty strings right so since we are just considering lowercase for this problem we can just think we can take we can consider should a to z minus total ah 26 character only right so not more than that so it every time it will fix right so basically what tried data structure says it so suppose i am i want to insert my apple right so i will take the i will consider my first character and i will check that is that character is exist on in our try or not so how we can check that so basically in for each and every character we are going to maintain a separate node right in a tree so initially we have node right so for each and every node we are going to maintain a separate character for that right so basically if i will start from suppose its my root node right so this is my root node i want to start inserting my i am just inserting my apple what right so i will check for the apple right so this one so i will see okay so there is nothing for apple right so there is no existing initially it is blank right so i am going to insert apple here right so let me insert a then i will check is there anything p after a so a had does a have any child for p i think again there is no child right so i am going to insert b here right so let's insert p here now after that i need to check the same thing for is there anything for after did p have any child for p so i already told you right since we are just considering uh small lowercase character so each and every node can have at max 26 nodes right 26 child node so again i will see there is no child node for p right so again i will create one of the new node and i will insert p there after that we need to check it for l right so how we can check for l basically again p don't does not have any child for l right so i am going to insert l there after that what i need to check for e again for e we don't have anything right so we are going to insert e here okay so let me quickly connect this and then after that i will try to insert another word so let me connect this first so this is how it will look like for our try okay so now uh what i will do so now okay so there should be another connection okay so now what we do i will try to insert this second character ah this one right f so again i will start with a right so let's start with it and i will say okay a is already there right so we don't need to create a separate node for a right in the index 0 a is already there so we can we are not going to insert anything right we are going to reuse that character node okay so now what i will do i will i need to check for t right so again i will see that okay p is also there so then we don't integrate anything right then again i will then i again i will come here right and here i can see okay i have again p so p is already exist so we don't for so for inserting the app what we don't need to create any extra nodes since app is a sub word of apple right but somehow whenever we will search we need to identify that this is the end right so for each and every node character node we are going to each and every node has to we have two properties right one is the bull one is with the child so it should have max at max 26 child and it should have one flag associated with that with it right so using that we can understand okay this is the end of my work so we don't so if whenever we are going to search anything then using that flag we can identify okay this is the end of what end of a word there can be a sub word but that is also what and so using that flag we can identify that what is exist or not right in our try so for each and every node we are going to maintain one flag right and i will set that flag as true that means this is our end of a one particular app word right so similarly we will do it for apple also light so again i am going to set my flag here true right so that i can identify later this is a what we already inserted right in our try okay so now let's try to insert another word so let's take an example so suppose we want to insert one word like epic something like this app y right so how we can do that so again i will check a is already there p is already there but whenever i will come here then i will see p has only one child only that is i right so there is no child called y right so basically again i need to take another i need to create another node and i am going to insert y there right so after inserting api or it will look like this and obviously i need to set my flag through here right so this is how the tri data structure look like so suppose if you have any word from bat or something like bad so there should be and separate added for the same right bad so let's take the example for bad also right quickly so if i want to insert bad so what i will check okay so there is nothing for b write i am going to create one b for b then again i need to create for a and then again i need to create for d right since there is no child exist for b right so again let me quickly connect that so it should be like this and okay so it will look like this right so our try will look like this again i will need to make this flag through right so it should be flagged should be equals to true right so that i can identify this is the end of a word right so this is how the insertion happened right so let's try to understand the logic part similarly for search also so how we can search so basically we are going to use the same logic right so at first i will check for each and every one suppose i am checking for apple right so i will check for a and i will found it okay then i will check for p again i will found it then again i will check for p again i will found it but we need to stop at any point in one condition right so here we will stop once we find all the five so apple has five its length is five right so whenever i will five i will find all the five characters in our try then we are going to return true from there only right but there is another scenario also right so suppose i am going to i want to search for f right here i found a then p and again i can see okay i found all my three characters but it can happen that we have not we did not inserted this app right so in that case we have so suppose it's a substring of a ah of a actual bigger string like for f is the substring of apple right so if i found a suppose we are searching for app and i found that then i need to check that is that a really end of it what whatever we inserted so in that case we are going to check this flag right if it is true then we will going to return true right that means that what is exist if it is false then we are going to return false then means app is exist in the try but that is not the actual string we inserted that's a probably a substring right so that is the case so if it is false that means app is not inserted right so whenever we insert the app then only we make it true right so suppose we did not inserted this right and we just forgot this side so if it we did not insert it so it should be false right then in that case i will i am searching for app i will find app but i will see that okay it will be false right if we are not inside it will be false then angular written false actually the word is exit but we have not inserted it probably it was a substring of apple okay so this is how we can search it right and another one it starts with so that's also kind of similar to search basically we need to suppose we need to start with app right so i will see okay a is xzp is xvp but in that case we don't need to check the flag right since we are using just checking the start suite not the actual word so apple is also start with applied so in that case i am going to return f so we don't need to check flag for in that scenario so let's proceed and let's try to code it out in java ah so one by one so at first we will do it for inserts and then search then start with light and then i will also give you code walkthrough so what i will do so at first i will need to take i will take one another separate java poser class and probably i will name it as trinode only and it should have two properties right one is the boolean that boolean flag that is its end of not so probably is end let me name it like this is a leap node leaf means end right so it should be okay and that there should be another so each and every node can have maximum 26 child rights so it should be an array right array of try nodes okay so let me define and demand declare that also and let me name it as child only okay child now let me create one constructor default constructor public trinode and let me initialize this value also so how we can utilize it so initially this dot is leaf will become false and this dot child will be a new tri node at a of 26 since we are considering lower case letter a to z only okay i think that's pretty much for the puzzle now let's try to ah insert it right so before inserting we need to declare one variable here it should be type of trinode and let me name it as root only and in the constructor we are going to initialize it so it should be this dot root equals to new tri node okay we are just calling this constructor right this constructor okay now let's move forward ah let's try to insert it right so in the for inserting we will get one as word as the input right so what i need to do check first so what i will do i will take one temporary node here so probably equal to t or temp and something like this it name should be named and inside that initially it will be it will point to root only write root index now what i need to check so let's go back to our actual diagram right so i need to insert apple so i first i will i need to check that a is exist or not right so let's check that so how we can check that consider one thing that we are using integer added right so we are since we are considering 0 to 26 so somehow we need to convert this character to integer to get the actual index right so how we can do that it's very pretty simple so probably we can take another integer temporary variable in that we are going to store the actual index right so it should be one dot care so it's a pretty inbuilt method carried using which i can pick up the current uh correct current character for of that word so i will pick it up for initially what it should be so basically okay so basically we need to check for the we need to suppose i am inserting apple right so since we are inserting apple i so i need to run a for loop from a to e right so since we need to insert all the character right so let us define one for loop here so it should be int i equals to 0 and i should be less than what dot length make next what it will be after that i need to increment i counter right after that what i need to do i need to check this logic right so i need to pick it up the index so it should be carried at i and if i so since it's a character and character contains the ascii value i am going to do the minus a right ah so basically a character starts from the 65 right so basically since where index is 0 to 26 so suppose it's apple for a it's a right this will return a minus a so 65 minus 65 is 0 right so basically a will be saved in the zeroth index right similarly it will be for b and c and d right so basically uh to get the current to get this index we just need to do minus a character right so that will give me the actual index right in the try edit okay now let's move for uh move further so i got my index right so now i got my index i know that a right so now i need to check is that index and null or not if it is a null initially it will be now right then in that case i need to initialize one new index right so let's do that so how we can do that so i'm going to just check that my the what was my temp right temp same dot child and whatever index j equals to null nulls means that there is no exist no node exists for a right so for that case what i am going to do i need to create one i need to initialize one new tri node right so let's do that so temp child j should be a new try node okay now what i need to do ah once we are done so if i found it if i whenever i am done with the creation of new node i am going to insert my value there right so i am going to visualize that there right so i need to go further right so what i will do so it should my team my new team will become so i in this after until up to this what we have done here so i found this child i found that there is no node for a i initialized one new node and i inserted there now i need to move further right i need to check it for p so i need to increment my counter right so let's do that so if team my name will be temp dot child and it should be j right so i think okay so it will run for all each and every character now once we are done with that we are just so we inserted apple here right so i came till here right now i need to set this flag right so let's set the let's set this back up to the for loop so what it will be it should be temp dot what was the attribute name it was easily pride so is leaf that means its end is leave equals to true i will make it true so that's a end of a word so apple then l e is the last word or last characterized so that i make it true right now let's do the ah implementation for search so basically for search also we are going to use the same logic we are going to take one try temporary node ah let me name it as same again i will start from root now what i need to check that ah okay so what i will do so since we had we need to check it again and again right so we are going to use recursion right so we are going to declare the separate function right for search and i am going to call that function inside this search function right so let us create and private function since we are not calling it from outside and its return type will be obviously boolean uh let me name it as find words okay and in this we need to pass one index right so we need to keep tracking the length right to identify that we have we are done with all the character iteration right and after that we need to check the flag right so we need two thing as input one should be int index initially we will start from the zero character and it will go till what dot length right and we need obviously we need the word so it should be string what then again what i need my index right so it should be a try node sorry my actual root node right from where i need to begin so it should be let me name it as node only okay so now move forward so what i need to do so at first i there should be one scenario right so suppose i found all the character there i need to check that my length is equal or not so let's check that so if index equals to what dot length then that means we found all the five character now we need to check is that a really end right so we can test directly return it should be node dot is leaf right so whatever is the value if it is true then true if it's false and false right so this is for the last condition when we will find all the characters so let's now let's forget this part now let's consider from here right we are searching for fl we are here now so i need to check that this node is exit or not if it does exist that means a is present if it is not then a is not present right so let's do that so let's check that so how we can check that so basically ah what i need to do i need to calculate index one second right to get the index so it should be into j equals two and it should be y dot care at and since we are starting we are keep tracking everything using this index variable so it should be carried at index again minus a to give the actual index and i am going to return what i am going to return i am going to check two condition and that okay so before that i need to find that temp node right also so let me take one node called tree equal to temp node something like this and it should be node dot node.child node dot node.child node dot node.child and it should be indexed would be j died so if you exist that means that character is found if it is not found then we are going to return false so whatever we need to check so in this condition i will going to check return temp node equals to equals not equals to null if it is equal to null then we are going to written false right so if not equals to run and if it is not equal to 1 then we need to check further right so similarly we need to call this function as recursion so find words again in this case my index will be found since we found my our first word so we are going to increase my index so index y one again after that we need to pass my word obviously and i need to pass my temporary node right as my i need to move further right okay i think that's pretty much for the search itself okay and whatever it is it will we're going to return that okay so now let's let us call it from here only right so let's call it so return but what we will call here again we will call this find words method and we need to pass index in since we are starting from zero we need to pass the zero then what then this temp right root or temp something like that okay i think that's pretty much for search now let's do it for starts with and so similarly basically for start two is also we are going to use the same logic as search but we do not need to check this condition right we need to want to keep the keep tracking the index right because suppose we are in checking for app right so apple length is three so there is no point to track the f right uh track the index or length right since apple is length five f is three so we need to just check a is exist if a is agreed then i will check for the next one p is exist okay it's exist then i will move forward and i will check if x false right we will not bother about the rest of the force and right so let's write logic for the same also so how we can do that so we can again take one temporary node and it should be temp node something like this and again i am going to initialize root here now what i need to check i need to probably run one for loop so it should be uncare so i am going to use enhanced for loop i am going to similarly i am just going through each and every character and i'm going to pick the index so it should be prefix to can add a so i'm just converting it to carry array and once we are done with that now what i need to do inside this for loop i need to pick the index type so i will check that if my temp node and dot child and index will be c minus a basically it's the same thing we are doing it's a shortcut kind of thing equals to null then that means it's not exit then we can return false from there else ah if it is not returning false then we need to move forward right we need to move further so i found my so suppose i am searching for f right and i found a now i will come here right so now i found a now i will i need to check here right so let's do that so how we can do that so again i need to engage my counter right so my temp node will become my temp node will be temp node equals to temp node dot child should be child and it should be okay so it should be temp note child and ah what will be the index so it should be c minus a okay something like this and if it is not written false inside this for loop then it that means we found all the character required character and we need to return true from there only right it should be written true okay now i think we were pretty much done let's run our code and check whether it's compiling or not i think it's throwing some adder let me fix that quickly okay double equals okay it should be single equals and anything else let's run it once again and check okay i think there is one other one in line number 51 let's fix that also quickly basically it should be since it's a java it should be one equals okay so i have done some typo here everything will be tri node instead of prenode let's check that quickly is there anything still there or for tree note yeah i think we have tree node so let me rename it to trinode one by one okay i think that's enough yeah i think the solution is running now and its runtime is five seconds so basically i fix all the errors so there are some type of tree node and all and now let's submit our answer and check right whether it's submit accepted or not yeah i think it's accepted our solution is accepted you can see so now let's go through our code let's let us give that so let us go through our code and try to understand what we are doing here right so for the inserts and right so what we have done at first we created this fojo right so this is our project we are taking sleep to track the end of a word and we are taking a child added so it should be size will be 26 forward since we are considering a to z so while inserting what we are doing here so we are going through each of the character of the uh particular word whatever we want to insert and checking that is there any node exists or not so since we are doing checking ah we have to it we keep we are taking integer address so we are need to convert this using this minus a so since using the ascii value we are just taking the integer index of that particular character and we are checking that so since we will start with root right so i will check that a is exit for so a in index of a is exit in our existing try or not so if it is null that means it is not exist we are going to initialize one new node for the same and we are going to insert a there right then i will move further like and what i will go till end and whenever in at the end we are going to set it through right so that means that's the end of word right so basically for searching what are doing here we are using the recursion so this is our searching logic we are doing similar thing so we are taking index so that's the index so suppose i am searching for apple right so my index will be initially zero and i will find okay a is already there then i will move further my index will be two one right again it's there right and for each and every uh before we if we for calling our caption we are checking the index right so whenever i will see that my index is reached to five since the apple length is five i am going to stop my execution i am going to check that its end or not right so similarly like this we will come here and here my index will be five and i will see that okay and i will find and i will also see that my flag is also true right easily flag is true then i am going to return true and i will say that this word is exist right so that's what i have written here for search and similarly for start switch we don't need to keep track this flag thing but rest of the portion is like search only right so i will check this if this exists exit if all the three characters exist so suppose i am i'm doing this right starts with app then we're going to return true i think that's pretty much for this video i hope you understand this video uh let's do some time complexity analysis also before we close this video uh so for it for the insertion right so suppose i am going to insert apple so how at worst case scenario how much time it can take so basically in the worst question what can happen that no node is exist right so in that case we need to create we need to initialize three new five new node right so it should be order of uh n is the word size right so for searching also we need to check for each and every character again the searching is also order n order of n so basically insertion and searching is both is order of n is the word length i think that's pretty much for this video i am going to add the code link in the video description thanks for watching bye
|
Implement Trie (Prefix Tree)
|
implement-trie-prefix-tree
|
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
| null |
Hash Table,String,Design,Trie
|
Medium
|
211,642,648,676,1433,1949
|
224 |
welcome to september's lego challenge today's problem is basic calculator given a string s representing a valid expression implement a basic calculator to evaluate it and return the result of the evaluation you are not allowed to use any built-in functions which use any built-in functions which use any built-in functions which evaluates strings as mathematical expressions if we're given a string like one plus one we want to return two if we're given a string like this we want to calculate everything and return 23. they give you a couple constraints you can see the string could be pretty large so we probably want to do this in o of n and string is going to consist of digits plus minus parenthesis or white space now one thing to note is we could have a minus being used as a unary operation so that just means like we could have minus parentheses one plus whatever meaning that the whole thing needs to be negative at the end okay so say that we're giving this string here how do we solve it normally if we were to solve this normally by hand what we would do is probably solve everything in the enclosed parenthesis first here we can see 4 plus 5 plus 2 equals 11. here this would be 14. after that we'd solve everything else this would be 12 minus 3 so that'd be 9. and finally solve everything here with 23. but we really can't do that here with programming this is programming we could i suppose look for the enclosed parenthesis and try to do some sort of recursion but it's going to be very inefficient how can we do this in one pass after all our length is going to be quite large so if we were to do this in one pass what we would probably have to do is store some partial information somewhere as we move along because you can imagine whenever we have a parenthesis we want to calculate everything within it first right but we can't just keep track of like everything rolling we have to store like this last operator that we've seen as well as whatever we calculated so far before so uh with this example we'd have to have the stack what we'll do is add whatever we've calculated so far like here at one we've calculated one we're going to add that to a stack here and we'll reset our output and also store the last operator that we saw that would be a plus just in case this is a minus here now once we do that we'll reset and calculate everything within this parenthesis this would be 9 be 11. and when we see a another close parenthesis what we're going to do is uh take what we've calculated so far and use this sign to see if we want to add or subtract from what we've gotten so far so if this was a negative we would actually say 1 minus 11 like this and this sign here is what we're going to keep track of to make sure we do that so we have to have a couple things to store here we have our output that's what we're going to return we're going to have the current number so far that we've calculated as well as the sign which is whether we've seen a plus or minus last as well as stack so this would be zero sign would be we'll start with one and stack would be just a list so for c and s there's four possibilities we could have a digit we could have a plus or minus or we could have parentheses right and depending on whether it's a open or close we're going to behave a little bit differently here so if it does digit it's pretty simple what we want to do is just make sure that we calculate the correct number because we could have like 123 but these are all strings right so to kind of take care of that we'll say if c is digits we're going to get a curve and say occur times 10 plus the integer of c this will make sure that we calculate the correct number now otherwise if c is equal to or i should say n plus or minus well there's a couple things we want to do we want to reset our current to equal zero and we want to add to our output whatever we've calculated so far so we'll say output plus or equal curve times sine now depending on whether this is a plus or minus if c equals minus then we want to set this sign to equal negative one otherwise make the sign equal to one okay so just plug this here okay so we're taking care of the operator now what about a open parenthesis well this is where it gets tricky if it's an open parenthesis we want to store what we've calculated so far onto the stack right so we'll take our stack and append our output right now and we also want to reset this output to equal zero uh but we also need to keep track of the last sign in case it's the unitary where we have to like subtract the whole thing so we'll say stack append the sign that we saw last and we can reset our sign here as well and finally when it's a closed parenthesis notice i can't do else here because we could have white space what we'll do is we've reset our output but we could have a new output right now right so first add the current times sine to our output and we are going to pop off from our stack whatever the last operator was so this would mean we're just going to multiply this whole thing by whether it was a plus or minus because we're going to either add or subtract the whole thing right so we'll just multiply by stack pop and then we're going to add whatever stackpop is here as well and i believe we're just going to have to reset our current now to zero but we don't need to do anything else finally we return our output but one thing we also need to add the current times sign here because we only finalize our output when we see a closed parenthesis right or a upper operator we could have you know even one plus one here that last one wouldn't be added so we'd have our current number here and our sign so we decided at the very end and that should be it so let's make sure this works all right let's just do a more complicated expression just in case okay so that looks like it's working let's go and submit it so there we go accepted this is oven time complexity and space would be the same because of our stack now there are some other variations to this you could use a combination of stack and recursion you could possibly use two stacks but it starts getting really complicated i found this one to be the most simple so hopefully this helps you know my first approach at this was quite the mess so uh this is a very difficult problem as far as i can tell all right well thanks for watching my channel remember do not trust me i know nothing
|
Basic Calculator
|
basic-calculator
|
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_.
**Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
**Example 1:**
**Input:** s = "1 + 1 "
**Output:** 2
**Example 2:**
**Input:** s = " 2-1 + 2 "
**Output:** 3
**Example 3:**
**Input:** s = "(1+(4+5+2)-3)+(6+8) "
**Output:** 23
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`.
* `s` represents a valid expression.
* `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid).
* `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid).
* There will be no two consecutive operators in the input.
* Every number and running calculation will fit in a signed 32-bit integer.
| null |
Math,String,Stack,Recursion
|
Hard
|
150,227,241,282,785,2147,2328
|
385 |
today we're gonna be working on lead code question number 385 mini parcel uh given a string s represents the serialization of a nested list implement a parser or tutorial d serialization and return the d serialize d serialized nested integer so basically if you have been given three to five you will be returning 324 but this one is a little bit more interesting so if you have been given this kind of a string what you're going to be when you're whenever you're going to be looking uh at the opening bracket you're gonna be actually saying that so you're gonna be saying that an integer containing value of 123 so you're gonna have this one and a nested list containing two elements it's gonna have a nested list containing two elements and then when you go into the nested list an integer containing the value of 365 and the second element is also a nested list with one element which is uh 389 so again as they have said like we're gonna be looking at different things uh like we're gonna be looking at do you see an opening bracket then you're gonna actually you're gonna be putting things into a stack now you're gonna be putting uh if you see uh like and a closing bracket you're gonna be done with uh that particular element if you see a comma uh like you're gonna be adding uh like inside the stack you're gonna be adding the next element so again we're gonna be looking at every single character and processing it so for that the first thing we can say that if the string is empty okay if it is empty what are we going to do if it is empty just return the null yep if it is empty its gonna be the null then uh we also have to take care of another special case like what if the character at the beginning is not like look at this one example one what if the first character is not an opening bracket then in that case we can only expect a single entry so we are just gonna uh take that string convert it to an integer and return it so it's a special case so we're gonna say that if s dot character at 0 is not equal to for characters we actually use the single quotes here okay if that is the case i just convert that thing uh into dot value off s and then you're gonna say because we are expecting a nested integer so we're gonna say return new nested integer okay yeah that should do it so okay once we are out of that we know that uh it's gonna start with a with open brackets so we're gonna say that the stack we need a stack for that okay uh the stack and then stack of nested integer let's call it stack which is equal to new stack okay uh and the current nested and uh nested integer is kind of gonna set it to null okay then we our left side is gonna be zero right so basically it is gonna point to the uh the beginning and the right side is actually gonna uh it's also gonna start from the uh from the zero and it is gonna be incrementing and it's gonna go up to the end so for int r the right side it's gonna start with zero and the r is less than e s dot length and then r plus okay then we're going to take our character which we are processing at the moment okay if that character is equal to opening bracket we're gonna say that uh if the current is not null right if the current is not equal to null if it is not equal to null just put the current into the stack right otherwise the current basically in any case whether it was null or not now we already processed that but we're going to say that the current is equal to new nested integer and then uh we're going to say our left is going to become equal to right plus 1. so we updated our uh because we just opened uh we have seen this character if we were processing something else we just saved it into the stack and we updated our left to the current position that okay now we're going to start processing from the next one that should take care of opening bracket okay else if we see let's deal with uh what happens if we see a closing bracket okay if we see a closing bracket first of all we know that we were processing something so we're gonna say that what is that number the string uh number is gonna be equal to s dot sub string uh from l uh to r uh we need to put so if the current is like the we need to see if the number is which we just created if it is not empty right if that number is not an empty number then we're going to process it if that is the case we're just going to process it meaning we're going to take the value of the number and put it into the current so integer dot value of this number okay and we're gonna say that this number is current dot add a new nested integer okay we're gonna add that to the current okay we're done with this one when if it is not empty right also if the stack is not empty uh like if the stack is basically not empty what we need to do is to take the value out of that uh one and then we take the value out of the that one and then because it could be uh wait one second let me write it down nested integer let's call it pop because we're gonna be getting it from the pop we are just popping it so that we can add a new element to it so we're gonna say that pop dot add the current and then current is gonna become equal to pop nice okay this is for the else f right and no this is uh for the now this where did we say that did i just delete that no i did not delete it i need this we only need to do it if the stack is not empty so we need to i think i just said it but i didn't put the code in there and that is empty so if the stack is not empty then we're gonna be doing all that stuff yep okay if the stack is not empty then we can do that and now we're gonna again just like previously we're gonna be updating our l plus uh l is equal to r plus one okay last but not least what if it is else if the character is equal to a dot then that would be another point where we need to process it's gonna be very similar uh we're gonna say that uh our s dot character at uh r minus one if that was not equal to a closing bracket uh then we can process that we're gonna say that string num is equal to s dot once we have the number we're going to say current dot add just like previously new nested integer of integer dot value of uh value of that thing num okay and then just like previously we're gonna update our l to r plus one that would be it so once we are out of this for loop we can just return the current value current is the one where we are actually putting everything in god yep looking good and it works
|
Mini Parser
|
mini-parser
|
Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return _the deserialized_ `NestedInteger`.
Each element is either an integer or a list whose elements may also be integers or other lists.
**Example 1:**
**Input:** s = "324 "
**Output:** 324
**Explanation:** You should return a NestedInteger object which contains a single integer 324.
**Example 2:**
**Input:** s = "\[123,\[456,\[789\]\]\] "
**Output:** \[123,\[456,\[789\]\]\]
**Explanation:** Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
i. An integer containing value 456.
ii. A nested list with one element:
a. An integer containing value 789
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `s` consists of digits, square brackets `"[] "`, negative sign `'-'`, and commas `','`.
* `s` is the serialization of valid `NestedInteger`.
* All the values in the input are in the range `[-106, 106]`.
| null |
String,Stack,Depth-First Search
|
Medium
|
341,439,722
|
959 |
hello friends today last sub-regions cut hello friends today last sub-regions cut hello friends today last sub-regions cut by slashes it says in a given urn times on greed it is composed of 1 times 1 squares each one times one square consists of a slash backslash or blanks space these characters divide the square into continuous regions note that the backslash characters are accepted so backslash is represented as double backslashes slashes return number of regions and see the examples in this case this true / can be continuous so it case this true / can be continuous so it case this true / can be continuous so it divides the area to two parts so we return to in this example even though we have one slash but in this case the whole pattern is also connected so there is only one connected component in this case this fall well these two slashes this is - backslash slashes so it this is - backslash slashes so it this is - backslash slashes so it divides this area 2 to 4 parts so we return for in this example we divided 2 to 5 parts how to solve this problem it seems like very complicated but if you look carefully actually we are how to the number of connected components it is kind of like the disjoint asset in the case we only have one connected component in this example we have four connected components in kids we have five so actually we may think to use the unifying algorithm to solve this problem well let's recall what the components in the unified actually we usually have a root array that means given a node we need to record its root and the we usually will use a size array that is used in one optimization that is sorted by their rank and we have a true function one is a Union two notes and the find is you find a given node its root node and in this function and actually we will always use a path compression okay well actually I have so many problems use these algorithm so I will list these problems in the description you can check it afterwards well the problem is how to use this classical unifying to solve this question well the given grid you can treat it like a 2t character array so one thing is that we need to convert it to a 1d array well that's easy we just needed to do some index calculation that's okay oh now that's thing about two cases one is if the current character is a slash how do we check whether we can divide this area to two parts only when the slashes are continuous and it's a connector from the boat to the boat it is continuous in the Acacia we can divide so forth even character we needed to check it's a next line proceeding : this place we check line proceeding : this place we check line proceeding : this place we check this whether these two parts have the same root if it has the same root we know it can divide the area to two parts so we bet the count of the kinetic components increment by one so the same idea if a backslash we need to check the next align in the next column is part if they have the same root we know is connected if it did not have test them if we do not have the same root we needed to Union them so that's the idea okay so I just think that we need a chew Newell root the size equal to n times M but actually if we initialize a root or to Thompson we may have some problems one thing is that we always need to check whether the index is valid right here we need to check next row next called : we need to check whether the called : we need to check whether the called : we need to check whether the index is valid this is one thing another thing is that for the root initialization who may have some issues because we needed to know whether they are connected the whole way I mean in their continuous way if it's continuous we know we can divide it to two parts so if we in other way we knew the root at U n plus 1 times n plus 1 we can just initialize all the powders to 0 and Oda seems in inside true they are on their route or to their own in their case if the last two have the root at 0 we know in this hallway it's it is the connected I mean if it's a backslash they all have backslash if it's a slash they all have slashes so that's the reason why we initialize the root at u plus 1 times n plus 1 ok because in this way the root actually is transitive only when the slashes start from powder - powder Italy divided area this is the - powder Italy divided area this is the - powder Italy divided area this is the whole idea okay so that means we just need to change something modify of the classical unifying algorithm and we knew the route to a different size and we check the character cell by cell if we meet her this - or backslash we check that the this - or backslash we check that the this - or backslash we check that the next connected the part see whether he's had the same route in Indiana we just need return just join the sound cut that's it okay let's write the code so we first need to write this joint static in the case we need the route that we do not need to the size because in this case we do not need that you to the store to buy their anchor this is a code means the number of the kinetic components and this is the constructor so the future will be 10 plus 1 times n plus 1 the couch efforts will go to one in the for inter I go to 0 Alice will equal 10 and I plus 4 in the J equal to 0 jealous Oh accordion and J plus when you know their index in the 1d array Toyota will be I times n plus 1 plus J right if the I equal to 0 if they are in the boulders J equal to 0 or equal to N or J you go to and we just let the root number equal to 0 otherwise all the other it you go through the self so the root number just you go to number okay then we needed to write to find forgive an odor if the root X not equal to X there we keep fine its root so we change the root executor find root X if it's an equal just to return the root X is because we actually do the path compression okay this is the Union for into X equal into wine we first to find the root X and the root Y you caught your finder why okay if the root X equal to root Y they are connected the idea is a continuous so look how to should increment by one and they were just a return otherwise we need to Union it and you will see actually it is head odor like if it's X this will be Y if it's X this is y so we change the root of Y to the root of x so change your route why children text okay now let's write this part and you go to great talents and the window are disjointed yes you knew TSU pass and there we iterated every character a prosperous for injured J equal to 0 J less than J past us so we get current char which will be great them I char ad - J - case it if you see them I char ad - J - case it if you see them I char ad - J - case it if you see coach others laugh with your check two parts one is the current of place it will be I times n plus 1 plus J I sure will search a plus-one because in I sure will search a plus-one because in I sure will search a plus-one because in their case we know the Y is always valid the index it'll sure be Naxalites so either will be I plus one times M plus 1 plus J because it's a preceding color so it'll always be valid if you were right Jay then in this case we need to check whether J minus 1 is great or equal to 0 it is clear we do not need it you check so the N DSU Union X Y ok another thing else this will see you coach shooter backslash into x value coach you I times n plus 1 plus J why because we have two backslash so when we check here we meet on the first backslash we will need to do the check so the next line will be n plus 1 plus J plus 1 because the next row next column the same thing gives you Union X Y so in the end the return TSU doc out ok okay thank you for watching see you next time
|
Regions Cut By Slashes
|
3sum-with-multiplicity
|
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions.
Given the grid `grid` represented as a string array, return _the number of regions_.
Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`.
**Example 1:**
**Input:** grid = \[ " / ", "/ "\]
**Output:** 2
**Example 2:**
**Input:** grid = \[ " / ", " "\]
**Output:** 1
**Example 3:**
**Input:** grid = \[ "/\\\\ ", "\\/ "\]
**Output:** 5
**Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\.
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 30`
* `grid[i][j]` is either `'/'`, `'\'`, or `' '`.
| null |
Array,Hash Table,Two Pointers,Sorting,Counting
|
Medium
| null |
1,091 |
guys welcome to another video in the series of coding today we are going to do the problem which is called shortest path in binary matrix so you are given a binary matrix and you have to find the shortest length of the path that you can take uh to travel from the first cell to the last cell and the path should be only of all zeros so from first to large cell here uh the length of the path is two in the next example you can see they have marked the path in blue color from first to the last cell the shortest path is consisting of one two three four zeros and so on so let's take our own examples and try to find parts that are going to start from the first cell and end at the last cell but it has to be shortest path if we try to list all such paths right one of the paths would be this right and so on so if you consider the first path it is of length one two three four five right if you consider the next part that i had listed which is this it will be of length one two three four five six and so on right so among all the parts that are possible the shortest path is this one which is of length phi let's take another example in this matrix we have to list down all paths starting from starting to the end right uh one of the paths could be this right another path could be let's say something like this because you can travel in all the eight directions right in this question you are allowed to travel in all the eight directions so this is also one valid path but it would be of length five right you can see that there is another path which is of length four which is like this but the shortest path would be of length three and it would go something like this so how do we solve this question so uh listing down shortest path and you have given neighbors uh bfs is a very good way to solve this question breadth first so let's see what we are going to do bfs uses a queue right so let's start we have to reach from the starting to the end so starting uh coordinate is 0 and the ending coordinate is 2 comma 2 right so whenever we reach 2 comma 2 we know that we have reached the end okay so let's start from the very beginning we have to start from zero comma zero so let's put zero comma zero in the queue okay and along with that let's say this is the first cell that we are visiting right so along with that i'll put one in the queue that means at zero comma zero the length of the path is one right there's a first cell that i'm visiting so the length of the path is one as of now after this in the queue i am going to put all the neighbors which are possible that are going to give me the correct path so if you see the neighbors of one right sorry if you see the neighbors of the first cell if you see the neighbors of the cell which is having the coordinate zero comma zero it has three neighbors right it has three neighbors all other neighbors are not valid but there are three neighbors among these three neighbors two neighbors are having value of one they are not valid neighbors they are useless neighbors right so only one neighbor is going to give me the correct path so i am just going to travel in that one neighbor right so what is the coordinate of this is one comma one so after this in the queue i'm going to put one comma one and if i travel at one comma one the length of the path is going to become equal to two okay so at one comma one the length of the path is two now i come to this cell which is one comma one i see all of its neighbors right so let me just focus on one comma one to make some space let me clear uh the marks around it okay just notice the cell one comma one this is the cell one comma one now how many neighbors does it have it has one two three four five six seven eight neighbors okay the cell one comma one which is this cell which i just marked okay it has eight neighbors now among its eight neighbors first of all which are the valid neighbors only that i will mark okay valid neighbors means see from this cell i cannot travel to one cannot be a part of the path right similarly i cannot travel to this all these are one so these are useless neighbors so let me just mark the useful neighbors only the neighbors which are value zero are useful numbers now notice the neighbor zero comma zero if from one comma one i go to zero comma zero right and make it as length three again from zero comma zero if i go to one comma one make it at length four again from one comma when if i go to zero comma zero make it as length i will enter into a what i will enter into infinite recursive problem where i will just be traveling from 0 to 1 comma 1 and from 1 comma 1 to 0 comma 0 right see if from this cell i travel to this cell from the cell to back to the cell from back to the cell and so on so this will give me a problem so to solve this problem i need to somehow use something which is called visited right that means whenever i visit something i don't want to visit it again i don't want to enter into the recursive problems what i will do you can keep a visited grade you can use a set also to mark which coordinates have already visited you know very simple ways just keep a visited grid whenever you visit something market is true right so i've already visited zero comma zero so at zero comma zero i'm going to mark it as true so next time when i want to visit again zero comma zero i know that it's already true i need not visit it okay so now when i see the neighbors of zero which are valid i have four neighbors which are valid okay so four neighbors are going to give me the path so what i'm going to do i'm going to enter all those four neighbors in my queue any of the four can give me the path right so let's see what are the coordinates of the four neighbors that are possible what is this is zero comma two right so i put zero comma two in the queue and if i visit that the path will become of length 3 okay what is the next neighbor is this one what is this is having a coordinate of 1 comma 2 right so i enter 1 comma 2 also in the queue and the length of the path if i visit it is also going to be 3 okay because 2 plus 1 is 3 right so after to any neighbor that i visit is going to be of length 3 right so this is length 1 this is length 2 and this is length 3 and so on ok so now what are the other neighbors i have already listed on two neighbors this neighbor is also a valid neighbor right so when i list this neighbor when i go into the queue and before listing the neighbor which is 2 comma 2 and the path length is 3 i check that it is 2 comma 2 is the neighbor which is my end neighbor once i hit 2 comma 2 i have reached the end okay i have reached the end so once i know that i have reached the end that means i am going to stop and the length which i am storing along this is my answer so 3 is my answer in this case hey guys a short one minute break a lot of you keep asking about what courses should i take to prepare for placements i would like to share the course that i had taken during my placements which was from geeksforgeeks there our data structures and algorithms course was what i had taken which is this course dsl live for working professionals and it was very uh helpful in fact one of the questions that was discussed during the class that was actually asked in the second round of my interview with microsoft and it was very uh helpful course for building the concepts and they had discussed lot of interview problems during the class so it gave me a lot of confidence during my placements and the course was extremely helpful the pace of the course was very nice they started from the basics from every topic they covered every topic from arrays to dynamic programming to graphs all of the topics were covered in detail and the instructor was also very nice the instructor was very helpful and he cleared all the doubts that we had during classes and i had taken live classes because i found it um very helpful or to maintain dc plane that's why i taken live classes uh but i have taken their other courses also i have taken their system design course also which is very helpful so these are all other courses i will put the link in description you can check it out and there is one amazing news that if you want a discount on their courses then you can use coupon code alicia on any of their courses and you will get a 10 a discount which is pretty amazing so do check out their courses uh thank you so let's move forward to coding it so we have to declare a cue for the breadth first search in the queue we are storing two things first of all we are storing a pair uh for the coordinates and along with the pair we are storing the current length of the path right so it's a so let me declare a pair which we are storing and let me name the uh qsq okay so to perform the breadth first search we are going to perform it unless the queue is okay not empty if the queue has some cells we are going to perform it right so in the queue the first thing that we are going to push is we are going to push the first uh cells coordinate which is zero comma zero and the length of the path is initially one so we are pushing that in the queue right also now we need a visited matrix as we discussed for the recursive uh problem that we may face so we need to mark the cells that we have visited as visited to never visit them again right and it's going to be the same size as the grid so let me take its size same as that of the grid and uh this is how we are going to declare it and the first cell that we are going to visit is the zero comma zero coordinate so that we are going to mark it as true in the visited matrix okay now we are going to perform the bfs and after performing the bfs if we are never going to uh reach the end of the matrix then we can return minus 1 okay or we have a path which is consisting of only once uh then we can return or minus one right we need at least one successful path to return the length of the path okay now uh let's extract the first of all the coordinates of the uh current cell so let me give q dot friend dot first this will extract zero comma zero for me and to extract the x and y coordinates separately i can just give p dot first this will give me zero and if i do p dot second that will give me again zero the x and y coordinates of the first cell are zero comma zero now to extract the length of the current path okay so length of path current length of path uh that i can give by q dot front dot second so currently the length of the path is one because in the queue we have pushed one right this is what we have pushed in the queue so the length of the path is one that's what we have pushed in the queue and that's what we'll expect after extracting this we can pop this element in the queue and now we can visit its neighbors so to visit the neighbors right to visit the neighbors i will give a vector pair in comment neighbors right to visit the neighbors what we can do we can write how much we have to add to the current coordinates to visit the neighbors we have eight neighbors right so one by one if we just add these eight quantities to any cell we will be visiting the neighbors right so let me write all the eight neighbors that we have for any cell right so if i add these eight quantities i can visit neighbor for any of the cell okay so now for pair and command neighbor in neighbors right neighbors is my vector of neighbors so if i add these quantities right so what do i mean by that neighbor dot first plus x if i do this then i get my next cell okay then i get the coordinate of the next cell similarly if i want to get the y coordinate of the next cell i just do neighbor dot second plus y right so this will give me the new neighbors now i have to check if these neighbors are valid or not okay how to check if the neighbors are valid or not so they should be within the bounds if i ever reach a condition when they are not within the bounds then i will get an error so i have to first of all check they should be valid so i am just giving some condition checks for the new neighbors to be valid right and after they are valid i still have to check two things first thing i have to check is they should also be having the value of 0 right because if they are having a value of 1 they cannot be part of the current path and i also have to check that they should not be already visited if they're already visited i should never put them back in the queue okay if they are not visited then it's great so i have to check these conditions after checking these conditions right after checking these conditions now i can put them in my queue if they satisfy all these conditions then i can happily put them in the queue and what will be the length of the new path whatever is the length of the current path plus 1 right because the length of the path is giving me the current length of the path if i add 1 to that will give me the new length of path if i add a extra neighbor i am always increasing the path length by 1 okay that's it now i also have to mark them whenever i'm putting them in the queue i also have to mark them visited as true okay now here i can give a condition check if i reach the end cell right if i ever reach the end cell that means if the x and y coordinates are as such when i'm reaching the end cell right that means that i can return the answer i have found the cell last cell which i am looking for then i can return this as my answer okay that's it these are the simple things that i have to do now there are just uh one or two base cases that we have to consider first of all if in the first cell right if the first cell is itself having a value of one you can simply return minus one as the answer right because this is the condition for that if the first cell is 1 you never have a path because path should have only zeros similarly if there is one more base case which is given which is like this when the first cell is zero and the last cell is also 0 for this base case you can again check if grade of 0 comma 0 is equal to 0 and grade dot size is equal to 1 and grade of 0 dot size is equal to one right in this case the length of the path is one so you can return one these are just some base cases that you can check otherwise it seems fine to me let me sum it and see if this code is working for all the test cases it's working thank you for being patient and listening
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
429 |
hi everyone welcome to my youtube channel i hope y'all are doing well so today in this video we are going to solve lead code daily challenge right so this is the problem of the need for daily challenge the problem is energy tree label order traverses the problem is easy only right if you know about level order traversal for binary tree so in a similar way we have to do it but this time we are having an e3 right so binary tree have at most two children now for energy tree it can have at most n children right so given an energy tree return the level order traversal of its nodes values energy uh tree input serialization is represented in their level order traversal each group of children is separated by the null value see examples so the first example that we do have for this one right so if you are traversing this energy tree level by level so what should be the output so on the level zero we have one okay for level one we have three two four for level two we have five six or you can say for level one we have one right and for level two we have three two four and label three we have five six okay and that's what we are having in the output right and if you will go through this example right so here for label one we have one for label two we have two three four five for level three we have six seven eight nine ten right so one two three for level four we have 11 12 13 for level five we have 40 so level one level two level three level four level five right so that's what we're having in the output the height of the angry tree is less than or equal to thousand that's what the constant even they have given right so now for level of travel so what we'll be doing is the similar weight is going to be like we do for binary tree so we'll be taking a q right and in that queue first of all we are going to insert the given root node right so we are gonna insert that root node and then uh what we gonna do is we are going to explore the other level so uh root node you know that is one is the root node and that is at the top this is the level one now we are going to explore the children of uh children of the root node so right for one if you will see what are the children three two four right and then so three to four you took inside your queue now we'll be exploring for three so three what are the children five six for two there is no children for four there is no children right so that's what we're gonna do is and simply we're gonna insert this level by level when we'll be traversing so we'll be insert or this value to the array list right so that's what it is like i think uh the problem is self-explanatory itself the problem is self-explanatory itself the problem is self-explanatory itself once you'll be having a look on the code you'll be able to understand that what actually i'm talking about so let's have a look so here we have it on list of list right so that's what we are taking here so res to which we'll be storing the value so first thing that you have to check that if the root value itself is null uh then we'll be simply returning this res right no need to proceed further otherwise what we're going to do is we are going to take a queue right and in which we'll be inserting our nodes so first we are inserting our root node right now we are having a while loop and we will be continuing till the time q is not empty one square is empty so no need to proceed for the right so it doesn't make sense so for each level we have to do the traversal level or the traversal we have so in this end we are going to store the size of the cube size will be depending on the number of elements that it does have so for now uh let's say we inserted root uh node one right so there's just one element right so n value is going to be one now this list right so that will be responsible for holding the elements of a specific level so as of now we are talking about level one so uh now we are have we are having this for loop it will run till the time i values less than that of n i plus now we are popping the current node that we are having so let's say we are having the node 1 so current is holding the value right and now what we're going to do is we are going to explore the children of that particular node that was there in our queue right so let's say um we were having at the top we were having one then as of now i'm fighting like this and then for this one what are the children two three four it has three children two three four right so what we're gonna see here this t of energy tree has see value as well as list of node of children right so what we're gonna do is we are going to explore its children now so for node well uh current.children so for node well uh current.children so for node well uh current.children so we're gonna explore all the children of that particular current node so current node is what one so what are the children of current node two three four right so what we're gonna do is we are going to insert them into this queue right so first our cube was having that one then we removed that uh that particular node writes or we did here right q dot pull right so um now we have inserted two three four right so in our cube we are having this two three four okay and also this level dot add right so in our list that we are having right so in our list level we have added this one okay because on level one we are having just one element okay then uh what we're going to do is again we're going to we are going to check this so q is empty no right it is having three elements three nodes okay three elements it is having whatever the size of the q this time that is three okay so for india equal to zero i less than three i plus so first it is going to q dot what we gonna do so current node is two it will be popped out right and then we are going to explore the children of two so let's say for two the children are six seven okay so this has been removed from the queue now this 2 has been removed from the queue now let me uh remove it and it is having children 6 7 so right so that will be inserting in our queue right so our queue is having element 3 4 6 7 right okay so now on i value will be one this time one less than three the condition is still true right so this three will be popped out right this three will be popped out this time and see we are continuously live we are continuously adding these values to our level as well right so first we added in our level current dot well right we are adding this then three also we added in our level for three uh let's say there is no children right so there is no children for three okay then i value will be what two less than three condition is still true right so we'll be popping out this four also because you can see two three four were there on the same level and they were the children of node one right so for node on or also let's say there are no children so we are not going to proceed in this loop and we're going to add this current dot well that is nothing but four to the uh to the level right so now we are remaining let's say we are remaining with just these two um two notes only so this is how we're gonna add them as well so let's say they are on level three so we will be having six seven okay we'll be having let me write here six seven right and so uh here you can see we are adding this also right we are adding this level to our res so first this level when uh our node was what one so it got added right and then when the level was two where the elements were two three four it got added and then for level three the elements were the nodes were six seven right it got added right so we're gonna return this res and that's what we have to do right so it was you can see this was the similar to that one only that we did for binary fields that's the thing was that there we were having this left and right and that's how we were exploring right so the i have provided the code in the description in case you want to refer it but i believe that most of you will be able to quote it by yourself so code it by yourself and just check your answer whether you are able to solve or not so that's all for my side thank you so much for watching everyone bye
|
N-ary Tree Level Order Traversal
|
n-ary-tree-level-order-traversal
|
Given an n-ary tree, return the _level order_ traversal of its nodes' values.
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[\[1\],\[3,2,4\],\[5,6\]\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[\[1\],\[2,3,4,5\],\[6,7,8,9,10\],\[11,12,13\],\[14\]\]
**Constraints:**
* The height of the n-ary tree is less than or equal to `1000`
* The total number of nodes is between `[0, 104]`
| null | null |
Medium
| null |
129 |
so hello everyone i am straight i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product based company so let's start with the problem let's look at this problem so it says sum root to leaf numbers okay so we have been given a root of a binary tree okay so it's a medium level problem so we will try to solve it with recursion as we try to do most problems of binary tree based on recursion so we will try to do this as well we need to return the total number of root to leaf numbers okay so this is let's say a binary tree and we need to find the all the paths some from root to leaf okay so if we'll see no if we will see this binary is 3 so it is 0 2 and 3 so it is 1 into 10 plus 2 plus 1 into 10 plus 3 this is 12 this is 13 and we add both of them that results as 25 okay so this is the tree so simple recursion if we try to think of we will try to call this part and add it to our sum correct sum will be what sum is equals to sum into 10 plus root of value whatever it is and then we will just uh call it okay so first we will calculate values then we will call that is the one thing that we need to run because that will only because for this value we need to multiply it by 10 okay so let's try to code this and it will give you a better insight i'll just pass in one more variable that is in sum okay that is into sum is equals to zero and the first what in recursion we do we write the base is base cases not equal to three we return null correct now what i need to do i need to calculate the sum correct tool if we have reached the leaf then i'll return the sum else what i'll just call some numbers root of left comma sum plus i'll just copy it to this side this will be right so this is the total recursive code let's try to run it i'll just remove that so it got accepted i was we should we cannot do the ampersand thing here okay so it got accepted uh and yes so we can just try some more problems based on the similar concept like these okay try it for the enteratory and it should this logic will work fine okay thank you so much you
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
940 |
hey everybody this is Larry it's November 6th or well it is number six here Daylight Saving is kind of weird for me so yeah uh today we're going to do a bonus question that I haven't done before hopefully so yeah hit the like button hit the Subscribe button join me in Discord let me know what you think about this poem also I'm gonna I don't know I wouldn't say a contest can you see it um okay so yeah I'm trying to name my plant so definitely give it some love uh let me know in the comments what you think you know lavies plant can be named or whatever so yeah let's do a hard one it's Sunday I have some uh whatever so yeah okay so let's spin um yeah okay good oh 940 distinct subsequence is too hard um that yeah let's get started I think this one is kind of uh n is 2000 is always a little bit tricky for python so we'll see if this actually times out but otherwise it should be okay and I forgot the mod a couple of times so let's actually do the mod foreign I mean this is a way um way uh what can I call it um I wouldn't say standard but something that comes up a lot so let's see which one this thing now I'm okay so uh oh wait I missed I thought this is the one where you have two sequences and then you count the number of whatever so that's not that um okay so this one it's but it is this is still a very old school um like not to say it is easy but it's a problem that for whatever reason used to come up on textbooks right so if you study algo you'll probably have um come across this um but so we'll see how far I get from going from first principles because I haven't seen this in a long time except for I think there was a variation on this on a Q4 maybe a year and a half ago or two years ago where like there's like a evil string like that so I think it was like distinct non-empty it was like distinct non-empty it was like distinct non-empty subsequence with a non-devo uh substring subsequence with a non-devo uh substring subsequence with a non-devo uh substring or something like that or subsequence I forget so you know so that is a little bit tricky but you know uh that's not so bad so the hard part is kind of figuring out how the um distinct part works right because for example you have any you have and characters there's always going to be two to the N for a number of subsequences um that's just how you know like every character could be in and out but then now you have to figure out the distinct part um I'm not gonna lie I do not remember quite how to you know um figure it out but like I don't remember the recurrence uh and this is something that should but let's kind of start right so I imagine I have an index but what does that index mean right so let's say we have an A um what we want to do or like what are the duplicates right I mean so also for these things you can do it both ways you could count the number of duplicates and or whatever and then subtract it from the total or you could just count them with distinct um I think this is actually one of my week I used to be very good at this particular one because um to more than two decades ago this was something that I studied in uni um as because I was in computational biology and there was some stuff that dealt with a number of distinct subsequent stuff um with dnas but that was a long time ago um so I definitely could you know but it's one of those things that you know uh it's so textful you could cheat nowadays where back then you couldn't really Google it that much that's what I mean by cheating by the way but okay so what is the recurrence here and this may take a while not gonna lie I don't remember quite how to do it so let's say ref okay let's maybe go from first principle so let's say now we have ABC um let's say we have a so okay let's say we have order a prefixes right um so that means that we have a using the first one with a B well we just have regular a b uh AC ABC right so there's four foreign okay or if we don't use the a what do we get right we get B you get C we get oh I guess this is a I mean yes but this is you know it's not useful because um you know it's just like I said two to the end so we need something a little bit more awkward so let's just say we have a b a like something like this um okay so web a which the um let's say we take this a right because there are really only two things and we're trying to figure out the recurrence and yeah um okay so then now we have a b web Aba we have a I don't know what's the best way to enumerate this is I guess we just do the okay let's just do it this way a um this is awkward right I don't know what is the best way to enumerate it ABA that's just to do it this way then um and then a b a right and then a b is not true and not just ba um so there's no one here and also a is not true right so in this case um this is all the prefixes that start using the same a what is the recurrence here right well I'm missing one actually I think there's an a yeah well maybe you've been missing more to be honest so this is going to be an actual song Just because I remember the literature but I don't remember how to attack this I do have some ideas so it's still uh whatever but this is how it looks like if you like 80 off if I haven't seen this before pretty much because it was so long ago um okay is this all there is I think I'm missing some here as well so I lie um so there's a b a no this is duped um a B I guess that's it maybe I don't even know anymore right and then I what is the idea can I take advantage of you know repeated A's right like one idea which I don't know if it works it's just an idea is that we take we do the recursion on order a stuff and then we subtract out the stuff that has um the next a does that work the reasoning being say that let's say we have um we have the a suffix right because then now what we want to subtract out is all the so can you subtract out just all the suffix A's what I'm trying to do is that okay let's say we have some uh F of a b you know something like this well what we want to do is subtract out something like F I don't even know I could draw it quite right but what we want to do is let's say this a and then because let's say we you know let's say we ignore the repeats for now we know that let's redo the function in a more uh natural way under skipping ones well we have a we have ABA a b we have ABA we have a right and all these of course by definition um let's just look at the suffix here right by definition um and the suffix here are just going to be you know empty so this is nothing uh we have a b where ba and then we have an a right so that's just these without this a right um and in that case another way to think about is that let's say you want to add an a well we can add the a from here and we can add a from here right so that means that the first instinct would already contain all these things so that would be subtract it from here then you're deduping it um I and this is going to have to you know that's an idea I don't know if this is going to end up being um uh approved by AC a little bit and then the second idea is also I mean the second thing I'm thinking of is let's say you have this um do you like it almost becomes like an inclusion exclusion thing of like okay you have this a you minus this a um do we also minus this a from here I know that this a minus this a so then we have to like you know um like I said like inclusion exclusion right so okay we'll give it a try like I said I don't know how to do this uh off my head per se so yeah I mean I'm gonna just skip the caching put um for the teaching I'm gonna use the cash we'll talk about it a little bit but I want to focus on the hard part right um if you are struggling with Dynamic program problems and I have a lot of videos where I try to do it in the way that is easier for teaching so definitely you know focus on that one but yeah foreign yeah okay so then here we have goal of index plus one that's just not using this letter Plus um where is it hmm well something like this because then both using and not using is the same but then now we just want to subtract out um something like we want to subtract out or the other ones and I don't know that just like I said um this is me exploring so yeah so this is me going go index uh um if S Sub I is equal to uh index or S of index and of course we actually want to start from index plus one and then is that the io I plus one no it's I plus one because you're assuming that you use it maybe I don't know uh let's play around with this okay the beauty of python is that you could actually write this like so quickly you know oh I forgot to uh um and it may be like minus one because we count the empty string to something so yeah uh okay well that's unfortunate that this is right actually but because if they were both wrong and off by one then it's a little bit easier um but maybe that this is just maybe I don't handle the empty string quite well or like the uh yeah let's try at least something funkier first if this is why Danny gives me confidence to think about this one a little bit this is pretty slow it shouldn't be done slow down okay so this is not even close um foreign this is just wait what oh yeah why is this one so it okay let's at least debug this one should be easier to debug at least in logic I mean I know that I could just fix it by off by one but that's not why we're debugging right um what's the first one oh there it is let's see okay so this is well I mean that's fine well I um that means that we're doubling up somewhere um maybe just part of the logic as well because my logic here is that you know we have two cases one is not using and one's using it but there's clearly some weirdness about not using it okay so let's trace this a little bit right so we're F5 right let's start with five uh let's actually have one that's five then why not what do I think I get maybe this is I um okay now it's just mobile it's still very well actually and also okay well because now you're using that one yeah I mean I think this logic is okay but well I mean obviously the logic isn't okay but I just mean like conceptually Okay so let's talk about this right so at indexes you go zero what do we have well at index is equal to four um that's just gonna well index is equal to five then this is just U goes to one um index is equal to four then it returns two because it doubles up which is it's one but that's okay because that's where the um the minus one comes from because it contains the empty string okay so that dupes it so I think in theory that's okay so indexes you go to three is where we are starting to get off the wheels because basically now you have an A you go twice of uh this one so now we have four or is equal to 4 minus um this one so then minus one so this is equals to three which is already wrong because it only has two well okay no actually this is still right because for two things um again we're adding an extra one because you know um yeah I'm not counting this quite yet um because it contains the empty string so okay so index is equal to two R is equal to well now it's six from the 3 times 2 um and then we subtract from we subtract 2 and then we subtract one so that's equal to 3 again now that's not consistent even if it's right I mean it yeah that's not right I actually don't know how I'll just unless I'm doing it wrong let's print it out real quick let me put it on this side see if that works okay just okay so this is actually what we said it was uh or what we have here kind of I mean it doesn't point five but that's okay so two three and that's what I thought that this is weird and then oh okay so we're getting a big number because this is uh two um so do we um if this did fix it I wasn't sure we needed to do it for every index or just the next index um okay wow so that is enough to solve it huh wow that is uh because that was the thing that I wasn't sure about whether like with I know about the inclusion exclusion but I wasn't sure whether that was going to keep going um and one thing that we can do here is noting that this is very expensive to kind of keep going so we can actually just pre-calculate this but let's give just pre-calculate this but let's give just pre-calculate this but let's give it some mid real quick to be honest uh let's not prematurely optimize um I might that oh okay well did I mess up on the whatever because this should be the same oh right okay fine yeah I just okay that's a silly mistake but okay I mean there's some optimizations we can do here but at the end of the day um you know index can go from zero to n and this Loop so yeah time complexity is you go to you know um a number of inputs times input per time or time per input whoops and of course they're of n inputs of and time each so o of N squared right um you could reduce this to log in you can reduce this to uh o of one so we can do that as well what's my submission time uh yeah it's kind of terrible because this is N squared as a result right let's play around with optimizing this because we have time um yeah the reason why this works and I was actually not sure about which way it was going to be um to be honest is or like we need a double count is because when you do the next one uh the next character then it already encompasses the stuff that you're already going to delete in the future something like that I don't know if I'm saying that right so um but that's basically the idea um okay that's actually optimize this um because we can and then here um let's just say we have something like this we have four um I and range of n minus one s of I is the character to doing so we have lots of this is the code to um I right yeah so that we update this but we update this last and then we have a previous array as we go to none times n and then basically you have well I guess technically it's not previous is next now right but I as you go to last sub X of I if the sub I is s of I is in last we do this um and then here then now we can just do something like if previous of index is not none then we do this yeah right someone like that uh let's give it a submit let's use the optimization right um and now we go to you know I forget where we were but now we're much faster eight percent eighty two percent I mean now it's linear time right because now this is just an all one operation so that means that this is all one and then now we have linear time linear space though I didn't explain this part very well but what we're doing is we kind of look at the old for Loop all right let me just if we look at the old photo what you're doing is you look at you're trying to find the next instance where you know given this index your current character you're just trying to find the next um next index where they match right where the characters appear um and so we just build up the table so that we can I call it previous maybe I should call it next but um but yeah it's just the next case where it shows up and then we run it backwards so that we could keep track of it yeah and this is of course linear space and this is just all of 26 space or whatever so um yeah so that's why this is the near time linear space that's pretty much it um I did solve this idea from scratch which I'm really happy about I'm actually surprised that it works I thought there was something more complicated maybe it's been a while because I this is one of those problems I'm very happy to serve even though it's I've solved this a couple of times like decades ago and the reason is because I think back in the day and I'm not gonna lie but this is just me telling a story and you know you're here hopefully this is an interesting story is that I probably learned a lot of dynamic programming through the same way that allowed you at home half right um you know you just memorize certain patterns and you know kind of figure it out and hopefully just make it a little bit better and you know back in those days um we didn't have Google we didn't have YouTube I mean we had Google a little bit but you couldn't Google for resources anyway um because no one created the websites that you could Google from really um so a lot of is from textbooks and so this one I think I probably is one of those problems that I just kind of memorized a little bit uh from two decades ago um and this time I feel proud that I actually was able to do it from scratch I did have some inkling about this subtraction thing so it wasn't totally from scratch uh to be honest but yeah so hopefully I can you know self similar problems easier in the future or something anyway um that's pretty much all I have for this one so let me know what you think um stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Distinct Subsequences II
|
fruit-into-baskets
|
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not.
**Example 1:**
**Input:** s = "abc "
**Output:** 7
**Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ".
**Example 2:**
**Input:** s = "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ".
**Example 3:**
**Input:** s = "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ".
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters.
| null |
Array,Hash Table,Sliding Window
|
Medium
| null |
1,171 |
hello everyone so I'm solving this medium level problem called remove zero some consecutive nodes from link list it's a good problem uh I did it as a part of daily problem I'm trying to solve that so let's take a look at what this question is asking us to do so given uh given the head of Link list we repeatedly delete consecutive sequences of node that sums to zero until there are no such sequences after doing so return the head of the final link list you may return any such answer okay and then it says note that in the example below all sequences are calization of list node objects so basically this head is telling us that this is the uh link list we have one 2 -3 1 right so in this question one 2 -3 1 right so in this question one 2 -3 1 right so in this question it's asking us that if you find the consecutive sequence of node that sums to zero we just have to delete those right so let's consider this first example uh so if you actually think about it this is very similar to a uh already existing lead P lead code problem called prefix sum so if you guys don't know what exactly a prefix sum is let me just describe real quickly let's assume let's not take Link list let's just assume that this is the given array so a prefix sum is a running sum on that particular index so if I say what's the prefix sum of this entire uh array we are just going to start off the first element so one over here then we'll move on to the next one and we'll keep the track of the sum so we just encountered one before that so I'll just add one to this two so it's going Become Three so up till this point we have three the sum is three now let's move on to the next element is or next number in the vector or array is -3 we already have seen the or array is -3 we already have seen the or array is -3 we already have seen the running sum is three over here at this point and then we move on to the next one so it becomes three -3 so it becomes 0er over here and then -3 so it becomes 0er over here and then -3 so it becomes 0er over here and then again the running sum is Zer at this point we'll move on to the next one we'll see three so 0 + 3 is three then we'll see three so 0 + 3 is three then we'll see three so 0 + 3 is three then we will move on to the next one where 3 + 1 is 4 so the that's the prefix so we + 1 is 4 so the that's the prefix so we + 1 is 4 so the that's the prefix so we have to use very similar logic over here as well as soon as the running sum or a prefix sum is equals to zero we are going to delete those uh nodes from this uh link list right so let's start over again keeping prefix sum in mind so let's the prefix sum at this point is just one we'll add two to it so it's three then we'll move on to the next one so 3 -3 is 0 so now we know next one so 3 -3 is 0 so now we know next one so 3 -3 is 0 so now we know that we have encounted zero so the running or cons as it says consecutive sequence of nodes is zero so we have already encountered 1 + 2 is 3 -3 is 0 already encountered 1 + 2 is 3 -3 is 0 already encountered 1 + 2 is 3 -3 is 0 so at this point it's zero right so we'll just remove these elements what is it left we just have three and one so that's why the answer is just three and one right and then it says answer one 12 one is also accepted one two one okay yeah one 2 one is just take this window in this window the uh prefix sum is zero right so let me discuss what strategy I'm going to use over here so since for prefix sum I'll be using two pointer essentially the reason I use two pointer or just keep track of two indices so that as I move forward I'll just keep track of the window or the running sum of that window that over here this window has zero so I'm just going to keep track of this or as I told initially that the sum of this three first three uh element of array whatever you want to say over here it's link list so the first three nodes of the link list sums to zero that's why either it's 31 or 1 121 is also accepted solution okay let's move on to the second example over here let's do the same thing over here uh the first element is one so uh let's take a r running sum so 1 + 2 3 let's take a r running sum so 1 + 2 3 let's take a r running sum so 1 + 2 3 + 3 6 + 3 6 + 3 6 63 is 3 and 3 + 4 is 7 right so in this 63 is 3 and 3 + 4 is 7 right so in this 63 is 3 and 3 + 4 is 7 right so in this window starting from this till the end we haven't encountered zero yet so what we are going to do is we are going to start with the smaller window now since we have already seen in this bigger window we did not find any uh zero let's move on to the smaller window so let's consider from starting from 2 so 2 + 3 consider from starting from 2 so 2 + 3 consider from starting from 2 so 2 + 3 is 6 oh 2 + 3 is 5 - 3 is 2 and 2 + is 6 oh 2 + 3 is 5 - 3 is 2 and 2 + is 6 oh 2 + 3 is 5 - 3 is 2 and 2 + 4 is 6 right so we did not really find zero even in this window so let's move on to the um next element and let's start off from three this time so 3 -3 start off from three this time so 3 -3 start off from three this time so 3 -3 is uh zero so we uncounted zero over here right so now if we remove these two elements what we are left with we are just left with 1 2 and four and that's the answer okay let's try it try our algorithm on the third one as well let's start off from the first element over here it's one so the running sum over here is like until this uh index is one then we move on to the next one so 1 + 2 then we move on to the next one so 1 + 2 then we move on to the next one so 1 + 2 is 3 + 3 is 6 uh - 3 is 3 - 2 is 3 + 3 is 6 uh - 3 is 3 - 2 is 3 + 3 is 6 uh - 3 is 3 - 2 is uh 1 so we haven't encountered zero yet so let's move on and now start from 2 so 2 + 3 is 5 - 3 is 2 - 2 is uh zero 2 + 3 is 5 - 3 is 2 - 2 is uh zero 2 + 3 is 5 - 3 is 2 - 2 is uh zero right so now we have encountered zero so we have to delete all of the element which exist in this uh window so the only element left is one right so you kind of you kind you will get the hang of the problem right like as I explained once you go and watch the video again you will understand what I'm doing is I'm starting off with the first uh first node of the link list I'm keep on going I'll keep on iterating in that link list as soon as I hit zero I'm just going to delete the entire node which exists in that window if not I'll just start it from or like make it even further shorter so that I can look in a smaller window and I'll keep on doing it until the end of the uh end of the node right so let me formally write what I'm trying to uh say over here so let's start off with uh okay so I'm going to use something called Sentinel node what this means is that ENT creating a dumy node so that I can keep track of my link list so let's create a sentinel node which would be just creating a new node list star and let's just call it as new head so that's a new head and we have to create a new link list a new node which will start with zero and the other uh the next element should be head so that what's going on is that I'm just creating a new node so just think of it as creating a new link list where the heads or the new head starts with zero and then it connects with this one and now I'm going to just iterate with the existing uh Stu or the new head so let's just call it as new head so now I'm what I'm doing is I'm creating a uh this I'm not creating exactly a new node what I'm doing is I'm creating a reference to a list node or a pointer to a list note which will um which is ref referencing a new head right so it's this pointer called start is pointing at new head right so once we have that what I'm going to do is okay I'll write a while loop which will start from which will have a condition where start shouldn't be null so keep on running it until it reaches the null pointer and inside that I'll create another pointer as I told initially right I'll be using two pointer over here or two yeah two pointer just to keep track of the start of the window and end is the end of the window so should point at start next right we're going to point it to the next because if I'm starting with one I don't want to start again like point the end at one right because then both of the point are at is at the same position I don't want that if start is at one the end should start with two so that we can have the running sum so let's start with this and also we need to have a variable which will keep track of our the sum so let's just call it prefix s and just initialize it zero once we have that we will right we'll have another while loop which will what the another while loop is necessary because we are keeping track like as I showed right in this example if we just start from here end on four we don't get zero so we need to again move on the second point and same this end what this uh nested for Loop or V Loop does is that it keeps on increasing the pointer to the next one so this would be very similar to the previous uh while loop it but now this time it should iterate until it reaches a null pointer right and then we'll check or then I'll just add the prefix sum first or just update the prefix sum it would be have the already existing prefix sum and the end uh value which exist in the end pointer and then we'll check if prefix sum is equals to zero that means we have come to a uh we have uh arrived to a position where that window or sums up to be zero right in this case right over here these cases where the window is zero now what we need to do is we need to delete so for delete there is this operation for example if the start is at two we'll know that start is two and end is -3 what we need to do is now join two is -3 what we need to do is now join two is -3 what we need to do is now join two with four so the only way to do is we need to point the starts next node To The Ends next node so that's uh that's going to be the new uh connection right start do next or start uh pointing next is and next oh next all right so once we arrive at this position at two uh just think of two being the start at the start pointer and then what we need to do is we need to make this connection from 2 to 1 so start next and end is over here at three right because -3 and 3 is zero at three right because -3 and 3 is zero at three right because -3 and 3 is zero so end is over here then ends next we need to connect starts next to the end next this is what we do and since we are uh in this while loop we also have to update the end so end equals to end next so that it trevers to the next one so end next and we have to do the same thing with the start over here so start equals to. next and once we have that we will be returning new head next because as you can remember it's a sentinel node right it's a dummy node which I'm just using to keep track so I'll be returning the dummy's next node because that will head towards the new uh Point towards the new head so that should new Heads next and that's the reason I was using a d node so that I already have a track of where my um new head would be it would be new head next let's try to run this okay so all the three cases get paed let me submit it all right successfully Summits so uh again uh let me give you a review quickly so what we did is this uh is something which if it's new to you might uh it would be helpful to understand why I'm using a sentinent node or dummy node because I want to keep track I don't want to lose because start and end pointers are moving they are traversing so we don't really how would you know that uh now what the new link list would be right so we need to keep track and this is the best way to go about it just create a dummy node and then point that dummy node's next node to the head and then at the end we'll just return uh new head next uh so the only trick is uh while traving you need to keep track of start next and end next this creating a new connection from one to one this two next should be ends next right because end is over here at three and start is over here so starts next is in next and that's basically uh the main logic that we need to create connection as soon as the prefix sum becomes zero and the iteration is simple right both the pointers start and end goes till the end of the link list and then as soon as we hit the end of the link list it just aborts or it comes out of the while loop and then uh we return the new link list uh really nice question so it will give you a good idea of how to create connections when you have to delete and that's the benefit of using link list right link list data structure is pretty good because in constant time you can remove the elements from it uh yeah so that's pretty much today's question uh let me know if you have any uh other doubts I'll uh look at my comment section so you guys can put the U put any question you have in comment section and then I'll take a look all right thanks a lot for watching the video I'll see you in the next one
|
Remove Zero Sum Consecutive Nodes from Linked List
|
shortest-path-in-binary-matrix
|
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`.
|
Do a breadth first search to find the shortest path.
|
Array,Breadth-First Search,Matrix
|
Medium
| null |
62 |
hey guys it's off by one here and today we're going to be solving unique pads in this problem we're told that there's a robot on an M by n grid and the robot is initially located on the top left corner like you can see here and they want the robot to try and move to the bottom right corner where it says finish and they're telling us that the robot can move only down or to the right at any point so we can't move up and can't move to the left so given two integers M and N they want us to return the number of possible unique paths that the robot can take to reach the finish line so let's do this example here since we already know our expected output should be 28. so how many unique paths can we take to get to this square right here well we know that you can only go right so that would be one unique path but what about over here well this Square here is also the same you can only go down so that's one unique path okay well what about this Square here now well you can either go down and then right or you can go right and then down so that's two unique pads okay well what about this Square here this second Square we can only go to the right so that means there's still only one unique path and it's actually the case for the whole first row so we can just set all of these to one because like I said you can only move to the right in the scenario so there's only one way to get to all of these squares and same thing goes for this column here we can only move down so there's only one unique path to get to this bottom left Square so we can see that this whole grid on the first row in the First Column is going to be just one unique path so now that we know that let's try and calculate this Square here how many unique paths can we take well we can go to the right and then we can go down to reach this Square so that's one path we can go to the right down and then to the right again so that's now two paths or we can go down to the right and then to the right so that's three paths and I'm sure some of you see it already there is a pattern here so for example for this 2 here we can see that if we add the number of unique paths above it and the number of unique paths to the left we can get two and same thing goes for this three here if we add the unique path to the left and the unique paths above you'll get three so let's verify that so for this Square here we would expect a 3 because 2 plus 1 would be equal to three so let's try that so like I said we're expecting a total of three unique paths to get to the square so let's count them we can go down and then to the right that's one path we can go down to the right and then down that's two paths or we can go to the right and then down and down again so that is three paths so we can see that this pattern does work so let's follow this pattern and fill out the rest of this grid and see if we get 28 over here so like I said let's say we're looking at this Square here then all we would do is add the number above it and the number to the left of it and that will give us the number of unique paths to get to this Square so three plus three would be six and now let's go through the rest of the grid so for this Square here we would add three and one and that gives us four for this Square here we would get 10 because 6 plus 4 is 10. and now we do this Square this is five this square is six this square is seven now for this Square we're going to do 10 plus 5 that's 15 plus 6 that's 21 and 21 plus 7 does give us 28. so that checks out so now we can use this pattern to develop our code so here I've drawn another example where m is equal to 2 and M is equal to 3. so the array is going to be of size n going that way and of size m going this way so to start we want to do is set this whole first row and First Column just equal to one because we know there's only one unique path to get to all of these and now let's just write our algorithm well we know that we want to set the current result equal to the result above plus the results to the left so if we just fill in this array here one plus one this would be two and then two plus one this would be three and we would return this index at the end so we want to return result at the bottom right index and also we want to have some for Loops so we want to run it for n and for m so 4 n times we also want to Nest a for Loop here for M times and that should have fill in our array and at the end we just returned our bottom right index so now we can go over the complexities so our time complexity would be o of n times M the reason we do that is because we have these nested for Loops that are of size n and M and for space we're going to have o of n times M as well because our array is a 2d array of size n by m but actually this problem can be solved using just o event space and I'll show you how to do that in the code so let's get into it to start I'm going to initialize a variable and we're going to call it row above and this is going to be set to all ones for a size n and the reason I named it row above is because in this code this is what this variable is going to be used for from here we just want to iterate for I range of M minus one the reason we're doing n minus 1 is because the First Column is already going to be all ones so we can just skip over that and then at this point you want to make a temporary array we're going to call it current row and same thing we're going to set it to all ones for size n and from here we're going to iterate for J in range of 1 through n the reason I'm starting from 1 is because the first row is already going to be all ones and we're going all the way to the end so that's why we stop at n and then from here if you remember we want to set our current value equal to the value to the left plus the value above so let's see how do we do that so we're going to have our current row at J equal to current row at the left which is J minus one plus rho above at J and this would give us our value at the left this would give us our value above from here we just want to update our row above to be equal to our current row because in our next iteration we're going to use current row and we're going to set a two row above and then from here you can just return row above at the index n because that'll be the last index but actually should be n minus 1 because at size n that means that we will start from zero and go all the way to n minus one and that should work so as you can see this code is pretty efficient and now I'll go through the code manually so for this problem here I'm going to make n equals 3 and M equals 2 just to keep it short and to start we want to initialize our row above to have all ones for a size n as you can see this row above array is size n and they're all limits nice to once so we can check that off and now we want to do for I in range of n minus 1. so m is 2 so n minus 1 would be one so we only want to do one iteration for this for Loop and now we want to initialize our current row which I've already done here so we can just check that off and now we want to do for J in range starting from one all the way to n so we're going to start from this first index and go all the way to the last index and what we want to do is Set current row at J which is currently one equal to current J current row at J minus 1 which will be the left plus row above at J so let's see current row at J minus 1 that would be this number here plus row above at J that would be this number here so we're going to update this to A2 and now we go through our next iteration where J is going to be equal to 2. so current row at 2 is going to be equal to current row at J minus 1 which is 2 here plus row above at J which is 1. so we're going to set current row at J equal to 3 because 2 plus 1 is 3. and at the end we just want to update our row above to be equal to our current row so at zero it's still one at this first Index this is going to be updated to 2 and the second index is going to be updated to 3. and then at the end we just return row above at n minus one so that would be this index here because n is three so that would give the second index and that's correct if this video helping in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
|
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
|
746 |
hi guys welcome to tech geek so today the question for the daily lead foot challenge problem was minimum cost climbing stairs uh that's an easy one basically it's a the same as jumping or climbing stairs or jumping the wall so that's what the series comes up with it's more of a dp problem if you think of it in a very interesting way and it's quite a beginner level question so give time to understand the approach try to go the answers rather than going with the code itself before beginning i'd like to request you all to please like share and subscribe to my channel for the batch of 2023 i have shared two upcoming placement sessions that are going to happen one is the newest house of code and second one is cisco hiring do see that's quite good for you it would be beneficial for you go register yourself give yourself a chance and if in case you need any help with the placements aoa preparations interview preparations do let me know in the comments with the company name i'll come up with the genuine questions and even the excel sheet which i have prepared for two companies i'll be preparing it for more for group people now let's see what the question has okay the question says will be given an integer array cost where positive i is the cost of i step on staircase okay so the i step will take that would be the cost once you pay the cost you can either climb one or two steps so whenever let's say you have these many stairs let's say you have six stairs okay initially obviously the person would be on the first one okay first the cost was something x you paid this x now it's up to you to climb to the first or second so how you will decide to go with which one that will basically depend on the cost of these two so you will take the minimum cost because you have to pay let's say this was one this was two so obviously you will just climb the climb one step one because you have to pay lesser amount again now you are here you can move here and here again you will compare the lesser amount so let's say the single s amount was two steps away same here now here you will check for the lesser amount let's say one is zero other is one so your time zero and obviously for the last three can work that's what you have to do you have to check for the if you are at if index you have to check for the minimum of i plus 1 and i plus 2 that's basically what they want to say by climbing this you can start from index 0 or with the step index one now this is also upon us we have to compare these two okay let's say this was also zero initially for our case that's why we began uh if in case this was two and one then we will directly begin from first one you have to find the minimum cost of reaching the top of the flow you have to reach here itself this point what is the minimum cost you have been given two examples 10 15 20 again see here if we check if we take 10 then we have to pay 20 also that's 30 but if you directly pay 15 then obviously won't require it so that's what has to be understood okay let's see this question now okay we have 10 we have 15 and we have 12 we have to reach the top of the strength so why not to begin an opposite direction we'll consider we have reached and we are going back and checking what is the cost right that's we'll do that means we'll traverse the array from back to form okay we can take two steps either one step or we can take two steps okay and what is the current step that we need so these are the three variables that we will introduce step one step two and current step now current step would be the cost of this plus the minimum of these two steps because taking the two steps we need to check which is minimum so initially the minimum cost is zero 20 plus zero is 20 now on moving backward that's traversing the next element what we'll do before that we'll make s1 equal to s2 so value of s2 will move here again 0 is same and value of current step will move here so this becomes okay now current step will be positive 5 15 plus minimum of these two minimum is 0 again so this becomes 15 do the same thing this becomes 20 this becomes 15 again coming to the next reversal this becomes 10 plus minimum of this is 50 so this becomes 25 now no more traversals we will stop for the current step but again the switching has to be done first this becomes 15 and this becomes 25 okay the result will be the minimum of the two steps so minimum is 15 so our answer is this is order of n solution now let's see what the code is that's simple take step one zero step two zero backward direction current step is cost of i plus minimum of step one and step two step one will point you step two step toward five one step the minimum would be stefan step that's order of n solution if in case you have any queries do let me know before that keep following tech geek let me know in the comment box if there are any queries thank you
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
76 |
so in this video we are going to solve one very common and interesting problem minimum window substring so problem is that you have given the two is doing SNP and you have to find out if all the characters even it is the duplic duplicate are present in this string or not and you have to find out that Windows means if you see here A B C so you have to find out the ABC so if you see a is here and D is here then C is here right so you can consider this is the one window in that window you all the characters are there ABC that might be duplicate if he T would have the aabc then you have to find out the two aabc then you might be window the bigger here right in the case of a ABC but in the case of ABC this is the window you have to find out so that is this is called the windows but also you have to find out the minimum window size right so if you see other possibilities are there if you see from here foreign this is another possibility another window is here in this window also you can see all the characters a b c but if you see the first window size was the one two three four five six but if you see that this window one two three four so obvious this green color window is the Eraser size so you have to return the this window bcpa and if you cannot find out this uh string here you can return the empty one so this is the problem you have to solve it right so if you see the under case uh if this is the S is equal to a and t is equal to a yes you can see this is the find out and you can return the 1A but in the case of the T is also a so you can return the a if suppose this is the D here or p q so this D is not here a d is not here so you can return the empty one so how you are going to solve this right so to understand that we make one the format of the system for the better understanding so I just make in the Box for the easy understanding and let me give the index for the each character so for this array this is the index so uh we will take the advantage of the two pointer array so when you solve the most of the windows substring problem you can uh we took the approach for the two point website so it will help you to solve any string window plugins so two pointer means I will take the I and I will take the G so we move the two pointers to trace two scan this is doing as well so how you can do that so the easiest way you might have many other Solutions but what I have understand the easiest way is that take one map this is a map in map you have the key and the value right so in the key side give all the characters what is you are looking for that so what you have to do you have to iterate this string T make each character into the math and see how many occurrence are there so a is 1 B is 1 so we have the A1 so suppose if this string would be like this then a number should be the two right so that first you have to make one map and then we'll be proceed here right so once you get it while making this is the map because the purpose of that map we need means this is my requirement we need the A1 B1 and the C1 number in the Mainstay right so once you're getting we reduce the number how you can do that and make the contact also and suppose this is the m length is the 10 and this is the end event is the 3 right and make the one contact also foreign now what you have to do that you move this J M right so your Loop will be there J you have to move that less than the m means q9 here right and now this is there is no job for the system so if you communicate between these two this so for the time being if you want you can remove this there is no use of this one right now except the length was the 3 the event was the 3 that you keep in mind so I will always communicate these two parts here map and S so take the first p is p here no problem then make the J here right now J was here so this P was here no so no move the J at one index one now if you see this J is here yes here this a is here what is the number one so if this value this map get what are the value we are looking in the case of here a if greater than 0 means I need that number if that is the case means we find out the A and also I need number one which I need the a in that case what you have to do you have to increment the contact so in this case this contact becomes the one and also update the map with minus means it was the one now it become the zero two things you have to do so now the counter is the one and NJ is here now move the G nor J will come here is n there no again move the J p is here no again move the G Q is here in map no move the G not busy a Jeepers pipe no B is there so B is there this B value is more than zero yes if this is a condition actually yes if the value is more than zero then content increment by one now contact become the 2 and update this number minus 1 so it become the zero right again J move here this is here urgent yes she is urgent this value is greater than 0 yes so increment the counter and update the map mine sorry it was the one and now so now you can see that counter Theory means what are the need was there everything we got it and the Contour 3 mission of the P size was the N was the theory so we got all the characters in The String so the moment you got the character means your job is half done means if you see here J and also uh always update the J here right so now your G is here so now if you see I is equal to at the 0 right now is go to 0 so what is the size of that windows so size of window is J minus I so J minus so if you see the 7 minus 0 this is your window size right so one two three four five six seven so this is your window size but you have to optimize that as I explain you this window is this one but other possibilities are there to optimize even though if you see this window what we got from here to here right this window you got it but you can remove this P also I can reduce the by the we can minimize the window size so p is not required for those kind of things I will take the help of the eye so now let it be the J here stop it the moment you the condition that n is the number of the searching P size right T was the a b c the moment you got all the required character new string so the moment you contact become the end the moment you con or the value is equal to zero and you achieve all this number what you are looking for that then you have to move the G so in this case what you have to do first and foremost when the contact is equal to N means you already find out of the character so you have to keep the minimum value that J is equal to minus I am getting minimum because I have to return that characters for that calculations ib2 and also I will do the starting point is called to I so right now our starting point is u so when I return the methods what is the windows so I will return from G from SP to minimum so SP is equal to 0 to the minimum is the saver so that have to return for that purpose you have to keep this value here right so that minimum and I will do that right now what you have to do you start the scanning here so p is p means if s i here I was saying the s j here as I this s i is project in the map this is the p is present in the window or the agenda map it is not perfect so nothing I will move it forward now your eyes here is the one right you can see this a is here so the moment you get the here first what you have to do you have to increment when I was moving the J I was making that document when I removed the I will increment the finding values so make the A1 means here miss the same case if map dot gate s I is greater than zero this is the one condition and before that what I have to do you have to make the update plus that time I was doing the minus this time and plus keep in mind in the first time we are moving the J I was increment the contact and then update the map here in the case of eye movement I will update the map and then check the conditions so the moment you make the one this condition is satisfied the moment this condition is satisfied do the counter minus so now this counter become the true so the moment it is the one here it is saying that okay you have already one got a window but if you can get the one more a the possibilities that are there we can minimize the window that's why this is the asking if you can find out one more a okay so now your contact becomes the two so this condition will be not satisfied you can again go up again move the J so now my dear was here so p is here no then your J is here a is here yes a is here so what you have to do you have and we have used more than zero more than 0 so what you have to do update the counter and update the map it becomes again jio so now you can see again your contact becomes 3 this condition is satisfied let us start again so that time I was the one right again move the I now because this condition is satisfied so you have to move the I you have to stop the J and you have to move the I so n is matching no need to do anything p is matching no Q is matching no B is matching the moment is B is matching so what you have to do you have to update the minimum means right now I is equal to 5 and J that time was the 8 right so you have to that might be G is updated here so that might be come here right so 9 minus 5 we can keep the four minimum size and now starting point is five so when you make the new window that window will start from here that's why I will store this SP value that will see in the code now check this one so B is matching what I will do I will update the map increment this become the one this condition is also satisfied it is more than the jio so what you have to do you have to make the counter minus so this counter becomes the two now again move the this context become to this condition is not satisfied again move the J so now my JB which here and this condition is now it become the false we will stop here so if you see that your I become the here and minimum was the I minus J from that time itself so this was the minimum so in this is your window you can find out how it works actually you have to take the two pointer approach and you can get it so I will show in the code how it works but one more thing I want to say instead of the map we have the some better option to do the same thing how you do that all right don't take the map because again map operations we take to some complexity instead of the map take one array give this something name map area something size of the 120 8 because we have all the characters of the ASCII Parry 128 or the ABCD and I will take the advantage of the index with the character so if you see in the T we have the ABC right and index if you see two three four 65 67 68 67 right starting we keep index by default it will be the 0 foreign 66 make the one 67 make the one so I will take the advantage of the uh index of this array Institute of the map so it will make your quality bit EG so let us jump into the code and see how it works right or I would say take some another example and drive on whether it is working or not so first what we will do take the length so M as Dot event and for the teach to event analysis that take one map this is the array of the map right so we can do that int and height event will be the this much right and in the map we have to update with all the indexes of the tree right so go for the and here what we have to do we have to go the map in the map take the P Dot character it I means for the each character of the T in the case of the our example this is the APC if that is there just increment that so starting time it would be initialized by the jio and we can increment by the one so in this case or the 65 66 67 become the one so once you create the map then what you have to do take some variables that might be useful like counter make the jio I will take I also 0 take the j keep on the jio and you can also be starting the minimum value right so find out the minimum initial you keep the maximum value and then we can uh check the condition this is how we can find out the minimum value right so integer Max for you and last we have to check the starting point also I will be starting minus 1 right so now is everything fine now let me start the above J pointer so J we have to run 2 m right and what it says so first we check if in that man in that map if s dot character now no need to follow the T character I have to take the uh s character so if the first character is starting from the J if that characters is present and his value is greater than 0 right then we have to increment the contact after increment the counter what you have to do we have to also update the map right so this map you have to update so you have to take this map minus and also you have to make the J plus right you have to always do that so that would be that is way we can increment the J and make all the content increment the moment we find out all the values so again you have to check if you can find out Miss the contract become n so find out everything so we have to optimize that so check if counter become the end so now this is the time to take the initial value minimum value and start from the G right so what we have to do here so just taking the minimum value this is code for the minimum value if your J minus I is less than minimum this is how we can take the minimum value so then minimum keep the i j minus I so we can this one and also we have to keep the I value for making the windows right and now if I check that if a is present in the map right so before that what we have to do you have to increment the map value right if you can check a is matching so go and make the increment by the one right so s dot character this time I right if this is the present then make the increment and then check if the value is greater than 0 right then only you have to uh make the counter again plus right so you counter minus so check if this value is greater than 0 if this is the case then do the counter minus right so what you have in the minus so again we have the possibilities to run the J index to find out if any such element is there or not and of course we have to increment the I right so this is the code and from here what we have to return s dot substring starting from s i because SI is the starting point then s i plus minimum right that register you have to return let me check whether it's working or not then if you again any problem you can fix that so you have to make this is the array right mistake here it is the ashes small you have to make this small here it is working fine but in the case if it is not match right so suppose if it is not matched then you should return the empty suppose if I make the Q here it is not matching then I should return the empty so that part we have not covered here right so instead of make this statement not this statement so what I will do conditions if that minus one then you have to return the empty otherwise you have to return these things so if you do this it should work fine yeah so for time being change the test cases check one more time it is working fine and then you can further optimize the code so just you can concise the code here so if you see this or that it is not required instead of that we can use the single line code here how we can do if okay map means take this code complete here yeah if this one and we have to minus also right because this is minus here if it is greater than 0 and then also we are doing the jet plus then just what you have to do the contactless plus so instead of this three line you can use the one Vine so it is up to you convenient right I'm just making the comment here so it will reduce the code and same way what we are doing here first you are checking then document the map right but in this case here we have increment then checking the map so also these three lines you can remove in one line so what you have to do just copy this part so first increment and then this increment and the contact plus first you also no need to distributes so you can just minimize the code here now let me again check it is working fine or not so this is the full code that we you're working fine so this is the full code here so yeah so if you can evaluate remove this it should work fine so this is the whole code right let me submit this code it accepted right so thank you very much if you like this video please don't forget to comment or the Subscribe or uh discuss with your friend thank you very much
|
Minimum Window Substring
|
minimum-window-substring
|
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
|
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer.
|
Hash Table,String,Sliding Window
|
Hard
|
30,209,239,567,632,727
|
930 |
hey guys welcome to a new video in today's video we're going to look at lead code problem and the problem's name is binary subarrays with sum so in this question we given a binary array called nums and we also given an integer goal and our task is to return the number of non-entry subarrays with a sum equal to non-entry subarrays with a sum equal to non-entry subarrays with a sum equal to goal and by definition a subarray is contigous part of the array given to us so let's take the first example given to us here as you can see this is the input given to us and the goal is to which is the sum so we have to find sub arrays within this nums array with sum up to two so here you can identify one array so one comma 0a 1 is a subarray whose sum is equal to 2 and I can see one more subarray 1 0 here also the sum is equal to 2 and there's one subarray here 0 1 whose sum is also equal to 2 and there is one more subarray 1 0 1 whose sum is also equal to 2 so total there are four subar whose sum is equal to two which is the goal so four will be your output so here as you can see the main point is that you have to calculate the sum of every subarray so the Brute Force approach will be that you find all the subarrays and you find the sum of every subar and check if it is equal to go so that will take a Time complexity of O of n Cube because o of n s is for finding the subar and O of n to find the sum of that subar so total o of n Cub you can make it to Big of O of n squ by finding out the sum whenever you're forming the subar but these two are Brute Force approaches and these will fair for longer rums Aras so here we have to calculate the sum of every subarray right and check that sum with a goal so you can implement it using prefix sum because you iterate through the input array and calculate the prefix sum for every index so let's see what is the prefix sum for this so let's calculate the prefix sum we start with the first index so here the sum is equal to 1 and here the sum is also equal to 1 here the sum is equal to 2 and here the sum is equal to 3 and you might just see that whenever the prefix sum is equal to two you increment count there are two prefix sums 2 which is equal to the goal so you might think the answer is two but here you see that there is a three which means that if the current sum minus the goal so current sum is three here right so 3 minus goal is 2 which is equal to 1 we have to check if we encountered a prefix sum 1 earlier so one is appearing two times right so it means when you move the prefix sum so prefix sum will always start from the beginning Index right so here as you can see we proceed from further and keep adding the cumulative sum but if we want to calculate this prefix sum from here even then you might find probable answers so here you can see you're finding two more Sub arras 0 1 and 1 so we have to keep track of the prefix sum so not just finding the prefix sum we have to store them in a hashmap and check if this sum minus goal is already present inside the map so this two will be added to this two and you get the total count as four which is the expected output now let's do a dry run for this example by using a hash map so I create a map so the key is going to be the prefix Su and the value is going to be the frequency of prefix sum how many times that prefix sum is occurring so let's iterate through the array we start with this element and keep track of the sum so I create a variable sum which is initially zero and now I add this element sum is equal to 1 we check if this one is equal to goal no so count will remain zero so we keep track of the variable count which is initially zero and this count will be returned as the output and now add this value one which is the prefix sum and now add this value one into the map and it's occurring one time and now go further it is pointing to zero so add Zer to the sum is still one so check if this prefix some one is present inside the map yes so increment its value so the prefix sum 1 has appeared two times until now and now we move forward and the value is one so add it and the sum becomes two and the sum is two which is equal to the goal so it means we found one pair so increment the count by one now check if this sum is present inside the map no so add it and set its frequency to one so it means the prefix sum 2 has occurred once until now we add zero to the sum and the sum becomes two and again this prefix sum is equal to goal so we increment the count and the count is now two check if this two is present inside the map yes it was earlier having one so add one into it and now the value becomes two now move further we add one into the sum and the sum becomes three and now since the sum is three check if sum minus goal so sum is three and goal is 2 1 check if this one is present inside the map yes one is present inside the map and it's occurring two times so add this count two add its value into the count so two will be added and you get four so here it means we were calculating the prefix sum from the beginning right so from this point until this point we calculate the prefix sum which is currently 3 it doesn't mean that since 3 is not equal to 2 there is no sub array which is equ equal to the goal because this is a binary subarray these zero values will change the equation so it means if we want to move the prefix some value further so if we move this further here also we are finding binary sub arrays so this is one subar and this is one subar which is satisfying the condition so that is why we maintain this map and from this map we are checking this if some minus goal is present inside the map it means using these values you can find binary Subarus which sums up to goal and that value is this two which is occurring two times so we add two here and the count becomes four which is expected here so you do this check for every iteration I only showed you whenever sum is greater than uh goal but you place it inside the for Loop so that you don't have to do special checks now let's take a look at the code so here as you can see first we're creating the map and creating a variable count and creating a variable sum we iterating through the input array using a for each Loop so we iterate one value at a time and keep adding the sum we check if the sum is equal to goal only then we increment count but also if sum minus goal is already present inside the map then we get that value and add it into the count like in the last case so these two will come from this equation and before starting a new iteration we are adding that uh prefix sum into the map and keep incrementing it value whenever you are finding that value prefix sum already present inside the map and once you come out of the for Loop you return whatever is present inside the value count has the value four for this example so four will be returned as output so the time complexity of this approach is O of n because you iterating through the input array nums here and the space complexity is also of n because you're using a hash map to store the prefix Su and its count so the space complexity is also of n where n is the length of the namari now let's quickly take a look at the TWP pointer approach I'll show you how we can solve this using o of one space so here you notice that we have to compare the sum of the current uh subarray so how do you take sub Aras you take two pointers right so let's say this is the start pointer and this is the end pointer and you keep incrementing the values so here you can convert this question that instead of finding for subarrays which are exactly equal to the sum goal you can find sub arrays whose sum is atmost goal and you can also find sum which is equal to atmost goal minus one and once you find this if you subtract this you will get subar whose sum is exactly equal to goal and now rest of it is same you keep moving the start pointer and end pointer and keep adding these two values so let's take a look at the code and then see how the code is working so here as you can see first we are calling the helper function on goal and we are subtracting it from goal minus one so this will give you the count of subar with some at most goal minus one and this will give you the count of subar with some at most goal and when you subtract that you will get count of sub Ares exactly equal to goal and this means that if goal is less than zero you can directly return Zer as the output because the input contains only zeros and ones and you can't get a negative value from goal so there will be zero Subarus if goal is negative and now again we're keeping track of count and sum and these are the two pointers start and end sliding window and start pointer will iterate until it reaches the end and we keep adding the value at start so initially start and end both are here we keep adding this value into the sum so first we have to check when goal is equal to 2 and we have to check when goal is equal to 1 because we are doing goal minus 1 2 so these two values are important and we are performing sliding window here we keep adding the value at start into sum and when the sum is greater than goal we subtract the value at end and N keeps on going forward so this is important here start minus n + 1 we have to add it to its minus n + 1 we have to add it to its minus n + 1 we have to add it to its previous count so initially start and end are here right so 0 - 0 + 1 will end are here right so 0 - 0 + 1 will end are here right so 0 - 0 + 1 will give you 1 so you add 1 into the count so first we have are doing when goal is equal to 2 so count is equal to 1 now and now start will go forward in the next iteration so now start is here now again we have to do start - n + 1 so again we have to do start - n + 1 so again we have to do start - n + 1 so start is 1 - 0 + 1 is equal to 2 so we start is 1 - 0 + 1 is equal to 2 so we start is 1 - 0 + 1 is equal to 2 so we add 2 and the total count becomes three so it means that so you still are accessing these two elements only but how are you getting count three so the count three represents one this subarray zero the single subarray and combine 1 and zero so all these three barriers individually are having sum at most two so similarly you do all the values here and you repeat the same process when goal is equal to one and you subtract the two and whatever is present will be return returned as the out so do a try run for this test case and you'll know how the code is working so this is basically the idea here so the time complexity of this approach is O of n because you iterating through the entire array using sliding window and the space complexity is constant o of one because you're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
|
Binary Subarrays With Sum
|
all-possible-full-binary-trees
|
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0,1\]
\[**1,0,1,0**,1\]
\[1,**0,1,0,1**\]
\[1,0,**1,0,1**\]
**Example 2:**
**Input:** nums = \[0,0,0,0,0\], goal = 0
**Output:** 15
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `nums[i]` is either `0` or `1`.
* `0 <= goal <= nums.length`
| null |
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
|
Medium
| null |
1,970 |
hello and welcome to another Elite code video today we're going to be doing the final dream problem of the day for June 30th last day when you can still cross um and we're actually going to go over the solution that I found that I did not come up with myself I will briefly talk about the one that I came up with myself but I think the one that I found in red is um more interesting so we're going to talk about that so in this problem you are given a grid and the grid has all lands and then you have this cells and so the cells just tells you at every day one of the lands turns into a water so as you can see from this example one we start with all lands and then lands are represented as zeros and then every day one of the lands turns into a water so it starts here and then in one day cell one turns into a water and so these cells are also one index so one is actually over here so this one turns into water and then the two one turns into a water which is here and then the one two turns into a water and finally the two turns into water and so what you're being asked in this question is return the last day where it's possible to walk from the top to the bottom only by walking on land cells so pretty much that means that you can go from the any cell on the top to any cell on the bottom so we could see that it shows in the picture in the first part we can go straight down in the second part we can go straight down then we can go straight down but once there's three water cells we can't okay and so in the second picture they show us the same kind of thing and so you can see that once the whole top row is filled with water we can't go straight down because there's no top cell we can go down so now we have the third picture you can go down day one you can go down to two this the way or this way you can go down the next day you can still go down so any path is valid from any cell on the top to any cell on the bottom and now finally we can't go down on this last day so this would be uh day three yeah okay and so we need to figure out how we can do this yeah right so it'd be day three because this is day zero day one day two day three okay and so we need to figure out how we can do this so there is one way to do it that's pretty straightforward and I'm just going to talk about that really quickly first and then we're going to go into the mode into the most more interesting way so the really easy way to do it well not so easy but you know easy enough is you can just take every single state and so you actually don't want every single state so first of all you can realize that for the for these cells like let's say these cells you know let's just say we have these entries in the cells like entry zero one two three four five six and so on so after a certain point you're not going to be able to go down so let's say that point is this after some point you're not going to be able to cross so all of these will be no solution right you can't cross and all of these will be you can cross and so what you can actually do is you can actually just binary search into this pick a random day and so when you pick a random day you can actually create the Grid at that day right so you can just like figure out what would be the Grid at that day with these cells you can update the cells up to that day that you picked for the grid and then you can do a breadth first search from that day and see like is there a solution that's viable so let me show you how that would look like let's say we take this last day here right we just randomly binary search this last day so we would have something like this uh yeah and then we'd have these land cells and these water cells so pretty much all you're going to do is you're going to take every single land cell that's on the top row put those into a queue and then you're gonna bread first search and see if you can get to the bottom from any one of those and if you can't and so that's just a standard BFFs right you just put all these cells into a queue and then if you can get to if you get to the bottom for many of those with a standard BFFs then you can say that day works as a solution and so if that day does work like let's say we can like we picked this random day like this day here so let's say you can't you can uh it's actually so let's say we don't know the solution we just pick a random day at like four and then if we if this does work so let's just say it does like d if it does work now we can binary search again on this left side and we can keep doing that until we get the smallest possible day that uh or actually I think they asked the last possible day right so be the other way so if the day does work you would want to go over here and then you'd want to try these days and see is there a day greater than here and then you would just record like the last day in your binary search that you were able to cross so it's a pretty straightforward uh problem so you just do a binary search in this and then whatever days you pick you do have bread first search in the grid that in the grid with the States from cells and so the way that would work uh so the time and space complexity would be um so you have a binary search on this bottom which would be the length of cells right so it's going to be like log the length of cells which is uh row times column so it would be like log row times column and then you have to search you have to do a bread first search every time which is so be like row times column times row Times log row times column so binary search with a bread first search and I think that's like a pretty straightforward problem to do like you should be able to do that solution but we're actually going to go into the more interesting solution here and I think it's quite clever and so I wanted to go over that one and so the solution is going to rely on the fact that we're going to be using Union find for disjoint sets so hopefully if you heard of Union fine for just joined sets pretty much what that does is like a basic understanding is it connects nodes together and then we can find if something if two things are connected and the way we're actually going to do it is we're going to base it off of land so if we have these cells right if we have these cells what we can do is we can actually start with a grid that's completely full of water and then we can Traverse backwards in cells so let's say the cells has a bunch of elements like one two three four five six seven and so on we can Traverse this way and for every single cell that we need to change we're just going to change one limit to water so let's say we're here and this is saying like you know on the last day this cell turned into a water so then we would be going backwards and say okay now that we're here let's turn that back into a land and then for the cell that we visit we're gonna try to connect to every other land node that's near it right so we're going to try to connect it with every other land node that's near it so let's just say we go backwards from actually let's do let's take this example here and let's go backwards so let's do that let's actually uh so the last cell would be three one and so remember these are one indexed so we'd go to three one and we'd say okay where's three one so it's Row three uh column one it's going to be the cell right here we're going to turn that into a zero and we're going to connect it to every land that is near it so right now there are no lands that are near it then we're gonna go to 3 2 which is this land and we are going to connect it to every land that's near it so there's going to be a connection right there and now we have so we did three one we did three two right we're doing these cells over here now we have two three and so that's going to be row two column three which is right here there is no land near it now we have one three and now and I'll kind of show you like what the end State you need to have is so 1 3 is Row one column three which is here and then since we turn this into a zero we're going to connect to every land that's near it so we're going to make a connection here okay now we have one which is going to be the cell here so we're going to connect it to every land okay so now is when we actually have a viable solution and the way we know we have a viable solution is we're going to have a node with all the nodes in here and if we can reach if this node is connected to this top node so if any one of these nodes on the bottom is connected to any one of the nodes in the top I'm going to show you how to do this then we return true and so I definitely think it's a really clever solution because we are taking multiple cells and actually making them a node and I'll show you how to do that and this is if you think about the time complexity here so what we're doing here is we're traversing cells backwards every time we are just searching for one number and we are updating all the elements near that which is you know constant time and so this solution would actually be R by C so it's faster than the uh than the breadth first search with a binary search and I think it's definitely trickier to come up with and like even if you know you didn't find now that I told you all this it would still be hard to code like and I think that's like a sign of a good problem even if you know the solution it's still not easy to code like I would definitely encourage you to figure out how you would code it knowing that's how you would do the solution Traverse backwards and find and make these connections and once there's a connection between the top and the bottom you would return uh the day that happens and so if you think about it there is some index in these cells right where like there's some index that's the last day and so when we Traverse backwards when we go this way the first day that there's a connection is the last day that was possible to cross so as soon as we hit a connection by going backwards and using land that's going to be the last day that it was possible to cross okay so now we have a couple other things to take care of before we can actually solve this still and so let's go into that so let's actually make some more space here okay so for a union fine the union fine is typically given a number of nodes right and so let's say we have this grid um and we have these nodes and they're whatever values doesn't really matter we need to figure out how many nodes we actually give our Union find and so what we're actually going to do is we're going to have so the number of nodes we want our nodes to be numbered like this and this is how I'm going to do it anyway so our nodes are going to be numbered like this in our Union find so we're going to give it a number and then we're going to have one more node for the top so this big node is going to be node number nine and this big node is going to be node number 10. and then we are searching for a connection here between node number nine and node number 10. so when we call Union find we're actually going to give it you know like how many ads we're going to give it we're going to get row times column plus two nodes because we want this top and this bottom and so the way Union find works is you give it nodes and it will connect them for you and they can also check if they are connected and I'll paste the code uh you know I'll show you the code for Union fine you know I'll paste where it is only code if you want to look at it and I can also actually paste my code in the description if you want it but so that's pretty much what the union find actually does is it makes connections between nodes and so that's what we need to do and then every time we visit a cell so like I said every time we visit a cell and we change it to a zero we do need to connect it with all the land here but we also need to check so let's say we visit this cell if the cell is in the bottom row then we also need to connect that cell to the bottom row and then if it sells on the top row we need to connect that cell to the tall Pro and then finally after we make all these connections we just check is our top Pro equal to the bottom row so if top equals bottom if they're connected right not equals but if they're connected then we are able to actually return that we are able to cross okay and so we need that and then we need one more thing here so now that I showed you how we're going to number these nodes it's going to be important to figure out how we actually get a number from a like with so these are indexed like this right so we need to figure out how do we actually get a number like how do we get the seven if we're actually here and so the way that's going to be like let's focus on the seven the way to get this number is actually going to be the row we are at times the total columns let's just call that like big or like big call or something that's what we're going to use and so if you think about it that just means like how many total columns we've passed so let's say the columns here is three then they're over at is two that means we've passed six total items and we have so we've passed six total items that's why we're on this row but there's a little bit more here we also need to add the current column we're on so we need to do this like the row we're at times the total columns plus small column and so now if you think about that let's figure out what that would look like for this example so the row we're at is row two the number of total columns is three and the column we're on is column one and so we'd get a seven so that's how we would actually get this like what's the actual n integer number that we're going to use to index into our Union fine to connect these okay and I think that's everything we need yeah and then like I said our top will be you know in this example our top will be nine and then our bottom will be ten so we're going to need to pass it how many elements do we need to pass into the Union find we're going to pass in rows times columns plus two elements but they're going to be zero index so they're going to be like this zero one two and so on and yeah like for example for this zero if you did this problem right here it would be row zero times columns which would be two plus the column we're at which is zero and so that's zero so that's how you get a number out of an index you're at and yeah I think that's it for this problem so let's actually dive into the code and let's go into how it would work okay so this is just a standard Union find um I didn't write it myself this time I just copied it from Lee code sometimes I write it myself it depends like you know what I'm feeling uh I can write it myself I would definitely encourage you to if you had to be able to write this yourself uh in an interview but you know make sure you know how it works and yeah so I'll briefly describe it so you have like you have um you have roots for every node and you have a rank that symbolizes the size of like the tree like the how many elements are in the actual uh how many elements are actually in like the path with this node and then fine finds a parent of the disjoint set and Union makes the link between two nodes and then connected just checks if they are connected or not so let's actually go over the code so this first part's pretty straightforward we just have the directions like we normally have in a you know BFS DFS because we do need to still check all of these cells near the cell we're at and we're going to make an initial grid with just a bunch of ones so it's just going to take like for this example one it would be four ones you know for this example they would all be ones we're starting at the end and we're working backwards then we make a union find with the number of rows and columns like I said plus two for the top and the bottom and then the numbers we're going to use for Union fine so like let's say this rows and columns is three right like I showed in the other thing the top would be you know I think I used let's see here for the top I used UF elements minus one so the top would be ten here uh aside would be 9 and then the bottom would be ten so I did add this little elements thing just for myself this wasn't originally in the code so I just said like this is how many elements are in the union fine and so in here the elements would be uh this would give you eight um no actually no I wouldn't give you eight because we're going to pass in 11 elements right this would be 10. yeah that would be 10. okay so anyway so then you would have like nine and ten for your top and your bottom so now we are going backwards through the cells and then because these cells are one index we have to actually subtract one from each of these cells so like this two three is actually index one and column two not two three so make sure you subtract one now this is that number calculation that I said where we have some row and some column now how do we actually get the number for our Union fine which is this like we have some index how do we actually get the number that we need to use to represent that node in the union find so we're going to have nodes in the union find zero to ten if it was a three by three and so on okay now we need to change the water into the land going backwards so whatever cell we're at change it into a land now check all its neighbors if they are in not an out of bounds location we can combine them and the nice thing is if you do a union with a cell that like if you do you need cells that have been connected already it doesn't do anything which is kind of nice so it's okay like repeating your work like it'll just as you can see in this Union uh if the roots are different it'll do stuff but if the roots are the same it just won't do anything so it's totally fine to do another Union you don't have to track like if they're connected or whatever so then you connect like you so you change one cell into a one or sorry change what's up to a zero then you connect it to every other cell that you can next to it and now this is finally our conditions so if the thing we just turned into a uh land is on the top we need to add it to the top so we would do a union with the top if it's on the bottom we need to add it to the bottom and this is our return condition I don't think we actually need this return negative one there's there should always be a valid output so I think if we run it without this that should still work because at some point there has to be a valid output yeah and so you can see it's a pretty efficient algorithm this way it's more efficient than a uh than the BFS and the binary search like I said and so this is our return condition if the top and the bottom are connected meaning any node from the top is connected to any node from the bottom and I think this is like the clever part about this is I never really did something where I had my I had like a set of nodes represented by one node essentially what they're doing like they're saying any node here is one node is the top and any node here is the bottom I've never like thought of things that way so I do think that's like good to know and maybe you can do that you can use that for other problems okay so now let's think of the time and space complexity here so for the time like I said what we're doing is we're initializing a grid to all ones and we're going backwards and then we are just changing one cell at a time to a land we're connecting it to every possible land near it and then what we are doing is we are uh we are checking if the top and the bottom are connected so in an ideal Union file it's not exactly like this but all these algorithms are technically Big O one I think they're not exactly like that but that's the argument it's like the finest Union and this connected is bigger of one so assuming that's the case then we have a time of number of rows times number of columns because for each index all we're doing is changing one value to one checking Four directions and just checking if something's connected so that's just all constant Time stuff okay and then for the space so obviously we make a grid we make a new grid we can uh yeah I don't think we're given a grid but we can like we have to use this grid so that's already rows times columns but also in the union find in the union plan itself and you give it some elements uh you're going to make a root array and a rank array and so those are also Big O then where n is Rose times columns so those are going to be Rose times columns and uh let's see so we have the grid top and bottom and all that stuff is just uh nothing um yeah so like I said in this Union fine this is Big O of Rose times columns this part here and then this is also uh this grid is also row of Big O times call rows times columns and that's actually going to be it for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I definitely encourage you to code this one up yourself um even if you know the union fine like I said just because you know the solution this one's hard enough to where you can like I literally told you the solution and you can try to code it and it's still not that easy I think so it's definitely one that's good practice okay so I will see you in the next video thanks for watching
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
824 |
Hello friends welcome to my channel it's all the problem got lighting pimples and problem history with string in this problem sentence subscribe like this sentence subscribe to the Page if you liked The Video then subscribe to mobile se 2 minut modi ji from hair To the end of the millennium city Chief Minister also visits every Wednesday and later To the end of but in a sentence with word processing Id 2nd Id for example a but make a comment section soon simple first world version of words Starting With Jag Bal So Wick Android For This World This Is Not Starting With E Will Be The First Character In This Epic Poems In The Number Of Cases Subscribe Button To The Language At 108 Number Of Who Is This Is Words On The Third Number Three Like A Similar Default In English Also Amazon Sale Amazing At How Will Directly To Implementation Of First Form Will Keep Track Subscribe Nobir Will Result In On Do The Elected College Chief Minister Lies With From Winter Class Monitor So Will Create All The Word Using Splitting Current Wave Subscribe Points 151 Ki And Will Check The I Just As E I O U Tabs Letters And Small Boy Died Module Index Of Ki Is Dish Content Index Of The World Ne At First Letter First Character In Taxes Are Not Moved They Will Update World Environment subscribe for Live Video Water 10 subscribe and ji ho gaye stringer amazed when will also up and suffix 210 suffix of chapter note will also produced a has space india and saw a gift for this update our suffix voiding given into its basis of every time Video Channel Subscribe And Just Removed Mein Convert Desh A String Builder To String On That And Will Always Be Also Needed To Trim The Last Space York This Loot Subscribe To Is Sode Receiver Next Point Note Index Of Mathematics In Spring Boot Have Enough To Subscribe To ki accepted sudhar 6 like my solid like button and subscribe the Channel thanks for watching this
|
Goat Latin
|
number-of-lines-to-write-string
|
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
* If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word.
* For example, the word `"apple "` becomes `"applema "`.
* If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`.
* For example, the word `"goat "` becomes `"oatgma "`.
* Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`.
* For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on.
Return _the final sentence representing the conversion from sentence to Goat Latin_.
**Example 1:**
**Input:** sentence = "I speak Goat Latin"
**Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
**Example 2:**
**Input:** sentence = "The quick brown fox jumped over the lazy dog"
**Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
**Constraints:**
* `1 <= sentence.length <= 150`
* `sentence` consists of English letters and spaces.
* `sentence` has no leading or trailing spaces.
* All the words in `sentence` are separated by a single space.
| null |
Array,String
|
Easy
| null |
230 |
hello guys welcome back to take those and in this video we will see how to find the K its smallest element in a BST which is from lead code day 20 of them a challenge so let us now look at the problem statement let us assume that we are given a binary search tree and in here we want to find the K smallest element within this binary search tree so let us assume that we are given this binary search tree and we are required to find the third smallest element then this will clearly be this 4 and the fourth smallest element will be this 5 so how do we find this yet smallest element in a BST efficiently now the first thing which we should look at is the BST property so let us assume that this is our BST now what property does a BST holds all the left subtree elements from the root are less than this root and all the right subtree elements are greater than the root and if you have duplicate elements then you can say that all the left subtree elements are less than equals to root or you can assume that all the right subtree elements are greater than equals to root you need to take one of these so generally people take all the left subtree elements are less than equals to root so this is true for each and every node so let us say we start from this root so if you are checking for this node 5 whether this is following the BST property or not then all the nodes in the left subtree should be less than this 5 and all the nodes in the right subtree should be greater than this 5 and this should hold true for all the nodes recursively so we will again check for this node 3 and we will see if all the nodes on the left subtree are less than this 3 and all the nodes on the right subtree are greater than this 3 okay and if the right subtree elements are greater than 3 then it should be in the range of 5 to 3 it should not exceed this value 5 otherwise it will not follow the BST property so I hope you got the BST property now how do we find the K smallest element in the BST efficiently so let us look at the first method I will explain you 3 methods so the first method says that let us assume we are given a BST now what we will do is we will just find the inorder traversal so I hope you already know how to find inorder traversal if you find in order for a be t-then all the elements will be arranged t-then all the elements will be arranged t-then all the elements will be arranged in ascending order now you can simply find K minus one at the index element and return it as the K its smallest element so in this case K is equals to five so we will return the fourth index element which is equals to 6 this will be your fifth smallest element in this VSD so the total time complexity for this will be order of n for forming this array and then in just one time after forming this array we can return the K smallest element and the space complexity is also n because you need an extra array in order to store the in order traversal that is the elements in ascending order so this is one very simple approach let us now look at the next approach so the next approach is by using recursion actually this can also be done by using stack but actually recursion also implements stack therefore either you do by recursion or stack it will have the same time complexity so in this case we will be doing by recursion so let us say this is our root 5 and this is our given BST and now we want to find the fifth smallest element within this BST so how do we find it well in my code I have implemented this second method so what I will do is I will just do the inorder traversal that is we will do in order processing first we will travel to the left subtree then we will process and then again travel to the right subtree so first we travel to the left subtree from 5vh 3 from 3 we reach to and from 2 we make the left call so there is no left child of this 2 so this will return 0 now we will process this now we will check if K minus 1 is equals to 0 so you can see that K is actually 5 and if you decrement its value it will become 4 so this is not equals to 0 if it will be equals to 0 then we will simply return this node value but this is not equals to 0 so we won't return the value now we will make a right call so the right child is not present it will also return 0 now since the right is also 0 we will simply return 0 now this left call received a value 0 now we will do the processing that is we will decrement the K value by 1 so K value will now be equals to 3 so is three equals to zero no this is not equals to zero so this is not the element we want we will make the right call this is four from four we will make the left call this is not present it will return zeros and now we will process the element so we will actually decrement this value by one so this will be equals to two is 2 equals to zero no this is not equals to zero therefore this is not our required element we will make the right call this will return zero now since it got zero from both ends it will also return zero now this 3 has also been processed so it will return to this 5 so now we are at five and you can see that K was actually 5 and it decremented in it got equals to 2 saying that we actually processed three nodes so you can see that in the left subtree we process three nodes now we return from the left call to this root node 5 now the next step is to process this node so we will decrement the value of K it will now be equals to 1 is 1 equals to 0 no this is not equals to 0 therefore this is not our required element we will make the right call so we are at 7 we will make the left column we are at 6 we will make the left call this will return 0 since it is not present now we will process this element we will just decrement the K value it will be equals to 0 now since this is equals to 0 therefore this is our required K smallest element so whenever we find the K smallest element we will simply return without making any further calls so I will return the value this will be equals to 6 and since this 7 got a nonzero value from the left call therefore it will not make any further calls because since it got a nonzero value this indicates that it has found the value therefore it will simply return the value itself which is 6 and since this 5 received a nonzero value from the right call it will simply return that value saying that it has found the K smallest element so in this case our answer returned will be equals to 6 now you might be wondering that this 0 might not work if the range of value starts from 0 and goes to the value N or if it starts from some value minus N and goes to some value n so for these type of ranges you can basically take intamin that will always work okay so this process is actually taking order of n time complexity because if the elements are given in ascending order or the elements are given in descending order then this BST will ask actually be a skew tree and to find the K smallest element in a skewed three you will have to traverse all the elements so the time complexity will be Oh n now the space complexity is order of height because the stack will be of the size of the maximum depth of this tree therefore in this case since it can be a skewed tree therefore the space will also be of the order of n now is there any way to improve the time complexity of searching the K smallest element in a BST yes there is a way so let us look at the third method so in this third method what we will do is we will just store an extra integer variable for each and every node so this question does not allow to change the value of the node if you are allowed to change the value of the node or add an extra parameter then you can simply take an integer for each and every node and what will this integer store this will only store how many elements are present to the left subtree of this current node so you can see that for this five I have given l equals to three saying that in the left subtree there are three nodes and similarly you can see that for node 3 I have given l equals to 1 saying that in the left subtree you have just one node so how will storing this information improve our time complexity so let us say you want to find k equals to v smallest element so how do you find it actually we will start from the root node and then we will see if the k its smallest element is lying to the left subtree of this current element so the left subtree is having just three nodes therefore all the elements which are less than the current node are actually in the left subtree and there are only three such nodes but you want to find the fifth smallest element so there will be no node which will reveal smallest in this left subtree so you will skip all these elements all together and then you will decrement its value by three so it will be equal to two now if K becomes equal to 0 then the current node is our K smallest element so in this case this is not equals to zero so we will have to make a right call and before making the right call we are actually skipping this element therefore we will decrement the K value by one and this will now be equals to one so we are at this seven now we see that on the left hand side of seven there is just one element so is our K smallest element lying to the left sub-tree you can see lying to the left sub-tree you can see lying to the left sub-tree you can see that k's value is equals to one and we are having one node on the left hand side so obviously the K smallest element will be present on the left subtree so we will make a call to the left subtree now we are at this 6 and you can see that L is equals to zero saying that there is no element to the left hand side now we will process this current element so for processing this current element we will decrement the case value by 1 and now it becomes equal to zero so whenever K is equals to zero that means the current element is our kids smallest element and whenever we find our K smallest element we will simply return the value so this 7 gets our nonzero value which is equals to 6 now whenever it gets a nonzero value this will also return without making any further calls so this will return a value 6 and root will also return 6 so in this case you see that we just made two calls from 5 to 7 and from 7 to 6 so this took only order of height time okay so this process is having the lowest time complexity which is equals to order of height so if this is a skewed tree then this will be equals to order of n because for a skewed tree height is equals to the number of nodes so I hope you understood the explanation now let us look at the code for the second approach because we could not apply the third approach for this problem since we cannot modify the nodes so in this case we are given a root and the K value saying the K smallest element needs to be found so I will just call this solve and I will pass the root and K and I will return whatever is returned from this solve function now this always actually taking the root and is taking the K smallest element that is value of K by reference because whatever changes are made in a recursion call we want to remember it therefore I will receive it by reference and not by value so if there is no root that means the node is not present then we will simply return 0 as I explained in method 2 now first I will make the left call that is we are basically doing inorder traversal processing so first we will make left calls and then after returning from the left call I will check if the left call returned or nonzero value if it returned a nonzero value that means we have found our K smallest element on the left hand side and so we don't need to do further processing we will just return whatever value was returned from the left subtree otherwise if the left subtree just returned a 0 value then we will have to do the further processing so we will process this current node so how do we process this current node we actually decrement the value that is we decrement the value of K by 1 and now we will check after decrementing by 1 value if K is equals to 0 if it is equals to 0 then the current element is our K smallest element and we will simply return the current roots value otherwise if this is not our required element then we will make a right call so whatever is returned from the right call will be stored in this right variable and whatever is stored in this right variable will be returned because if the element is not found in our right subtree then this right subtree will be returning 0 so we will return 0 if the element is not found otherwise if the element is found then this will return our nonzero value and we will have to return this nonzero value so whatever is returned from the right subtree we will have to basically return it so this recursive process will actually be finding the K smallest element in order of n time and order of n space so this is the second method and I hope you enjoyed the solution if you have any other approach or solution in different languages then please post 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 video see you know no 0 thank you
|
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,901 |
That welcome back price today they are going to solid problem 19715 topic element 200 amazon told e know i open play list solution videos vilas coding solution videos in java j2ee Please subscribe to the Channel etc stand hai slot video divine preparation for java j2ee interviews telephonic interview More Code Interviews for This Channel Can Help You With This Law Too Good Playlist Created for Lips Dismissal Computer Science Concepts Life is Graph Matrix Problems Dynamic Programming and Decoration It Related Data Structure 100 Subscribe to the Channel Antique Look at the Play List Sonu Lets Go Over This Problem Solve Description By Topic Element In Two Decades In Element Rate Distinct Greater Than Half Its Addition Absolute Top And Bottom 101 Text Biometrics Net Where Not Waste Your Sales Remove Wine PK Limit Matrix IJ End Returned Length To Agro Maje Means Position of the salute you may have some better inter metric surrounded by Dr. Perimeter Finance - Vanshvel Late by Dr. Perimeter Finance - Vanshvel Late by Dr. Perimeter Finance - Vanshvel Late Rubens that like the additional original metrics and surrounded by - One in all metrics and surrounded by - One in all metrics and surrounded by - One in all directions are you must right algorithm children poem login and that's an login time I Saudi Swiss Accounts And A Are Yes To Family Mein Dal Gori Dum Rush Within Life Ko Hum Log In Or Home And Long-Term Times So They Will See The Tune Home And Long-Term Times So They Will See The Tune Home And Long-Term Times So They Will See The Tune Of Immediately Meaning And Welcome That Can Do You Do Something Like Binary Search And Flavor Of Binary Search Night So Let's Take One Example of Matrix and They Can Discuss How They Can Solve This Problem Solve First Before Which States Should Win The Original Problem is Just Want to Start with the Concept of Minor Research You Might Already Know But Its First No Porn Clip Allu's The Final Research Works In Normal Solidaritytight Solid Se 30 Patience High Solid End When Position 026 And Want To Find Out Element Forest Officer And Target So What Do In Binary Search This Will Always Be Divided In Life Story Calculator Middle Using A Plus Six Decades ago is the law and he is the six and this divine ugly is the middle 100 vikram hui check this element so i find this element meanwhile neck for its order for must be inside left side for this which shampoo use in binary searchlight vikas patience States Will Look Into The Left Side Again Will Calculate Zero Plus Two Divided By Two Right Sources Bellcomes One Should Look At The One Element Position One Element 420 War Like Returned Back Position Is The Position Of The Target Element Right In Disawar Delhi Disawar Normal Binary Search Listen Let's Look At The Example Date Its 120 Days By Sudhish Kanth Matrix Lately Its One Famous Hai Input Matrix Dhundh Just To Wrong 34 The Input Matrix Has Come In And Have The Matrix Surrounded By - In And Have The Matrix Surrounded By - In And Have The Matrix Surrounded By - Issues Already Stated That In The Problem Solved What Is The Present Were Going To Take Something Similar To Binary Search They Will Be Built Up Lines - Not The Matrix Every Built Up Lines - Not The Matrix Every Built Up Lines - Not The Matrix Every Morning But Inst Of This Is Not One Time Management Matrix Jab Tooti Matrix 80 Today Matrix Thursday Ko Employer Binary Search Sahib Concept For Daru Saudi Server for stroke 2030 friends call this 123 430 or so what will you give it calculate the middle from this start 0 and 420 calculator middle doh 1610 two is the middle product this what is the middle doh so what we will do swift final and Maximum element in this mill road show hui final maximum element the wisest like going all fear of like all this element find the maximum as limit should do am fine and what we do it is hui first universities payment hui ago in all the of up-down Take Right and Left All up-down Take Right and Left All up-down Take Right and Left All Directions To Right When You Go Up Directions Pure Sequence 400 Higher Means The So Not To Speak Elementary And Soul Which Means What We Have To Do Go For Research In Two Districts Of Just This Region Will Have The Pick Element So I will go into his reasons which mins the never start role still remains 058 Problems One Right Because We Are Not Trying to Sharing Our Reasons for Others Listen Start Now You Can See a Row and Once Again You Will Say or Plus One Divided Bye that some request 2052 you again going to 1000 which is the fastest and you tried to find the maximum element so how can you find what is maximum element servi status thank you take of this is pe elements over all directions to right we like app download Right and left to right and left you don't have to go because you have already found maximum elements for this produced only one proper maximum salut how to check benefit only you have to take up and down so if you have both elements monitored and elements in You can read in the position for example in this matrix you will return 101 position as you an answer is that which is a PK element all the elements of entertainment present for small assistance present smaller and minus one is model saunf bus returns 0 answer solved Will go over that common algorithm and implementation name so common what do you do it means of but you can read this a stop so this one find period matrix function and first will just like they have Jesus implemented one function where is passing year and it was giving His mother maximum of position for maximum element in the product to macro element position so let's go and it's just give me the maximum position indro vridhshravah element is located ok so amazon created special variables and variables 2000 is the maximum length minus one register maximum roads for Example in this function in ruby and white mexico total function in ruby and white mexico total function in ruby and white mexico total 2500 android apps for deposit sw0 shri waheguru is greater than or equal to started to be tried to find out the main to here is encounter pick element exists in this greed song hui calculated for middle probe by Default Sim Start Row End Plus And Minus Starter Divided By Two Basically 838 Formula Zero Plus Form - Zero Divided By Two Is To Right Form - Zero Divided By Two Is To Right Form - Zero Divided By Two Is To Right 100 Like This They Shrink Aa Oh Calculate Middle To Here Right End In This Printing It's So It Should Be In Tune With दवा It's So It Should Be In Tune With दवा It's So It Should Be In Tune With दवा डायल 100 INDEX IS PRINTED डायल 100 INDEX IS PRINTED डायल 100 INDEX IS PRINTED REMOVED BUT CLEARED ARE TRYING TO GET MIXER POSITION ELEMENT FOUR CROPS AND NEW YEAR NO PASSER GAZAR ON RENT MIDDLE HAVE TRIED TO FIND OUT FROM EXPOSITION HERE AND WE ARE DIFFICULT WILL JUST WHAT WE WILL DO IT IS WILL JUST Computer Data with the Next Story Vikas The Best Service Minus One in Wide Subha Hai That Questions Compare for the Forest That Destruction Strong SIM Column Position Basically Export They Are Doing Your Feet in this Mode and When You Hear Good Actually Me Hai Already Elements of PDP For example here right thirty minutes when you are inside for stroke days gone have to only care about the 20 next road is destroyed highlight this morning have to only care about this shroff baroda previous rohit will be on - vriddhi rohit will be on - vriddhi rohit will be on - vriddhi software only will care about this row end Specifically in this column Hui Care Hai Vikas Pradhan Jaaroo How to Find the Pick Element Property Rights of this Element So Survey 3000 Good for Chhattisgarh Only the Biggest Element Hindi Source Software To Only Care About This Column and This Position Basically Its Objective of This Drink Clear Hai To Sudhar Chhod This Only During And After Last Loota Already Top Order For Stroke How We Will Do And For The Last Five Will Only Compare With The Last - 148 Sim The Last - 148 Sim The Last - 148 Sim Waste Disposal Of Pro For Example A Good Place For Elements Hui Yar Comparing Rate Din hui have to compare only with this rogue basically anything previous rodde glass trophy kushvansh with any in minus one should care about it's - and investment to what hui cares about minus one should care about it's - and investment to what hui cares about minus one should care about it's - and investment to what hui cares about only through and about only this element previous row and disagreements with species what will decide 32days pay element and not right because only four directions to wear look so that is what they are doing clear is a song that this what do you do here middle row is the last right and left is not the question middle rohit somewhere in the middle basically In the middle of the matrix and this will just check with the giver middle stop plus one will check with the next9 and will check with the previous right the element is grated and both the states like up and down everyday basically with the same problem solve this Movement And Will Submit Andar Position Hair Middle 9 And Romance Basically Right Brow Mexico In Olympics That Is The Position Of The Maximum Elementary For Example This 1431 Romance Will Be Given For Patrol Bichha 1000 Yudhisthra T20 Match Will Be Given To For ISRO 5000 This Is To So like day basically 100 ko koi have been destroyed completely in the meaning of the matrix basically drama loot medicine and maxists later when it's true same column element which month starts probe into ne do listen the element have found is not the pick element day hui compare with the element which is this side write-up basically write-up basically write-up basically aap tarf element with compare this year and your feet is model the of element and will just start mode is equal to withdrawal plus one basically will do the yes you can see that if twenty One element that some will compete with us of elements which s24 of element soe dushman isme more so when will just what we will do hind is case started hui se sur ki stuti 100 mi throw element which lucid and element right its latest entertainment and started rolling Mills middle pro plus one in that case that andrew if he is will seth android is equal to middle of middle pro plus one rate morning spot with you for maxim surrendered next roles next road show year basically to this in alert this clear second icon should be shown Clearly Shivlinga Lot of Things Will Put On This That A Hua Hai Ki Pyaas What To Do What You Are Saying This For Example Ludhianvi Started Wear 821 Is The Maximum Age Limit For Middle To Find What You Are Saying This Win You Are Comparing The Next Row Element Enemy Reduce 1History That War Treatment Meanwhile Neck This Elements Of This Element Is Not Bigger 12183 It's Not Bigger Basically Shop In That Case Will Go And They Will Update Center Interview Will Be Middle - 20 Middleton - Once Interview Will Be Middle - 20 Middleton - Once Interview Will Be Middle - 20 Middleton - Once Mince In Soil Clear Name And Started To Kiss Hairstyle 2000 and Android OS 100 Take Care You Can See Basically This What They Are Doing There Strong Going On To The Side And Lower Half Years But They Have Decided To Bigg Boss 10 Way Fight Pointer In Case Of Minor Is Right They Would Have Always Liked and There Left and Right Point 810 Something They Are Doing Care for Example You're Clear 895 Weird Look After Death Will Mower and Pointer Fair Prize Winners Will Want to Go on the Left Side of Them How to Find the Value Now in that case Gulf Bureau and Hai Hui Mootoo Navarai Hai Luttu Hair Soft Way Can Only Consider This Life What They Are Doing Here Vote Share In this Case Hui and Considering Upper Half of the Matrix and Half of the Matrix Basically Suicide Note to Wear Doing a Year and accordingly if apps update is straw and ROM then will keep doing till Android is greater than or equal to start doing so will keep looking and tried to find out the limits in this greed and editor-in-chief don't find Anywhere in editor-in-chief don't find Anywhere in editor-in-chief don't find Anywhere in Village After - 9 - Village After - 9 - Village After - 9 - 1030's Element in The Matrix Episode Will Return in That Case So Its Kind of Flavor to Finally Sir Date Priya and Implementing Hair Soft Evolved Two Dimensional Matrix Like This Is the One Who Works with One Dimensional Matrix One Dimensional Me Sunao yaar doing enough to dimensional main rishu it basically courier move into the reached and the lower house depending on the value of the side and follow side value different from the term maximum value so let's you to yaar do in clearly 209 my mobile clearly mention like clearly explain you how it's working so let's check pr se matrix that you have discussed this 1430 600 se metric sweetu kheer vote nau hai to aisi you can see nav hui first have stopped 0n android ruby calculated S2 stopped 0n android ruby calculated S2 stopped 0n android ruby calculated S2 end in his first middle pro end Will Find Different Venues Highest Element And Again Will Compete With Jewelery Brand Sui Compete With Seven Sun Hui Came To Know That To Our Seven Small Also Want To Find Out In The Upper Side Basic A Nitesh Upper Half The Matrix U Want To Find What Should Be The Next Time You Yaar Singh Start Trusteeship 108 Android And Into One Now From Foreign Rebellion Kiya Prabhu Yaar Looking And Mental Problems Zero Song Again In The Zero This Powder Maximum Wave Cheese Third Year Right And For This Thank You Yaar Checking BSP's Element And Not and cities pay element energy return opposition called s this is vivek roy throw and one for marriage bureau first morning this what will return and satisfactory answer to answer is extra cutting accepted 100 glutes use oil examples and behavior given so just amazed at its working Fine that Sudhir Verma also for multiple Thank you can determine if the mid-day were mid-day were mid-day were software also our solutions working fine silence remove the system that prize bid to show you saw no way can submit to work hard hua hai 500 and kudi screen hundred percent Hero image with printed and seventy per cent in the memory usage force so pretty good a soul this feature is just how you can question of scientific element to problem solve what you have done is you have used the flavor of minor research and Ravi first calculate the And they calculate the maximum element in the middle pro and will go and check for direct sunlight and in this case help only check up and down because you have formed maximum inverter Vasudev Devnani to go and check left and right option exactly maximum song depending on the Values of up and if we will decide which the Values of up and if we will decide which the Values of up and if we will decide which upper house has to go and lower house is to go for the evening metrics and active again will keep calculating the maximum value in petrol price middle class and with key checking for the pick element Swadeshi approach to Solve Problem So Lets You Must Know My Offer Job At Least Solution Videos You In Java J2ee Technology Jewels Z Me Aa Helpful Interview Related Videos They Discuss Frequently Asked Questions And How To Answer Left Blank Video Se Related To Data Structure Channel Ko Bhi Dum And Different Jha and Kaun 600 If you or someone like him were looking to prepare for interview stand this channel is point subscribe to the Channel Your subscription will be really terrible and help of the channel totally to more people and will also get benefited and saved for watching the video
|
Find a Peak Element II
|
equal-sum-arrays-with-minimum-number-of-operations
|
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal.
|
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
|
Array,Hash Table,Greedy,Counting
|
Medium
|
1263
|
1,721 |
hello everyone welcome to asmr call today we are going to solve another lead code problem name swapping nodes in a linked list so basically if you have not seen the problem statement you can pause the video right now then we can begin so what they are saying here that we will be given one linked list and we also given another integer called k okay so now we need to iterate through the given linked list and we need to pick that k node from the beginning and we also pick the kth node from the end okay and then you need to swap those two nodes okay so i think discussion is pretty straightforward let's try to see the given example once okay so what they are saying here suppose this is our linked list and our k value is equals to 2 so that means we need to identify the second node from the beginning okay since the k is 2 this is the second node and we also need to identify the second last node okay so this will be our second last node from the end right so basically we need to swap this two and four node and then we need to return the head okay so in the second picture you can see that we already swapped this we swap two with four after swiping it will look like this one four three two five so this is the thing that we need to solve okay so i think hope you understand this problem now let's try to identify some solution for the same so in this video we are going to see couple of approach to solve the same so at first we will see one basic approach in that approach we will use some extra memory and using that we will solve it okay so how we can solve it so probably we can what we can do we can take one added and then what we will do we will iterate through this linked list given linked list and we will insert those value into the edit like this right one two three four and five correct so now we can easily since we know that in the add a uh we can easily fetch any value using index in order of one time right so we will convert this link list to array then suppose i will face the second element right so it will be k minus one element so that is i can see two here right i can easily find out that from the array and similarly i can find out the second last element using index right so i can easily identify these two nodes then we can easily swipe this right inside the array only right so it will look like this one four three then two then five now easily we can iterate through the array and we can create another new link list and we can return the head so at first let's see the code of this approach then we will try to modify this okay so ah let's so how we can solve this so probably we will use add a list here since if we want to use array then we need to know the exact length right that is not known to us because linkage can be any size can be anything right but in the java if you want to declare any array then you need to provide the size so since we don't know about the size so probably we are going to use add a list here so let's take one adder list and we are going to store integer number only here so the type should be integer and let us name it as list only and let us quickly initialize it as add a list okay now what next we declare one added this header is already declared now we are going to iterate through the linked list and we are going to add all the values into the id list okay so to do that we can use while loop and since we need to return the head later so probably we are going to take another variable so let us name it as current something like this and we are going to store the reference of head right why because suppose whenever in the while loop we will keep changing our head to the next position right so whenever we are done with our first iteration or linked list traversal our head will point to null so that we need to store that head reference in the other variable that is current okay now we will run one while loop and we will this will run till my head is not equal to null okay now suppose i am here in the first position right in first position or first node i am going to just insert that value in our add a list okay so it should be list dot add and we are going to insert head dot after that we need to move forward our pointer to the next position so it should be head dot next head equal to a dot next okay so after this while loop our array will look like this or add a list will look like this right every value will be inside our add list now what next now i need to swipe those two value right so i need to find out this second value and the fourth value and then you need to swap it okay so let's do that let's take one variable called temp and since it's alif we can use gate method so it should be list.gate method so it should be list.gate method so it should be list.gate and we need to get the second value right so since indexing start from 0 we will write like this it should be k minus 1 so this will give us 2 okay the value 2 in the temp variable right and we are going to take another variable probably let us name it stem 2 and in this variable we are going to store our second last value right so it should be my add in sorry my list dot size minus k okay now easily we can swap it right so let's quickly swap it okay so let's do swapping now so now i will update so list analyst comes with one inbuilt method called set basically in the set method we need to pass two thing the index where i need to update and the new value right so at first we will swap so this came to variable contains value four so at first let's set four in the second position right so we will write like this k minus one that will be index and our new value will be tem two okay and similarly we will update the fourth position value right so here my index will be list dot size and it should be minus k and our value will be 10 correct so after this our added list will look like this right 1 4 3 2 5 correct now we need to build one another link list from this error list only right so let's do that so we will again take another for loop probably and we need to pick each and every number from this add a list okay so let us name it as int num and we are running in as follow here now what i will do so my head will be initially null right so i need to check that my if my head is equal to equals to null that means this is our first node right suppose i am here and now i want to create one link list with one so if i see it is head then we need to use some other logic and for other nodes we are going to write this one as in the else node okay or sorry in else box in s block okay so if i see my head is equal to null then we are going to initialize the head as head equals to new link list and since you can see this constructed right so we have three constructor we can but it one is the new argument constructor one with value and one is value and node so okay we are going to use the second one and we are going to just pass the value right so num is our value right and else we are going to so if i see it is not the first node then we can easily update the next node right so our head dot next should be equals to new list node okay so sorry this should be list node only since our class name is release node so it should be list node similarly here we are going to initialize with normally okay now we need to move to the next pointer right so now my head suppose i picked one and now suppose i came here i need to add it in the next pointed right so it will point to two after adding two again we need to add three right so we will move that to our next pointer so head will be equals to head dot next okay and once we are done we need to return the current right so return curve but before that current was containing the older head right so once we update our new head we are going to update our current variable also right so it should be current equals to head okay so let's quickly run the code and see whether it's running for the first test or not okay you can see it's giving us expected answer for the fastest cases let's quickly submit this okay you can see our solution is accepted so let's check the runtime also okay so what will be the time complexity of this solution right so at first we are running this while loop right it will take order of n where n is the linked list size then we are just performing some update operation of the basically the swapping operation then again we are running another for loop that is also size of k in least size right left side is nothing but the middle side is nothing but the actual linkage side okay so overall time complexity of the solution is order of n and what about the space complexity yes we are using extra specifier that is we are using one extra idealist and that size can be up to in order of n only right so in this case our time and space completely both are order of n okay of this solution let's try to optimize the same let's try to solve the same problem without using any extra spaces so our time compressor will be remain same for the new solution but we are not going to use any extra list or something like that okay or any extra space okay so how we can solve it without using extra spaces so basically what we will do at first our first trucks will be identify the length of the linked list okay so we will run one while loop and we will identify the length so in this case i can see length is 0 1 2 3 4 okay so if we start from 0 our length is four now what next now again i will i need to identify these two node right this first node and this second last node okay so again i will run while do and i will identify these two nodes and probably i am going to store the same in two different variable probably the first node and the second node that is if four right and once we identify these two nodes then easily we can swap the value right so by this approach we are not going to use any extra memory okay so let's quickly see the code that will surely give you much better understanding so for this approach we don't need any extra variable but we need couple of we do we don't need any extra spaces but we need couple of variables right the first one is the list node and let us name it as fast that will contain the reference over first node and we need another list node that will be second and again let's measure it as null only and apart from this we need another temporary or current node that will store the reference of our head and apart from this i think we need another variable called length that will store the length okay it should be alien it should be length should be initially zero okay now what next now we need to iterate through this linked list and we need to identify the length okay so again we are going to run another while loop here and we will run till my head is you know haze is not equal to null right so okay fine now i will check that if my so while i trading for the fast node right or first time right we can easily identify this fast node right so we will check that if i see my length is equal to equals to k minus 1 since we are starting from zero then we are going to update our first variable right so it should be head okay so using this if condition we can easily identify the first node okay now we are going to increment our length since we need to know the actual length right so if we are not able to understand the actual length then we will not be able to identify the second last node right for that reason we are identifying the length okay and head should be equals to head dot next find so after this while loop i can i will be able that what is my length of our linked list okay now again i need to run the while loop and we need to identify the kth node from the end right so let's reset our head to the starting position so it should be again equal to current because again i need to start from the because after this first value it will be null right with head will be null so again we need to start from the first so that we are writing like the head equals to current now again i will run while loop and i will check and probably we need a temporary counter let's name it as count so that we can identify the second i for the last kf note from the last right so it will this time while loop will run till my count is not equals to length minus k okay so i will run till until i found this fourth node right in this example and similarly i will keep updating our count after each iteration and we will move our head also right so head should be equals to head dot next so whenever i will see that i reach this second last node it will come outside the while loop and we are going to update our second variable right let's quickly do that so second should be my head now we can easily swipe this value right between first and second so let's do that let's take let's write a simple swiping logic right so temp will contain the fast dot val and our let's update our first dot value with the second value so it should be fast dot val equals to second dot val okay and now we are going to update the second dot value using the temp so basically this is a basic swiping logic right and once we are done we are going to return our head right that is the current okay i think that's pretty much let's quickly run the code and see whether it is running properly or not okay you can see it is giving us expected answer let's quickly submit the same okay i think our this solution is also accepted now let's check the time and space complexity here so here we can see that we are not using any sorry this was our solution right so here we are not we can see that we are not using any extra spaces but we are using some extra variable four five variable but in this case our space companies will be order of one since this we are going to use this much value this uh these four variables only for any size of the given linked list okay so that in this case our time complexity is order open but guess completely is order of one okay i think that's pretty much for this video if you like this video please do subscribe to our channel and if you still have sound out you can ask me in the comment section thanks for watching bye
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
701 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem binary search tree iterator we're basically implementing a class that represents an iterator over a binary search tree that's supposed to be implemented by in order traversal basically what you would expect from a binary search tree if you've ever used you know a real iterator before like in java or something like that because that's kind of one of the purposes of a binary search tree to have the values in some kind of sorted order it's not literally sorted but it's in a way that you could iterate through them in sorted order pretty efficiently there's really three methods we want to implement one is just the constructor and then two are the actual ones that have some functionality that we need to do so one is has next it's going to return true if there still exists a value in the iterator that we can return so suppose this input the iterator is going to go through all the nodes in order so at first it would do the 3 then the 7 then the 9 then the 15 and then the 20 and then it would be done right after all five values the has next should return false because there aren't any values left for us to return a while there are still values though then we're going to return true but we're not actually returning the value itself with the has next function the next function though is the one where we're going to be returning the value so the kind of trivial solution to this that you might be thinking of why not just implement inorder traversal run it on the tree have every single value put inside of an array and then we can just have maintain like a single pointer right start at the first value return this etc right until we're done with the array and then we're good before we implement the solution let's understand how efficient it would be well overall time complexity is pretty good of n we're just iterating over the entire array or not the array of the tree and i guess we can put that in the constructor if we want to so the constructor will be o of n time not bad and then each uh has next and the next function each of those can just be done in big o of one time because we're just uh incrementing a single pointer over this array now the memory complexity is also clearly going to be big o of n because we're putting every single node in an array and if i showed you kind of the bottom part of this problem they ask us can we do better can we actually implement a solution where the memory is not the size of the tree but the memory is actually big o of h where h is the height of the tree and can we make it so that has next and next don't necessarily have a big o of one time complexity but they have an average uh time complexity that's constant meaning if we ran the has next and the next function for every single node in the tree what would have been the average time complexity it would have to be big o of one so that's kind of the restriction so you can see that it's kind of a trade-off we're getting it's kind of a trade-off we're getting it's kind of a trade-off we're getting better memory complexity and slightly worse time complexity because this is no longer big o this is the average so how would we go about implementing this a kind of more efficient solution well i'll tell you how but first let me just tell you a couple of problem solving techniques that you can use if you were stuck on this first of all this is a tree problem clearly and usually the solution to tree problems is always going to be some tree traversal whether it's you know a dfs or a bfs and of course these methods can be implemented dfs can be implemented recursively and it can also be implemented iteratively so that's really your options here you have to try to see which kind of solution will be somewhat effective on this problem and if none of these are effective then there might be some kind of special algorithm that might you know be needed to solve this problem probably an algorithm you wouldn't be able to figure out by yourself to be honest and in that case you would need a hint from your interviewer but the good thing is we don't need a special algorithm we can do this with a regular in-order do this with a regular in-order do this with a regular in-order traversal but first let's try the recursive reversal and then understand why that's not gonna work and then i'll show you why the iterative traversal is gonna work so let's say we're doing it recursively we start at the root we try to go left as much as we can because we're trying to do this in order so you know we visit here then we visit here and then we keep going left until we reach here which is null so then we're going to pop back up here and then say okay this is the return value so for the next this is what we would return but how can we do that if we know where two functions deep because we did this recursively we can't just return from the next function we'd have to pop back to the root which is okay because let's say we just decide to record these in some kind of list or some kind of array data structure that would work but at that point you're kind of doing extra work while this is probably feasible what we're noticing is we already have these in memory because we're doing this with recursion and then we're just adding it to a list we can maybe just skip the recursion anyway and just initially add these values to a list so instead of even doing this recursively let's do it iteratively and just start adding the values to a list or rather a stack which is used for iterative dfs so this does satisfy the overall memory uh complexity of big o of h because any in-order traversal whether it's a in-order traversal whether it's a in-order traversal whether it's a recursive or iterative is going to have big o of h memory but the thing here is we're not adding every single value to the stack we're only adding up to the height and by the way if you're not familiar with iterative dfs i actually did a video on it a few days ago so i recommend checking that out if you're not too familiar with it but basically this is how it's going to work we're going to add these two values to our stack basically we're adding as many values as we can so let's say our stack looks something like this and then if we called the next function we would just go ahead and pop the value and then return the three but what's gonna happen after we pop that three value should we do anything different in that case because what if we actually had a right child of this three we know for sure it doesn't have any left children because if we if they did we would have either popped them already or they would be on the stack right now so three doesn't have any left children but it could have some right children so what we're gonna do after we pop that is check does it have a right child it doesn't in this case but if it did have a right child we would take that right child add it to the stack and then basically do what we did when we originally started at the seven from that node just go as far left as we can adding each of the nodes to the stack that's how in order iterative dfs works in this case we don't though by the way what if we called our has next right now would we return true or false well since our stack is not empty we know for sure that we do have some nodes left but is that the only criteria we'll have to revisit to confirm that we can just check if our stack is non-empty can just check if our stack is non-empty can just check if our stack is non-empty to return true for the has next we're not a hundred percent sure about that yet so we'll have to revisit so now if we call next again we're just gonna pop seven and similarly from seven now we're gonna go to the right child in this case it does have a right child 15 so we add 15 to the stack and then we go as far left as we can so we go to the 9 add 9 to the stack we go to the left child of 9 but it doesn't have one so then we know we can stop so notice how we still have a 20 left it hasn't yet been added to the stack and it won't be added to the stack until we have popped these values that is to ensure first of all that's just how iterative dfs works in general but that is also to ensure that we stay within the of h height the memory limit so now literally the only thing we can do is either call has next which is going to return true because we know for sure we have some values left on our stack and we can also call next a couple times so we're gonna pop this nine it doesn't have any right children so we don't do anything with it we can also pop this 15. it does have a right child in this case so now we're going to go ahead and add 20 to the stack and then from 20 we're going to try to go as far left as we can but it doesn't have any left children so at this point we've pretty much solved the problem right if we're going to call next again we're just going to pop the 20 then we look does the 20 have any right children no it doesn't so at that point the stack would be empty and we're pretty much done so the question we had left was how are we going to implement this has next can we just check if the stack is non-empty to return true yes we stack is non-empty to return true yes we stack is non-empty to return true yes we can because notice how before we return any of the values we have to add them to the stack even if we just had a node with a single value we'd have to add it to the stack before we uh returned it you know suppose we had a tree like this we'd add all of these to the stack and then as we call the next we'd pop them one by one until the stack is empty and that's how you know that we're done now what if the tree had some more nodes like this well in that case we'd do the same thing pop until we can't pop any more but as soon as we popped this one our stack would become empty but then as soon as that happened we would end up adding these values well not both of them i think we just add this one to the stack so our stack would still be non-empty so our stack would still be non-empty so our stack would still be non-empty and then we'd pop that and then add this one to the stack so as long as our stack is not empty we still have some nodes that we need to traverse okay so now let's code it up and so the way i'm going to call our initializer our constructor is basically by initializing the stack and since we're going to have to remember the state of the stack in between next calls we should make the stack a class variable it should be a part of the object and we should also initialize the stack in the constructor because we could be given a non-empty tree as a parameter in the non-empty tree as a parameter in the non-empty tree as a parameter in the constructor if we don't initialize our stack then if we call has next it's going to return false even though we do have some nodes left so let's initialize our stack and we're going to do it very easily while the root is not null we're going to add that node to the stack and then just update the pointer that root is pointing at and just set it to be root dot left maybe to make this more clear i could have used like a cur variable i could have said cur is equal to root and then have updated that curve variable but i guess it just saves one line of code so as long as it's not too confusing to you i think this is fine to do it's not like we're actually modifying the tree or anything now for the has next function which we know is pretty easy as long as the stack is non-empty then as long as the stack is non-empty then as long as the stack is non-empty then we can return true if it's empty we can return false okay now for the next function what node are we going to return well basically whatever's on the top of the stack and by the way they tell us that next is only but going to be called if it's valid so basically if there still are nodes left then next is going to be called so we know for sure that our stack is not empty so we're gonna go ahead and pop from the stack and we're gonna get that node and when we're returning we're gonna return the value of that node but before we do that we know that there's a little bit of work left for us to do that node that we pop could have some it could have a right child so let's get that right child it could be null though so let's have a loop while the current pointer is non-null we're the current pointer is non-null we're the current pointer is non-null we're going to go ahead and add that to our stack and we're going to go ahead and update that current pointer to be cur dot left we're going to keep going left as far as we can adding each node to the stack notice how that's pretty much exactly what we did in the constructor so if you really want to you can create like a helper function for these three lines of code so you don't have to you know rewrite them i'm not going to do that though because i'm pretty lazy i don't think it's a huge deal if you repeat yourself and it's just three lines of code so i'm going to run this as is hopefully we implemented it correctly and as you can see on the left yes we did it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Insert into a Binary Search Tree
|
insert-into-a-binary-search-tree
|
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST.
**Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**.
**Example 1:**
**Input:** root = \[4,2,7,1,3\], val = 5
**Output:** \[4,2,7,1,3,5\]
**Explanation:** Another accepted tree is:
**Example 2:**
**Input:** root = \[40,20,60,10,30,50,70\], val = 25
**Output:** \[40,20,60,10,30,50,70,null,null,25\]
**Example 3:**
**Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5
**Output:** \[4,2,7,1,3,5\]
**Constraints:**
* The number of nodes in the tree will be in the range `[0, 104]`.
* `-108 <= Node.val <= 108`
* All the values `Node.val` are **unique**.
* `-108 <= val <= 108`
* It's **guaranteed** that `val` does not exist in the original BST.
| null | null |
Medium
| null |
61 |
hey everyone welcome back and let's write some more neat code today so today let's solve a linked list problem rotate list we're given the head of a linked list and all we need to do is rotate the list by k places so what do they actually mean by rotate well let's just take a look at the initial list you see we have one two three four five right we wanna rotate by k places and in this case we see that the input value for k is 2. so what that means is we want to take exactly two nodes k equals two nodes from the end of the linked list so this is our initial linked list so we're gonna take the last two nodes and so we're basically going to split these last two nodes from the rest of the linked list so the rest of the linked list is the entire linked list five nodes minus these two nodes right and then you get the remainder of the linked list and you can see that these two nodes in the result this is the resulting linked list right after the second rotation this is the first rotation this is the second rotation this is the end result so you can see that these two nodes have been moved over here right the order stayed the same we have a four in the first spot we have a five in the second spot and you can see that the first three nodes basically the remainder of the linked list got pushed to the end of the resulting linked list right this is basically what happened right so that's basically the problem statement right we take the input linked list and basically we take the last k nodes whatever k is and then we're going to break the linked list at that point right this k is going to tell us this position because we know that this is going to be k the nodes in the remainder of the linked list is going to be k nodes and we're going to cut the linked list here and then we're going to basically swap the order we're going to move the end of the linked list to the beginning of the linked list that's the algorithm now that we understand what we're trying to do it's actually not too difficult right it's pretty simple but we still have to figure out exactly how we're gonna do it and the main question here with this problem is how are we going to find this position we know it's possible but and we know once we find this position basically all we're doing is swapping we're basically cutting the linked list here right and swapping the positions of the two halves of the linked list now the first thing we're going to need to do is because we're counting k places right we know k equals two right k equals two and we're counting from the end of the linked list right we're getting the last k equals two notes from the end of the linked list so we have to count backwards first we're going to get the entire length of the linked list and once we do that we know one two three four five right we have five nodes in our linked list this will also give us a pointer to the last node the tail of our linked list so we'll have a pointer to this tail node because we'll have reached the end of it and we will know that length equals five so you can see over here i have length equals five so that's great right now we wanna find this position right this position that's why we got the length how can we get to this position well we know we have five nodes right length tells us that if we're starting at this position let's say right we're starting at the first node we want to get to this node over here right because we know we're going to cut in this position so the number of positions we're gonna have to move to get to this node three is going to be length minus k minus one the reason we have a minus one so this is the formula for how many nodes we're gonna shift from starting at the first node over here right since we're starting here we know we take one jump and then we take two jumps and then we're here right that's what we wanna do and we're minusing by one because we're already starting at the first node so we know with our math and our values we're gonna get length is five minus two because that's k minus one so in reality this value turns into two that makes sense because from here we're taking two jumps to get to three okay so that's great now let's say we get to this node three right now what are we gonna do we're gonna take this right we see it's already red right we're basically taking this pointer and instead we're assigning it to null now right because we know that this is going to be the end of our linked list so at this point the picture is getting pretty damn messy but we're almost done the last thing we have to do now is take these last two nodes and move them over here right that can be done pretty easily right all we're doing is taking let's see this five right that's the last note in the linked list it's also our tail the only thing we're gonna do is take its next pointer and set it all the way back to the one right so obviously this has gotten pretty messy but hopefully you can still see what we did here right basically we got this resulting length list right we basically did the simple operation that i was talking about earlier we rearranged it right we took the five right and set its next pointer to one that's what we did and we set the three pointer to null right so this is pointing at null now because it's the end of the list four has become the new head of the length list so that's what we've done this was the visualization now let's actually get into the code and it's not too bad oh and one last thing what if k was actually bigger than the length of the input right or what if k was exactly the size of the input what if k was five what does that mean five rotations basically five rotations would mean that we ended up with the same exact linked list if k is equal to the length of our linked list basically we're not doing any rotations right so now let's say k was actually six what does k six rotations end up being it ends up being five rotations which results in the exact same list plus one rotation right so that would take the last node and put it at the beginning right so basically what the formula we can use is the number of rotations we're going to be doing is k which is actually going to be k modded okay so the first thing we do have to worry about in this problem is that what if we get an empty linked list so what if the linked input linked list is empty in that case we know that we can't really do any rotations on it so we're just going to return that empty length list next thing we want to do is actually get the length of that length of our linked list so we're going to use a couple of variables length and we're going to get the tail of the linked list in the process of doing that so initially the length is going to be 1 because we know we at least have one input node that's not null and the tail is initially going to be set to the head node which we know for sure the head node is not null so while there's a next node for us to iterate to we're going to do exactly that we're going to move to that position to the next position of the linked list and we're going to increment our length by 1. now we're going to do what i talked about we're going to take k and mod it by the input length just to reduce it to a number that's less than the length and what we know now is if k is equal to zero that means that uh basically the number of rotations is a multiple of the length list so we're going to end up not doing any rotations on it so once again we can actually return the head of the length list so the next thing we're going to do is move to the pivot and actually perform the rotate so we're initially going to start at the head node so current is going to be at head and then we're going to iterate a certain number of times so for i in range this tells us how many times we're going to execute this loop and i'm going to do just like i showed you earlier we're going to take the entire length subtract k and subtract 1. that's how many positions we want to move to so we can find that pivot position and then actually perform the rotation so every iteration we're gonna move to the next position of our linked list and this is all we need to do so now we're at current is at the node that we're gonna do the pivot rotation thing at right so what i'm gonna do is current dot next we know this is actually going to be the new head right current.next is going to be the new head current.next is going to be the new head current.next is going to be the new head so we're going to save that in a variable now what we're going to do is actually update current.next update current.next update current.next and set it to null because we know that this is the pivot position this is going to be the new end of the length list and lastly we also want the tail of our linked list remember we did calculate our tail variable up here we got it to the end of the linked list and we want to set that now we want to set tail dot next to the beginning of the linked list just like i showed you in the picture we can do that by just setting it to head and now that new head variable that we saved up here now it's time for us to actually return that the new head of the linked list and then we're all done with this efficient uh linear time linked list solution we know that this is linear time because really all we're doing is iterating through the entire list maybe i think at most twice or two or three times right that's all we're really doing we're not really using extra memory or anything so this is a an efficient linked list rotation solution i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Rotate List
|
rotate-list
|
Given the `head` of a linked list, rotate the list to the right by `k` places.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[4,5,1,2,3\]
**Example 2:**
**Input:** head = \[0,1,2\], k = 4
**Output:** \[2,0,1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 500]`.
* `-100 <= Node.val <= 100`
* `0 <= k <= 2 * 109`
| null |
Linked List,Two Pointers
|
Medium
|
189,725
|
258 |
hey everybody this is larry this was the code daily challenge day 26 or something like that uh i did just hit the like button to subscribe and join me on discord you asked me more questions or whatever you like uh but yeah so this problem uh i have trouble figuring how to explain this uh because this is a weird problem i think in the sense that um i don't know it's just for me yeah there's some math there's some wikipedia article you can learn about digit roots and stuff like that and then do the math that way um and for me the annoying thing is that the yeezy the quote-unquote dc solution where you the quote-unquote dc solution where you the quote-unquote dc solution where you do it with loops and uh or recursion um you know it's you know good practice if you haven't practiced but otherwise it's straightforward to do and straight you know like understandably how to do it right um but uh and for in this case i actually happen to know the uh how to figure this out just because it is something that comes up in competitive programming relatively often for whatever reason uh but that said uh usually you have to just do while loops it yeah it makes a little bit slower but it's not that much because at most um at most you're getting rid of a lot of digits every time so you it's like roughly log n or something like that right um and it's a huge basis like log 10 of n or something like that um and the different the easy all of one solution um is or the old one solution in general it's really hard to prove i mean maybe you could figure it out you could play around with a lot of things but in an interview either you get it you don't uh and you can play around with things but even then like it takes a lot of um mathematical background to be able to kind of figure it out um just to like figure out and play around with the pattern right so it becomes really easy to do the direct thing and really hard to do this you know clever thing and on an interview i don't know right um so i think my thing is that um can it appear on an interview i guess uh on an interview i would ask what you know what's an acceptable solution you would talk about both of them uh and then try to figure out how to do it your way right um and also yeah uh in terms of studying and knowing this though however uh i would not think about it too much because um unless you're good with a lot of stuff and you're familiar with a lot of stuff already then yeah you know learn more is fun but if you have a budget of time budget uh then and you're trying if you're spending an hour two hours to understand how this works instead of just me you know memorizing trivia or something like that then i would just focus on like you know getting better at breath research getting better that first search getting better dynamic programming but there's a lot of things you get better at and spending like an hour or two to kind of really dig deep to understand this from core principles or maybe even longer if you don't have the mathematical background uh it's not really worth it for me uh to recommend so yeah that's the way that i would explain it and with that all that being said um you can just do this of simulation that's what i'm going to do uh here and yeah let me know what you think in the comments i look at some hints but i mean i actually know i mean when you play around with digits uh it comes up but it's like really uh unnecessary i don't even think honestly i don't think i came up with it i just kind of done it enough to see it enough to be like given the answer at some point um or given the pattern at some point to be like oh yeah i remember this pattern because i've seen it enough times which is not really that helpful to be honest so yeah so now we'll do um let's just do a length of the string of this number is greater than one right so that num is the code two uh let's just say let's convert to nums uh let's sum for x in 4x and this thing and of course you have to end it and i think that's all you need uh and then we turn them hope i'm right uh add more numbers but yeah uh so try zero one two three i don't know just numbers 99 should be nine uh okay all right just some random numbers really and i could do random numbers because they tell you the answer right otherwise you would have to do it man like you're typing a random input but then you have to figure out what the real correct answer is it looks good so let's hit it and submit and yeah i mean i didn't really you know this is pretty straightforward um so yeah let me know what you think and i do know that answer and i don't really feel like it's worth for me to teach it uh other than for trivial reasons but let me know what you think and i'll see y'all later bye
|
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,739 |
hey everybody this is larry this is me going for q4 of the recent weekly uh contest 225 or 255. wow oh no 225 okay uh building box uh hit the like button to subscribe and join me in discord i spent a little bit of rough time for me uh lately so um so definitely if i don't have the energy excuse me uh and let me know what you think about today's problem so this one i actually thought it was kind of hard but maybe it's because i'm bad at these math counting things but a lot of people solve this and i think there are a couple of formulas that you can do i'm gonna explain my way um i think my way makes sense but i do not recommend my code is ugly as hell i definitely do not recommend it i recommend you try to understand my logic and then um and then implement it in your own words hopefully in a better way um yeah so basically for this problem uh the idea that i had was um actually i think i should have just added a thing and then that would have made it a little bit straightforward er um let me see real quick yeah okay um but yeah so basically uh oh that's not even true that is okay so basically this is my code there's a lot of debugging let me clear that out but yeah so basically the idea is that um you know i pre-calculate this array and you know i pre-calculate this array and you know i pre-calculate this array and this is the triangular array uh this is the base where you can build from so it goes from your zero one uh and then is it uh let's see yeah 1 3 uh 6 10 15 21 and so forth right uh so that's basically um to progre the progression of um the last block right so that's basically my uh the base that i work off uh it's i think this part should be straightforward uh there are other ways to write this for sure um uh and i ate a wrong answer because i didn't i don't know my infinity was too low uh but yeah this is just pre-calculating this part uh pre-calculating this part uh pre-calculating this part uh and you can kind of draw it out yourself to kind of prove to yourself uh basically you start with one and then next you have this and then you know and then you add three and then the next one you add four and so forth right um so yeah so that's how i come up with this and then you know that's how you get the number of blocks in the last block right um and then after that uh next thing that i want to go over and you know i'm skipping ahead a little bit because is that i have a binary search for the answer um i like binary search problems in general so i definitely pay attention a little bit if because i know that some people um maybe i go over too quickly but basically the first thing that i say is okay this is inclusive um so we want left and right to be both within the range and when we get one number in the range if left is equal to right so that's just why we have a while loop like this um we set the middle and this is just regular getting middle and go just counts the number of um total blocks that it could support so basically what is go right uh let me rename this uh and i cache this i don't know if this is necessary to be honest um i think actually cam that's called cam box um so what is this function uh let's say we have a black box for now we'll go over in a second count box uh gives you the total number of boxes given the last level is mid right and what this means is that if the last if the bottom level is mid we get count box number of blocks and if this is greater than or equal to n um that means that okay that means that we can try smaller numbers right and because this is equal to we could set right is equal to mid um because this is the inclusive range so this is why um you know this is why right writers go to mid because mid is a good value um that we want to keep um otherwise you know that left cannot be mid is not good so you want to try more blocks on the bottom and then you move left to mid plus one because we already know that mid is no good so we do a plus one there and here as i said it gives you the number of total boxes so once i have this magical box be able to do this um i actually have trouble with this one apparently um i mean i wrote it this way though to be honest this is just a for loop as well um but basically i wrote it uh yeah in a really funky way um but i just want you to know kind of how i came to it and you could write it in a better way in it you leave in the comments how you wrote it because a lot of people wrote this in a better way but basically my idea is that okay so you have this array right um okay so if the bottom is 15 then you're done right because uh you have 15 then we just want to go um we look at the bottom and then we recursively oh this is count box oh yeah then this is done because if we do a binary search to get this index quicker that's just you know to get it a little bit quicker um but yeah once if this is equal to this that means this is done because 15 then the box above uh or the level above has 10 boxes plus 6 plus 3 plus 1 and so forth this is going to take square with end of time so this is going to be pretty fast in general and this takes um i don't know given was it a mu i did 100 million so that's going to be like 20 copies 20 30 times square root of n where n is uh a billion is going to be fast enough because it's just 20 you know 20 or 30 times 10 to the fifth is fast enough uh just like a couple of million um and it's actually less than that but uh but that's just me handwaving math right now to kind of prove to you why uh on top of my head that's how i was able to do it um but yeah so this is the perfect case where this is equal but what if it's not well if it is not then um then what's on the bottom layer right um well on the bottom layer well we have bottom because that's defined but how do we figure out what how many are on the layer before that um so the way that i did it is having this funky uh equation but the idea behind that is that okay so let's say we have uh this but instead of an x on top we have an x uh a circle on the bottom so instead of uh having 10 blocks we have nine right well what does this mean actually well then the other way of the reverse way of thinking about it is okay let's say we have six right and we're getting to ten well what happens well if we get one the first number we do it has no extra boxes to the previous level right and then now the second one does because now this block on the previous level has a block so this one adds this block on the previous level which you know there's a recursive nature of this up as well and then lastly adding this block adds this block as well which allows you to do this recursively and that's basically my idea so k is the block that's before so yeah so let's save your let's say your bottom is equal to eight um this thing is going to go to uh you know your current number is six um so then the one before that is going to be three um and then the extra is equal to two and you know given eight sorry this is eight that's messed up this is actually nine so i think maybe i s this book earlier but yeah so this is eight um so yeah so the two extra blocks that are from the six um and because you have two extra blocks as i said um you have one extra block in the level before so that's basically just how i did this math where um you know i take the index of um of the w over two which is the level that's two um so this is the biggest level um the biggest previous level uh we count the number of extra here and then we add it to uh recursively we look at two levels ahead or so we look at the levels ahead and then we add in those extra blocks because those are the extra ones that we get to add in and that's basically what this function does and yeah um again i really think this i mean i looked at some solution during code review they're way cleaner code than this but that's kind of my logic and as long as you have that logic you can definitely rewrite this in for loops um it's just that for me during the contest it was easier to think about it this way uh you may think about it in a different way or you may try to understand it in a different way but those are the invariance that i saw when i saw this form and that's how i figured this out um and also i just kind of have this you know if it's less than zero or less than two then we just return that's the number of blocks um yeah whoo um yeah that's the that's all i have um let me know what you think you can watch me solve it during the contest oh next uh but let me go over the complexity i forgot uh so in terms of space this is square root of n which is um technically x exponential in the number of bits um in terms of space uh i don't use space otherwise so that's the only time i use space except for if you're going to count the stack space but that's going to be also square root of now this is log uh now this is also the square root of n so yeah it's also exponential in that sense so i guess this also takes uh on the stack space this will call square with event time so yeah uh in terms of complexity i have a login here um and on this to be honest um now that i think about it you could have passed this down um so you don't need to do a binary search every time uh you could for example this is just this and then you could have like maybe this will get an index function um and then you know and then you have like an index minus one or something like that i'm going to change the code back because i don't know if that runs but that's basically the idea to reduce that space uh reduce the time but during the contest i didn't think it mattered and it didn't but uh but these are things that i would do if i had more time um but yeah uh and then uh but yeah after that so this as i said this would call itself a square root of n times for each um for each mid function so you have you know and this is a log of the universe loop which takes about 20 to 30 depending how you do it but it depends on infinity to every set or the max number depending how you want to set it um and yeah so that's square root of n times log n something like that roughly um uh so that's the yeah so that's the time complexity and the space again is just square root of n um with some optimizations perhaps around this so that we don't binary searching every time because once we do the binary search on the first one we can go down pretty much straight up uh and don't even need to do a binary search if you're only doing it once you just do a fold up going up and then fold up going down uh this is actually uh kind of now sad that i wrote it this way but uh but you know uh during a contest you do what you can and i did grind it out you know i took a long time on this one um but yeah um that's all i have for this problem i'm gonna leave this code here uh let me know what you think and uh and you can watch me suffer live during the contest next bye-bye i can't believe i solved that bye-bye i can't believe i solved that bye-bye i can't believe i solved that one in like two minutes with a waste okay let's see if we're in boxes place and you took the four vertical sides must be addressed into another box over what boxes are placed in the corner one way to go this seems straightforward maybe but i don't know because there are a lot of smart people and they should get it before i do would be roughly a square root um it's like three six and then another four so the base is one three six and ten and then the sum of those right this is going to be roughly square root that's five that's pretty just in case yeah okay but that's probably right and then okay let's try to attend to the nine keys 42 thousands that's not bad okay those are the possible answers so how many bases are there um so put it this goes to one and then it is four and then ten you uh this feels right so then now it is just binary search on this maybe not even so turn so then now let's just return can be this easy though right oh am i just confused okay oh i see because if you have 15 uh let's see okay because if you have 15 it up to 20 but you don't actually need to use all 10 okay let's see you can do a binary search of some sort so this is harder obviously than i thought a lot of people got it but i you so how what happens if we have nine right we reduce this to nine then it is nine minus three mosses so this is nine how much can i support 16. i want this to be inclusive also i want to make sure that this works for one um okay and the last one has what do we do so this should be six and ten okay that's good actually don't know about this so have to be careful so we want this to have four because that's the level that we're adding okay so if this is we can go smaller oh really just not my day let's see 126 should have been 36 i agree with that i get the science one so this is the number but this is too big we can make it smaller because it's too small let me make it bigger hmm 45 huh how does it get back to uh so this is 72 times that up 36 should give us more than 72 so my formula is wrong how did i get it right before just look okay that's not good oh 40 um too big that's too good that is too small 36 has 120 is that wrong is that not enough i was still expecting 39 not 36 anyway okay just 36 plus oh it's 120 plus one two three four five six seven eight am i wrong why is it 36 why is it 39 maybe i am wrong okay so if i take one here i have to take all this but then i think one here oh the second tick is only off by one wow okay this is harder than i thought um basically two we started there's some recursive frame that uh i think the binary search is right it's just this recursion to kind of calculate that um i'm just not we're not really smart right now i should have skipped this one i'm not in good mental state to do it like an optimal so uh so and in fact you don't even want to remove this in order because what you actually want to do is remove them like this so that you have two and two so for eight seven i guess has to be this and six seven but eight is the key one that lets you do three by three how do i even know this i thought it'll be someone like this but um you see i mean it's going to be binary search and then you have this function that lets you do it and then you recursively go down um i just want to do it five by five can you generate a four by four here it's not even 4x4 is you know this idea that you can have is this idea that i don't know i feel like i'm better at doing this one but i don't have any test cases to work on either but this is just the worst uh thing of my thingy so we're doing a for loop oh there's just a couple of forms i think that's the tricky one that i'm trying to figure it out is an eight um if you have eight then you want to do this so that you can support oh is that true no because this doesn't have to now said you could support now i think i made that up it's still the same because you only need to care about let's just even if this is the case you cannot make a 3x3 thing anyway no but you can and if i have it here instead then i can have these three this one which is the same as if i have it here okay so i was wrong so then this is two by two um so like really do this um then how do we do it okay we submitted it so whatever that should be good enough how many boxes does this support so this is eight this is four so it goes up to n squared over two or something like that so if this is what number two we said it was i printed it out let's see it was 1 3 6 10 i think 15 so that's n choose 2 so that means that how many things can it support if this is 15 which is times 2 is dirty i don't know if this is too slow but let's give it a go um okay maybe i should have deleted it actually just go for this nope i don't know it doesn't really matter so basically if the bottom layer has you know um this might have gone the wrong way but am i printing oh yeah this is the bottom so then now we take k which is the most right minus k so then this is you my oops oh that's not good what's the answer well that's not quite either so let's say the bottom is six what's my answer here i get eight that's not right is it now because if you have six uh okay six two no that shouldn't be right okay um i wish i kept my answers for it but i think the one time remember is one 126 15 and 126. okay i printed way too much but uh it's still wrong though unfortunately 15 is right it's 37 as well um 129 why i wish i won a real coding thing okay so 37 the next one is 29 is that true just for fun 37-29 is that true 37-29 is that true 37-29 is that true 36 so what's 37 is then minus four eight so minus eight like i said i don't know this one uh i'm just so bad just off by a little bit entire day it seems well two to one is not true right that's definitely that what's four is one two three four which is at most one so this is actually also wrong four is one what is two away there is uh so for four it goes six 20 minutes to fix it's just minus one i think i'm a little bit off on her yeah this is too much i'm just thinking about this the wrong way again well three going to zero is definitely wrong is this one so it's full okay so if it's six so for every two above the previous one okay let's do that this is the next one and now okay so that now you have extra as you go too uh okay for every extra well that's just clearly that way but uh i think i'm off by one here okay went over but 122 still too low missing by a couple of blocks we have five that's five you have two that's right uh you have nine what's nine three four six seven eight nine so nine jeff actually one two three four five six hmm it's roughly right though this is no way but we'll see if it's actually right nope just ten seven no ten is six i'm one on that one anyway but maybe just off by one oh no this is easy to fix i'm just i should have tested this case i thought about doing it um okay let's see i just didn't think about it too much um where's the answer okay hey everybody uh thanks for watching thanks for checking out this prom let me know what you think let me know what you're running into and i will see you hopefully next time bye
|
Building Boxes
|
split-two-strings-to-make-palindrome
|
You have a cubic storeroom where the width, length, and height of the room are all equal to `n` units. You are asked to place `n` boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
* You can place the boxes anywhere on the floor.
* If box `x` is placed on top of the box `y`, then each side of the four vertical sides of the box `y` **must** either be adjacent to another box or to a wall.
Given an integer `n`, return _the **minimum** possible number of boxes touching the floor._
**Example 1:**
**Input:** n = 3
**Output:** 3
**Explanation:** The figure above is for the placement of the three boxes.
These boxes are placed in the corner of the room, where the corner is on the left side.
**Example 2:**
**Input:** n = 4
**Output:** 3
**Explanation:** The figure above is for the placement of the four boxes.
These boxes are placed in the corner of the room, where the corner is on the left side.
**Example 3:**
**Input:** n = 10
**Output:** 6
**Explanation:** The figure above is for the placement of the ten boxes.
These boxes are placed in the corner of the room, where the corner is on the back side.
**Constraints:**
* `1 <= n <= 109`
|
Try finding the largest prefix form a that matches a suffix in b Try string matching
|
Two Pointers,String,Greedy
|
Medium
| null |
213 |
hey everyone in this video let's go to question 213 House robber 2 on leak code this is part of our blind 75 list of questions so let's begin in this question you're a professional robber planning to rob houses along a street each house has a certain amount of money stashed all houses at this place are arranged in a circle this means that the first house is the neighbor of the last one meanwhile adjacent houses have a security system connected where it will automatically contact police if two adjacent houses were broken into the same night given an integer array nums representing the total amount of money at each house we want to return the maximum amount of money you can rob tonight without alerting the police okay so we've actually done a similar problem before we've done the problem House robber one and in house Rubber One essentially the description is exactly the same but the only difference is that the houses are not arranged in a circle so what this means is that for example this last house is not come connected to this house so for example in this last house if we rob it didn't stop us from robbing this first house but in this case we actually are stopped from doing it in this place because it's arranged in a circle you can kind of think of it as this house and this house they're kind of connected and so how can we go about doing this question right so we can see the examples over here you cannot Rob house one money two and then Rob House 3 because they are adjacent so really if you think about it if there's three elements then the only thing we can do is Rob the middle house and for example similar to something like this you can drop house one and then we can rob house three and then we can't actually Rob this one regardless but even if we want it like even if we did two and then this one over here it's still kind of less than four so it didn't work okay in this case what can we do if we have these three houses here we're in these three houses well I made a mistake I said if there's like if there's three then choose the middle one but actually it turns out that we can just choose the last one in this case because it is the maximum one but we cannot Rob any other house in this place okay so how can we go about doing this question we've done a similar question in the past which is house Robert and so I have a video for that so check that one out because we went in depth about like how we can solve it first using recursion and then we worked our way towards dynamic programming so I'm basically going to go ahead and just illustrate this solution that we have here so what did we discuss so in the solution that we had with the recursive case maybe I can just go through this first of all so let's say we had like a house right so this is our entire Street okay this is our entire Street and we want to determine if we could Rob house number n if we can rob house number n which is the six in this place now if we wanted to Rob house number n then what we could do is we know that we cannot Rob the house number J right we cannot Rob house number J if we want to Rob house number n because it is directly adjacent to it so what we realized was that if we want to Rob house number n then we want to find the best answer to house I basically the best answer to two houses in the past the best answer to this and then we want to add on the money for house n now it's completely possible that we decided not to even rob a house I so even though we are finding the best answer up till house I it's possible that we didn't even decide to Rob house I so that's just one thing to note but if we did want to Rob house n then we want to find the best answer until house I and then we want to add in house n now if we don't want to Rob house n then we can just take the answer that is in-house J so basically the best answer in-house J so basically the best answer in-house J so basically the best answer up till this point and again this doesn't mean that we've robbed house J it is simply the best answer until this point so for example what does that mean well if you take a look at this one and maybe I can put this over here so let me take a look here and put this over here so let's say we have something like this right and we want to determine if we can rob house n so here this is house I and this is house J now what is the best answer here the best answer is actually 11 right it means we can rub this and then we can rub this so the best answer here is house 11. but if you think about it here if I'm at house 9 I want to know the best answer up till this point house I now no we are not robbing house I in this plot in this part we might as well if we wanted to but we're not actually dude we're not actually doing it because if we did it if we robbed house I that means that we couldn't Rob this house over here this one over here and so we couldn't arrive at the maximum solution here similarly here we're actually not even robbing house J so even though we're finding the best solution till this point we're not actually robbing house J okay so that's just kind of one of the things we discussed about anyways I don't want to go too much more detail into this one you can definitely check out the video where we discuss in detail how we want to approach this problem but let me go ahead and copy this solution that I have over here I'll go ahead and copy the solution that I have and what I'm going to do is I'm actually going to put this inside of our helper function so let me just call a helper function Dev Helper and what do I need to pass in it looks like I'm just passing in the nums themselves right so self and the nums okay so now it's inside of a helper function now why did I put it inside of a helper function well notice in this case right like what we are given is that the houses are placed in a circle so really if you like think about it let's say like we have like a bunch of houses right let's say we have like a bunch of houses here if you think about it at no point can we rob this house and also this house so really it doesn't even make sense for them to be in the same array because we can never Rob like the two adjacent houses at the very end right so in this case why don't we maybe divide the sub problem into two problems maybe we can figure out the best solution where we consider the first element but we don't consider the last one and we consider the best solution in which we consider the last element but we don't consider the first one and we're allowed to do this because under no circumstance will we rob both of the houses right so we if we rob this one we cannot Rob the three if we rob the three we cannot Rob the five so really it doesn't even belong in the same array we can just consider the best scenario in which whatever the answer is here maybe in this answer it's like X and then we can consider the best scenario of whatever the answer is here maybe here it's why and so if you think about it in this way we can just take the best answer of X and Y and then that would be our solution so what this kind of looks like in code is the following so what we can do is we can actually check we can check that first of all if length of nums let's maybe simplify this if length of nums is equal to maybe we can just actually go ahead and copy this right so let's go ahead and deal with the case where length of nums is greater than 3 or greater than two right so it's at least three if it's at least three then I know that at least like in the minimum case I will have two elements right two elements so I can go ahead and process them so what can I do in this case well I would just return the maximum of consider first house this will be self.helper we'll consider this will be self.helper we'll consider this will be self.helper we'll consider nums from zero all the way to minus one so this will basically consider everything except for the last element and here we will do consider last house and so here we'll have self.helper self.helper self.helper nums one and then onward so basically here we'll consider all of this and so then I can just return the maximum of these two where I'm considering the first house and then I'm considering the last house but not the first one and so this is all there is to this question if you think about it really makes sense right because these two the first index and the last index do not belong in the same array because we can never rub both of them so we don't really even need to consider both of them as part of the one question here so anyways this is how we do this problem and again if you have trouble understanding the House robber then go ahead and watch that problem to understand how we can better go about doing that one okay thanks for watching and let's quickly discuss the time complexity so looks like the time is just o of n right because we're just going through um the array and we're doing it twice so it's technically over like n plus n 2N but o of n is what we can do and then the space is the same thing because we're storing it in the array okay thanks for watching
|
House Robber II
|
house-robber-ii
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[2,3,2\]
**Output:** 3
**Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
**Example 2:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
|
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
|
Array,Dynamic Programming
|
Medium
|
198,256,276,337,600,656
|
1,721 |
hey folks welcome back to another video today we're looking at question 1721 swapping nodes in a linked list the way we'll be approaching this problem is by using two pointers uh slow and fast um so let's jump right in the a couple of things that you need to set up the question is that you need three notes slow fast and first and all of them point towards head the first step you need to take is to initialize a for loop that will go from zero to k minus one and the reason why we're doing k minus one is because all of the nodes are already at um they've taken their first step already by pointing the nodes towards head so that's the reason why you're going from zero to k minus one instead of zero to k and what you're doing here is you're just saying hey you know what like fast just move it um move it to the next one for uh k times and this way you will have access to the first uh the first node which is the first kth node so once we have access to that we just assign the value to the first node right so we have the first k node and what we need now is the second k node from the end so how will we achieve that we will use a while loop for that and we will say hey while the fast dot next is not equal to null keep moving both of the nodes fast dot next fast will be equal to fast or next and slow would be equal to slow dot next so what exactly is happening here right so since fast is already k steps ahead um by the time fast reaches the end of the linked list low would be pointing towards uh the uh k note from the end so now we have access to both of the nodes the first k node and the last head node which is pointing which we have asked to uh with slow uh so the thing you need to do in the end is just what the value so into temp would be equal to first dot volume uh so you would say slow dot value would be equal to oh no sorry the first closed dot volume is equal to slow down volume and slow dot value would be equal to 10 and in the end you would just return the head right so quickly let's compile this and see if it's okay the first test case is okay now everything else is okay as well awesome so let's quickly talk about the space and time complexity this space complexity of the entire solution is of one since we are not really using any additional space um and the time complexity is off and since we are iterating through all of the nodes in the linked list awesome so that's the solution for this problem if you have any questions please let me know in the comments below and please don't forget to subscribe i would really appreciate that and um if there are any other questions on legal that you want to solve also let me know in the comments below i'll be more than happy to solve it for you see you all in the next video peace
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
956 |
Hello everyone welcome, we are going to do video number 41 of my channel, okay and my playlist of DP consumption question has also started, so you can start watching that too, okay and I am also available on Facebook and Instagram. Court Service with Mike's name is ok lead number is 956 yaar medium mark toh hai sorry medium mark is not there so I think hard mark is ok but it is going to be very easy just because of it's explanation, we will not write it but it is very simple. Gonna use a little brain to convert it into memorization Thoughts IT Our story will end there Okay IT Bill has been on a very cake The name of the U OK question is the tallest billboard Google asked Let's consider this question as an OK question You are installing a billboard and you want to have the largest height. Meaning, you are installing a billboard, you have to take it to the longest height. Okay, you will have two steel supports. By doing this, there will be two roads. Its length will be l1, its length will be l. And by the way, the length of both should be equal, right, only then both means equal, if these bill boards are standing on two roads, then the size of both the roads should be equal. It is written here, keep giving the collection, they must be giving a lot of routes. Keep in mind that someone's length is one, someone's is three, someone's you are five and so on. Okay, now it is telling you that how big is the maximum road you can create, how much top the billboard has to reach, but the example. IF YOU HAVE BROADS OF LENGTH ONE TU THREE MAA LET'S TAKE IF YOU HAVE IN THE EXAM I HAVE GIVEN THREE ROADS OK THEN YOU HAVE BEST OP'S METHOD WHAT IS THE BEST OPTION BROTHER WHAT DO YOU DO THIS ONE ROAD AND TU ROAD BY DOING THIS Make this road, it is of three sizes and this is the third one whose length is the same, put it here, it is also of three sizes, so how much is the longest land, it is three, no, its height will be three, this is the bill. Like our answer of the board is bill b three is ok now return d largest possible head office zero if you can't then answer will be zero but example is 1 2 friend ok now you tell me one thing you have only two roads you have one here you will put one here Here you will put its length, this is your choice, it should be of equal length, so only in this question, what will be your answer, it will be zero, till now it is clear, okay, if you look at it is very simple, actually, isn't it? Why understand its reason? I am giving a small example. 1 2 1 This is your road. Sir, you have given all these rods. Okay, now what is it brother, there are two roads, the length of one of yours is l1, there is a calendar in the starting. Both are zero, I am fine under the billboard, so I have three options, if I don't see it, then I should take the first road, which is its length one, okay and tell me in which one should I add it in length one, okay then what is my album? The album will become one, okay, which roads will be left, this and these will become roads, that brother, you have not taken this one road, it is important, the story is not written in the question that you have to do all the roads, but the example. It's 123456 ok so come on man what can you do choose two choose three and do this thing two three five three dot went here and choose this and do another six here On one and on six, the length of both of them is 10. The billboard has gone. You are seeing that on one, I did not do it only, so it is not necessary that you have to do it on all the roads, then I got one more option that brother, I did not do it to anyone, so I did it. Still, what is the length of l1, it is zero and the length of l2 is also zero, okay, and here I have mentioned which one you went back and one went back, one is exhausted, okay, now that means in every option you have three. There is an option, there are three options in every index, so you can clearly see that the power of three is going to destroy its time complexity and it is also clear cut that it will only give you the power of three in time. nd is a big number, neither is time comprehensible, bill will be very slow, nor is very big, time will become very big, but in very slow solution, it is important to make a tree diagram of it so that you can understand it, its logic is correct, so let's move ahead here. But look, it is very difficult to make a complete tree, it will take very long, I will band one branch from where my answer will come out. Okay, so look, I will hold it. From here also I can see three options. Right here also three options are visible, what did you do in this and this one is the road, now you are looking at this road, what is the first option, brother, if you square in 11 then what will happen to L1, here it is red. Let me write that the length of l1, remember earlier it was already one, now I have taken this also, OnePlus 2 became 3 and if l2 is done then it still becomes 0. Earlier it was zero, here it is zero of zero. Okay and now which road do you have, just one mantra dot child, this one, let's go, okay after this or what was the other option that you did not add it in l1, what was the length of the rhythm one was one will remain one, here is one. And what will happen to the lens of L2, here the auto tax was zero and now you have added this two length road to L2, then the length of Altu has become two. Till now it is clear and what is the third option that you have not chosen anyone. So 11 went to l2 went to zero and here the road which child is just the one last road is okay we are okay now then friend from here we have three options I will go into this thing rest all you can go later also Ho but trade if we become very big so I'm just going here go here there are three options you can draw in these also you can draw here also It will be long so I am not making it right now, let's see here also what will come, okay like mother, let's take this last fraud child, you have three options to add it to the album, so what was the length of l1, last time. I had already done one, so you will become one plus one, okay, and what was the length of L2, you are the only one, okay, and here you are exhausted, if you take the mother, did you think of putting this one road in L2? D. In the second option, L1 will become L2, lens of L2 will become three, okay and you have exhausted all the roads, here how much will L1 take, one al tu karan bhi tu ka tu hi will be reduced because you have not given any road to it. So, all the roads have been exhausted. Okay, so it is obvious that everything has ended, isn't it? Now that you have reached the last position, all the other Sikhs who have come to the last position have become last, so as soon as all the notes are exhausted. So now you have to check what length you have got brother, let's see here l1 What have you got brother, you have got l2 What have you got brother, you have got very good, the length of both is equal isn't it, let's see here l1 What have you got There is one l, what have you got, 3, you have got it, brother, forget this one, which is there, l1, you have got 1 l2, you also forget that if you want one of length from both, then here I have got one of length, so I have got this. I will tell you that brother, I met both of them by length and you are the length, it is okay, so I will send you from here that brother, if there are going to be lenses from someone who is on the road, there will be two of each, so I would return two like this. I am fine and what will be the return from this brother, when the length is not equal then I will return zero or brother, if it is possible then I have returned zero. From here also it is not possible so from here also I have returned 0. Which is the maximum among the three? If it is two, then what did I do? I returned two here. Okay, something must have come from here too. Something must have come from here too. The one who is maximum among the three will be returned, so the maximum can be. Mother, let's take two. It is okay, so two returns have been made from here too, something will come from here too, and something will come from here too, so one among all, the maximum one will return, the answer will be mine, you will be okay, and look and the answer is you only, a billboard will have to be put up. So what will I do, I will take this one and one road, one with length and the one with two lengths, I will plant one here, two lands, see the total, this is my answer, it will be simple, so what is its recognition code also? You must have understood that by now, you can write the code by pausing, and still, I will show you, so see how to write the recognition code, tomorrow we will do a simple function called solve, I will say, start from index from zero. Which is my first road, that is, the one whose length is l1, which I am calling l1, its length in the starting is also zero and l2 is also zero in the starting, okay, I will return it, whoever gets the answer, now I Solved, I am late in writing here, ok, what is the second thing, as soon as all the elements are exhausted i.e. ID is the number, what had to be checked, remember, if there is no album, then brother, what did I say, make the return zero, that is not possible, zero has not been made. You will find that it is okay, what was the first option that you did not take? If you say nothing, then no road is okay. What will you do in this option, if you get flooded further, what will be the meaning? First of all, we find out the maximum of nothing and define N in global. It is clear till now, I had said that I will write a simple question function, I will have to send roads there as well as starting and there is a zero which is 11, its length is zero now and the length of l2 is also zero in the starting, so for both. Till now I have not even started taking the road, okay now see what I said, we have to see three things, first of all I have not taken the road of history, it is nothing, then simply the road which will flood further will remain the same because we have taken something. Not only this, any road is okay, second, what happened that Road One has been taken, right? Road One, either say it like this, but the road on the left, if I have added it to the left road, I will not add it to the album or else I will add it to the album. Added to the road and or right road exponential solution is okay auto is also length is even length will do this because you cannot take such a big size okay now if I run it like this then most probably this memory limit will give one seat Because we cannot allocate such a huge space, we will not be able to do it like this. Many people said that brother, make an unrooted map, make a key and store it in the map, that too will be resolved in time, I will not make it another dimension. How to do it, then you try to understand, okay, so see what we were sending in the solution just now, brother, which index is it? With the index, there were a total of three variables, so how to fix it, okay? Look, what is your goal ultimately, you have to see this only, brother, there should be no difference between the two roads being built, meaning the length of both should be equal, meaning L1 should be equal, you should know the meaning of L2. What should be the difference between the two, it should be zero then why don't I worry about the length of both and simply write the difference and as soon as I see that the difference has become zero then I will take action. What will I do, I will check the difference, how much is the difference child, now what is the difference brother, it is l1 - l2, it is ok, so tell me one thing, tell me one simple thing, if now the length of the first road is l1 and the length of the second road is l1. Do it as l2. What will be the difference between the two? It will become deeper. If I want to add it to l1, then I made it 11 plus Okay, so if we find out the difference, then we can write it like this, l1 - l2 l1 - l2 l1 - l2 + + I am Deep Plus X, what does it mean that now an extra This is what has happened in the lamp, its rod is so flooded, my lamp, my tip is so flooded, it is clear till here, now let's say something like l1 l2, it was there, mines, this is okay, now what happened that which X was there, I added it to l2, so l1 - l2 + The I added it to l2, so l1 - l2 + The first option was that it was quite simple for the nothing person, now let us understand one more important thing, so see if I write the code with this, then how will the code look, see just this concept, I have changed the code, then when will we have to do something? When the depth goes to zero, it means that both the lengths will be equal. Here I have to send something, I will see what to send, this is the biggest ministry, right, I think most of the video or most of the code solution which is provided. It is today's time that they are not explaining this point properly, I am getting such a feeling, okay, then we will understand that part well and look here on the internet think aid, you are the one on the left and you are the one on the right, how can you see these three. If nothing is added then the depth will remain the same. If you add left side road then you will do You also know that there will be mines, there is some fear, I told you earlier, okay, but now the question comes, look friend, tell me one thing, I have to find out the length, not what is the length of the road, I am not just adding the story but showing it. You know, this is a deep, this is also so, when I will return from this function, then what will I return, brother, what will I return that I will be thrown out like this, I am not doing the length of Santa, I am of the deep. I am tracking, okay, I am tracking the drift, don't know what I will do, I will add here that brother, have you added it to the road on your left, which road have you added to the road, so here I am. I will make an add and take out the length from here, so it is okay, I am taking out the length from here, there is no need to return anything from here, return zero from here, now there must be zero add, there must be some add. No, I will add it here. Similarly, here also you will think the same thing, it is okay to do so, yes, I am tracking that I am adding the length of the road and in the last place, from where the maximum length was taken, that is I will return it, I will do nothing, let's make a little sense right now, okay now we have to find the maximum time, so if the difficulty is not zero, then if I am not there, then what will I return, it's minus infinity, either say eat the minimum. It must be clearly visible too, okay but there is one more catch in it, okay, they understand now which is the most crystal part and I think 90% of the and I think 90% of the and I think 90% of the people have definitely complained about the empty noise in the other videos. Brother, you did not explain that part properly and now I am going to highlight that part. Okay, so let's see just a little while ago, remember we had made three diagrams, remember this very nice thread diagram, so you are looking for the solution one. Which lesson was one, went from here to here again, so what do I do, not just re-draw the lesson with the solution and re-draw the lesson with the solution and re-draw the lesson with the solution and make three diagrams of my lamp method, L one L tu, now we don't do it. So, I will make its three diagrams and description again and I have just highlighted the point from where my solution A came because the tree will become very big. On the left side, I will just tell you in the larger part of this lesson where the solution came from. Isn't this the same thing, you must remember it is okay so look let's move ahead here remember in the starting the index was here and in the starting here def was zero na div was zero see I am not writing in l1 l2 code by the way tell me Let me show you this l1 l2, it is not here, but I write it here in the cell so that you can know what is the depth. There must be zero in the beginning of the album, but there will be zero in the beginning, imagine, don't understand, I wrote it like this. Given so that you can see whose lens is working, if I take the one and add it to the left one i.e. L1 road, then it add it to the left one i.e. L1 road, then it add it to the left one i.e. L1 road, then it is ok, what will be the length of L1 and how much will the auto be, zero, ok till now. It is clearly visible, okay, now look, pay attention here, now we have gone ahead, here I have two road children and one road child, okay, now again I have three options, prepare here, I will add you. Should I take the left road or the right road or should I not take it at all, these are the three options, so I remember this was the lesson with the solution, I am taking it, so what did I do in this, I added on the L2 road, so this time What will happen to l1, which was earlier l1 has become one, l2 was zero earlier, now I have added two to it, so l2 has become 2, this time Div, what will become of my 1 - 2 date, it will become -1, my 1 - 2 date, it will become -1, my 1 - 2 date, it will become -1, definition is done, ok. After this one was my lesson of solution, I am going on this, you can also draw the rest, but it will be very long, that is why I am only showing you one thing, there is only one road, one child, this one is fine. Now whom have I told that I will add to the L1 one, okay then what will be the length of L1, one was already and now one night's to you will be, how much will L2 be to Altu's, if you were already, you will remain the same. Or see how much the lamp has become, define it, mine has become zero and what now, all my roads have been exhausted, all the dots have been exhausted, so what I said was that we will check the value of the lamp, is the value of the lamp zero brother? What did I say that we will make the returns zero, that now there is no need to do anything else? Okay, and remember what I said that when you are doing the recreation tomorrow, then before that also add what road has been added. Isn't it so that how much is the track, then ultimately the answer needed is what is the length, so before calling the recension here, I will also write that brother, which road has been added one, if the one road has been added, then how will one plus be added here tomorrow. How much return have I made from this to me? If it is zero then it must be 1 + 0. Is it zero then it must be 1 + 0. Is it zero then it must be 1 + 0. Is it right? One plus becomes zero, so what will happen from here, I will return minus infinity, from here also I will return minus infinity. Maximum among the three. Who is one, then one went from here, became in the return, now in this also, you must have done the same thing yesterday, you plus this one, tomorrow, now from here, this mines will be infinity, this also mines will be infinity, this one has come in the middle, so among the three. If there is no one to the max, then I returned one, you plus one returned three, it is okay here, so too, you must have done it yesterday, took this road, one plus, what is the maximum of the three? Three - what is the maximum of the three? Three - what is the maximum of the three? Three - Infinity - Infinity What is the maximum? Infinity - Infinity What is the maximum? Infinity - Infinity What is the maximum? So total to me, when I reached here back from yesterday, I returned from this thing, similarly, something will come from here, something will come from this thing, okay, so my text can be from here, mines is infinity, if I am doing management, then I am returning. I am but pay attention to one thing brother, there is no road land here, no one is of any length, Kalyan is one, you are one, so do you know what is actually happening, these two roads are being built for the sake of billboards. I have sympathy for both of them, what have I done with l1 l2, here I must have put one more two roads, one here and here also one forest and this one more mantra must have been put of two lengths, so how much is the sum of both the wholes, so that is the tax. Tax has been returned here, so I know ultimately what return has to be made, remember I had solved it yesterday, the solution is zero and the difference is in the setting, so whatever is the return, I will return it, okay, I will return it brother, that is my answer. If it is 4/2, then it will be my answer of one road, send 4/2, then it will be my answer of one road, send 4/2, then it will be my answer of one road, send it to me, send it, okay, till now it has been cleared, date is a, I am returning by doing y2 here, right and date is the same, I have returned zero here. Because I added Road here and why did I add Road? Brother, we were not just trying to see the story and we added the thoughts of the Road edition here. See, there is a reason behind every thing as to why this was added. This is why I did not write in the beginning that this is the solution and should be built. If I had written this entire line directly then you are not able to understand, there should be reasoning and it should be built. Your solution is correct and I also like it more than these three diagrams. Clarity came, I made the complete tray diagram, then I came to know, okay, he is doing it, then I do it, tell me, I turned the answer at the last minute, it is okay to keep both of them at length, what will happen 121 Mother's come, brother, I will do it, okay So friend, let's quickly code it and finish it and yes one thing and now you have understood that brother, in the memorization I will do now, there is a part of IDEX and a part of difference, okay till now. So if it is clear then what is the maximum in IDEX? If it is index then it is given in the question that brother, the maximum length is 20, so I will give many pulses, here I have given 20, I have given 21 pulses. Now the matter has come brother, what will you put? Okay Deep, now this is also a problem, okay, so it is given in the question that brother, the total which is even, it can be 5000 of our elements or what will happen is it will be 5000 and l2 which is zero, then what will be the difference. 5000 then the value of the lamp is fine in between 5000 so let's reduce one. Do you remember the thing I said yesterday about the late challenge, the longest arithmetic sequence, I remember what I had said that as soon as I came to know that if I had to index it can also go negative, so add a constant well value to all, whatever is the value of the lamp, add a constant value to all so that it becomes positive, then what will I do, 5000 to all. I will add ₹ 5000 to this also, it will become zero, ₹ 5000 to this also, it will become zero, ₹ 5000 to this also, it will become zero, okay, how much will it become, it will become 10000, okay, we will take 10000 from zero, the concert has been offset, I have added 5000, that will be given to him later, make a note of it and keep it, you are watching. Here, there was a problem with negative index, so how did you solve it? An offset was added this time. How much offset is there? There are 5000 choices, that's why I have to learn it. Write it down, whether it is a story or a story, then look at this thing in the two questions. It got offset. Edition Ja Shakti, according to us, so what will I do here, how much value of the lamp will I take more than Rs 10,000, let's take Rs 10,000, okay, so this is all we have to do and our memorization will be less, let's court it quickly and end it. Let's quickly finish this with our memorization technique. What did I say that here we have no less than 11 l2? I want to keep only one variable, so I want to keep these ideas deeper, okay here. If in the question of nothing, what did I say that except l1 and l2, here it will be filled with deep, if you have added it to the road on the left, then you will do deep plus mines plus here also there is no talk of road, so this. Remove it friend, I told you that it is difficult, you will check it for zero and make the return here if it is not so, then you will send a very small value, this means we will send it is okay and whatever value is coming in solve, you will buy it and send it here. Till is clear now what we have to do is to do memorization inter t of 21 ok and 1003 taken before solving everything let's check if t of id x but it can be negative so what did I say 5000 add Will we do it? If this note is equal to two minus one then we will simply return its value. Return this is fine and if it is not so then we will store it here first and then send it. Already do it every time. All are passing. Solved 0 No, just 0 Isn't this the index, this is deep and there is no need to send anything, we haven't let's pass, let's submit, let's see forever, you pass already, how to use this memory technique, indeed yes Solve this question is very good recognition memorization of this problem is fine its entire DP is bottom up also but we will make that in a separate video so I hope you can help any doubt would be raised in this common session and try to help us and next video thank you
|
Tallest Billboard
|
number-of-music-playlists
|
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000`
| null |
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
142 |
hi welcome to this video for elite code 142 linked list cycle the goal of this question is to actually find the beginning of where the cycle starts so of a linked list i should say and the other thing that you want to know is that this particular question involves a technique called fast and slow pointers it's very important to know because when you have something like a linked list and you want to detect a cycle you always want to use this technique first a little basic thing about what a link to list is it's a node that has a pointer to the next node and then at some point perhaps that node points to no or at some point maybe instead that node points to another node and then you have a cycle like here you can just keep going like this over and over again i think right now it's useful to think about an analogy of what would happen if you knew for a fact that you were in a cycle so what is a good way to think about a cycle let's think about a race track like a 400 meters race track at the olympics so this is definitely a cycle continuous and suppose you are a person who runs 10 kilometers an hour okay and you're racing usain bolt who runs 20 kilometers per hour now suppose this race would go on for perpetuity until usain bolt catches you now because usain bolt runs twice as fast as you do then suppose you both start at the same place at some point usain bolt will catch you i think this kind of analogy is easy for most of us to kind of visualize it and understand that if you're on a track one party runs twice as fast as the other party at some moment that will meet so if you have a linked list and you want to detect a cycle if that linked list doesn't ever end and no then you can keep looking for that cycle if it does end in the null that means you know the cycle doesn't exist it's worth pointing out that question 141 on lead code is to simply detect a cycle and si 141 is to detect a linkless cycle and 142 is to detect the starting point of that cycle so i think right now it helps to take a real quick look at the code and then we will go ahead and start on the example of running through what would happen so again you have a slow pointer here you have a fast pointer here and as long as the fast pointer is not null and it's next is not pointing to no meaning it hasn't ended then you can iterate you can step through and kind of move the pointers forward and as we mentioned the slow moves forward at one step and the fast moves forward at two steps and at some point they should meet if they don't meet then there's no cycle if they do meet what you want to do if you take a look at this type of lengthless cycle is that for example what might happen is you might have to fast pointer and slow pointer so after a few cycles end up at this step and then what you want to do is see if you move head forward one step at a time and slow one step at a time where do they end up meeting because they'll always end up meeting at the starting point the question is just how long it takes so i think if you understand the general concept of the code doing a quick step through will really help us to see what is exactly happening with both a fast and slow pointer so let's take a look at that right now so in the beginning you start at the same place for the slow and fast pointer and then when you move forward what's going to happen is slow moves forward one step fast move forwards two-step forwards two-step forwards two-step right so you see we'll just write it right here fast is 2x slow is 1x all right and so at the next point you'll see that fast move forwards two and slow will be at where fast currently is see if i show you the next step you'll see that's exactly what happens and then we continue to step through again and then again fast move forward two spots slow move forward one spot so they almost about to catch you at each other and they will at the next step i guess it's very important to note that when you are moving these things through you know you want to make sure that you compare the value of what the node contains so usually like you know i don't know sorry you don't have to compare the value but no you just compare to see if they are the same note so once you achieve this particular spot it goes back to what we talked about earlier where you have the head at this place so once these two meet what you want to do is so when it's fast and slow meet you want to advance slow one step at a time and head one step at a time until they gradually meet each other and that's exactly what's going to happen if you take a look at what we drew earlier and we actually just try to take that one step at a time right so then head will be here slow will be here and then head will be here and slow me head and then you end up returning this note okay so that's lead code 142 linked list cycle where you find where the start of the cycle is hopefully this video helps you think about cycles with a better analogy and also drawing it out helps you see what you're supposed to do when you have this kind of question remember this requires a technique called fast and slow pointer and when you see a lot of linked list questions and it's asking you about cycles this is probably the first technique to try to think about okay that's it thank you so much
|
Linked List Cycle II
|
linked-list-cycle-ii
|
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Medium
|
141,287
|
957 |
Hello hello everybody welcome to my channel today is the day 3 of sewa recording challenge MB problem in presence of trends in this problem for nurses back to win the best tools everyday subscribe our Channel subscribe and subscribe the Channel subscribe Video subscribe duty world ki main 1000 Subscription Rate Tools Saw With His Two Rule Considerations Of Baghavan Initial State Of The Return Of The Day And Subscribe Our 10000 Problem Basically So Like This Is The Meaning Of Free Subscribe Like It Is Like Acid's Rally Mention In The Problem Be Happy Version From Day One Search Sales Very Like The Settings and Self Bomb 014 and Luther BF Draft subscribe and subscribe this Video subscribe Solve 1234 500 600 21 Three Floor 5 to 6 Total subscribe The Channel and subscribe the Channel and subscribe A What for I Think What We Have Two Villages Sector-51 Value Equal Two Villages Sector-51 Value Equal Two Villages Sector-51 Value Equal Two Plus One Value subscribe Video Rule Subscribe Everything Which Exists In The Next Day This Status Tha Next Smith Will Right Choice Will Return After Your State Of The Chapter First And Dividend Will Be Condition And It Will start from 21 Lootere subscribe The Channel Please subscribe this Video subscribe and subscribe the Channel 100 Quantity 0 Veer and Saunf Isi Time Complexity and Year in Problem The Constraints and Its Very True Most Strong Draws to the Power of Future of Power Will Definitely Have To quit after subscribe sure subscribe changing 600 2012 hai to how many total combinations can be possible sweet say today power 2664 combination sudhir total different 64 combination co-star sudhir total different 64 combination co-star sudhir total different 64 combination co-star twilight seven wave the indus isse zari pattern total toot 6 mission for this is the state of the Amazing Repetition Of Them Would Definitely Be Repeated After 6 And You Will Basically Say This Is The Latest News Hai Shesh And We Shape So Let's Check Also Consideration Of The Burden Of Fixed Point Bhava Vision Raddi Ki Saunf Bal Dhoop Va Deep Chaudhary Element And Generate A String Using The Amazing Library Method To Strings Vijay Create A String And Take Medicine To Our Sites And Will Check Continuously Is That Is Already Exists In The Exit Point Will Find A Cycle So Lets Also Say That Dyan Ki Vansh 4000 Ki One And Ki 2.23 Boys Video Channel Subscribe to Saunf Baghwa Repeated after the will get cycle and every time you later this is the what we can reduce the model of J&K model of J&K model of J&K that this what is the state of the places where written test will basically reduce time complexity Late Lakshmi And they will discuss and commercial little better Latest Implement this code first will it help method which is the president without state and will get the initial sales and here will generate new cars celebs to subscribe will loot from 10 inch plus ideas to souls of - One Subscribe ideas to souls of - One Subscribe ideas to souls of - One Subscribe Plus Shravan Ko Ma Middle School In One Otherwise 10 And Beer With No Like Or Subscribe Like Subscribe And Share It That And Will Take Away In The Level Of Baroda Information Way For Cyclone Tubelight College Cycle Its An Initial Eyes Will You Will Take place will check subscribe that and food will call and the next day the are from dimer album the next day state civil services in the next generation using red two strings yes string swadesh me generally twisting the next9 will check is scene donnison reader that thursday Ko Civil Judge Updater Cycle Stop This is the President for B.Sc for B.Sc for B.Sc that and Update Dulhan Plus and Also Written Updates of Vidyansh Yudhishthir Vikram This is not withdrawn in villages Check Cycle is the return of the - Lu This State Cycle is the return of the - Lu This State Cycle is the return of the - Lu This State of the Year Will Return Se Method Completely Updated On That Adarvais Vijay Returns The Amazing Cycle Fictions Foreign Soldiers Have Solid Body Ray Hua Main Is Chord Is Compile And They Are Adding A Correct Answers For This So Let's Submit Solution The Cities In Law And Justice Accept This Place talk time complexity AP to like total to the power six combination sir possible service rule of veer run maximum 6 times for the time complexity and complexity of dissolution of 6 and not stand in the way of CMS school me store maximum 64 values in websphere store maximum 64 values in websphere store maximum 64 values in websphere Subscribe Button President Mirwaiz Like And Also Started With A Slide District Values More Important Slide District Values More Important Slide District Values More Important Dadar To Be Don't Care About Time Vikas The From The Next Day E Salute All Vikram Jeera Saunf Randhir Wa Status For Daddy Se 1000 Milk A1 Plus Elements Of Plus 7000 Left Side But this 8000 repeats itself will not be a 200 this is like improved a proof on the map theory also in this to be ranger cycle will repeat add first one and also from similar solution but which is not difficult as it is not easy to get into doing so Will Give Withdraw From Moving In A Code To Reset My First Step Mother Of Two Souls Will Agree With You And You Will Like Share And Subscribe Paid So Let's Thank You Feel Like My Solution Please Like Share And Subscribe My Channel For The More Sach Videos
|
Prison Cells After N Days
|
minimum-add-to-make-parentheses-valid
|
There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109`
| null |
String,Stack,Greedy
|
Medium
|
2095
|
1,377 |
hey what's up guys this is chung here so today uh let's take a look at this hard problem here uh number 1377 frog position after t seconds okay so you're given like an undirected tree right and the nodes are from one to okay and a frog starts jumping from node one and in each second right the frog jumps from its current node to another unvisited notes okay if they are like uh if there are like a deer are connected right and the frog cannot jump back to a visited node basically if the node is already visited the frog cannot jump back which means that the frog we can only go to the unvisited nodes okay and in case if let's say if the frog can jump to different nodes let's say from one the frog have can jump to either two three and seven right and the probability right to jump to each node is like it's random basically it's evenly so the probability from uh to jump from one to two is it's one third same probability for three and seven they're both they're all one-third all one-third all one-third okay and uh what else the uh so another one is let's say when the frog could not jump to any animated the vertex basically if at the uh if at the time t uh there's no unvisited node the frog can go to basically it will just stay at this node forever okay and the input is like the other address and then the nodes here unknowns and what is what it's asking you to get is uh it gives you the t here basically it means that after the time after t seconds and also the target so from one to after t seconds to add the target at the target nodes what's the probability of that okay so i mean this is like a ver it's obviously like a either a tree or a graph problem i think it's more like a tree problem yeah i think it's true because there's another like a graph so and it asks you to find the uh the probabilities okay and for normally you know for a tree problem we always we usually use like dfs search right to traverse to the uh to our targets and a few things we need to be careful here right basically and the first thing is that what's going to be our like ending point right what's going to be our base case so it's kind of obvious right obviously the base case is when the card node is a target okay and then that's our base case but when the target when the current node is target node we have a we have two scenarios okay so the first scenario is the uh let's see the currents let's see the target for example with this node here with this tree structure here let's say the target uh is three it's three okay and the t is uh let's say five in this case let's say five so what this one means is that you know at the time one here right time one here uh the probability jump to two three and seven they are they're all one uh one third okay so basically after t one okay we're at the target three here but then can we return the minus uh commit return to one third here not it's probably not why is that because the problem is asking us to return the probabilities after t seconds so then i think if we look uh watch closely here basically uh when we add a target here we have uh two scenarios i mean the first one is if the current time if the time is equal to the t okay so if that's the case let's say for example if the t in this case is one instead of five is one which means uh when we're at three at a target the time it just happened to be our final our like the target time here then of course we can simply return basically the current probability that's going to be our answer okay and yeah and how about another case is it's for is for this one let's say another case let's say for example this five here when it's five here and if there's any basically if the current time is smaller than t so this one means that we cannot stop at the target which means we have to keep jumping okay so in this case right so we need to check if we have any unvisited nodes here so it means that you know if we have uh at this at the target notes here if we have any unvisited nodes at this moment which means in this case we are three here we have we cannot stay here because if we have a another unvisited nodes so the frog has to choose one of them and jump to it which means from three it has to jump to five so what does this mean it means that okay we were at three here but we couldn't stop at three here it means that we have to jump from three to five but in this case since the 3 has already been visited which means we can never go back to our target right which means the probability is 0. right it means that we will never be able to jump to here uh and when the time is smaller than t and we have some unvisited nodes here yeah i think that's basically some the basic uh two scenarios right of the base case and other than that it's just like the dfs search with the calculation of the probabilities okay yeah i mean if you can figure if you guys can figure out these two like uh ending scenarios i mean i think it shouldn't be that hard to solve this problem uh okay let's try to code these things here basically with dfs right i'm gonna create a dfs here we're gonna have a node here and the time right that's going to be our current time and i think for from my case i uh i'm passing the current probability to here i've i find that this is like a more intuitive to me to end i mean to understand okay so that's that and then first let's create a build a graph here right so it's gonna be a default dictionary and list okay and then for u and v right for uv and in edges okay graph u dot append v and the graph v dot append pen u okay so that's the graph and we all we're gonna also need like a visited like set okay cool so that's that and at the beginning right since we st we always start from one that's where we always add one here okay and then and we'll be having an answer here answer equals to zero okay and then we'll be calling this dfs here so the starting node is one and the time is at zero and the probability is one because we're starting from one here right and then later on we'll be using the current probability to not uh to multiply with the different options here okay and then we return the answer basically that's our that's my structure here and okay so now that the main part which is dfs here so what's going to be our like uh base case or the ending case right uh basically if the node right is equal to the target okay when the node is equal to target i mean we can certainly uh verify right if we're gonna return like an answer or not and also it's because this is like once the notice has been visited right there's no way uh basically this three the target node can only be visited once so that we can simply uh return from here because what we know once we're at the current target here it's we can basically determine our probabilities already okay it's either like zero or where the current probability okay and in order to determine the probabilities here we also need another like variable which is the uh like i said do we have any unvisited nodes at this moment okay so to do that i mean with the current node uh we have a neighbors right so neighbors from the graph okay of the note okay and to get to be able to get the unvisited right i'm gonna just do a simple uh process here basically the neighbor for neighbor in neighbors right if the neighbor not in visited okay yeah this is pretty straightforward right basically since we have a visited notes here a visited set here so whoever is has it's not in the visitor knows it's the is the note it's unbelievable notes okay that's why uh so two scenarios we can return the current probability the first one is the this one like i said when the current time is the same as the t then we can simply return the current probability second one is the what or uh where the time uh it's smaller than t right when we still have to move um well actually probably we don't even need to need this time check here we can simply use uh or not unvisited visited and then the answer will be the probability so this one means that uh if the current one is the if the time is the uh um if the current time is this and or you if we still have some time uh do we need to check if the time is smaller than t here yeah what if the time is over is greater than t here okay you know let's uh let me try to finish this one first and then we'll probably we can come back to double check if we need to verify if the current time is smaller than t or not okay so now and then we simply return right because we already find the answer or word not right we're not big or not means that the answer will stay at zero so i mean if the current node is not a target so what do we know we need to do uh we need to calculate the current probabilities right to the next uh node which is be it going to be the probability equals to what n divided by the length of unvisited right uh oh i think here uh we need to uh if un visited basically this one this check means that if there's a any unvisited nodes otherwise we'll have like divided by zero exception here right so that's going to be the current probabilities and then okay so now for each neighbor right for each neighbor in un visited okay so here i'm also using like a little bit backtracking mechanism why is that because let's say we have a for example for this from one we have three scenarios one to two to three to seven so for each of the scenario here basically every time we have neighbors here i'm gonna add visited dot uh add this card neighbor to the unvisited and then i'm gonna do a dfs to a neighbors right that's going to be on time plus one also the probability is time the probabilities okay but that's only for the one scenarios since i'm not passing the visited uh the since all of the branches they're all sharing the same visited set here and after this one for loop i need to remove set remove that node from the visited here remove okay so that i mean when this dfs branch is finished when we're coming back to the second branch which is three here the visited is the uh is still uh still correct okay yeah i think that's that should be it okay let's try to run the code here visited okay 16 unvisit a lot of typos here uh oh sorry so here i think i need to do a non-local here non-local here non-local here answer right because we're setting a global variable here yeah cool i see yeah i see so i think this means that i mean for one of the return conditions here i mean we cannot simply check if there's no not visited we have to check i mean or time uh it's smaller than the t and not visited yeah so basically this condition means that i mean uh we are at the uh or you know what actually here so basically if the time is greater than t right we simply our return so then i think we can just do this i think this should work yeah basically i mean uh i'm just adding like this one of the branch cut check here which means that i mean as long whenever the uh the time is greater than t right and the e you know we haven't seen the node yet then we know okay it's obviously like a zero it's a invalid like we there's no way we can reach the uh the target right uh within the time here that's why we simply do the return here otherwise right otherwise we can simply uh otherwise whenever we have a like we see the target we can simply check these two things right at this moment uh if the time uh just happened to be our target time here we can simply set the probabilities or even if the time is not but there is no unvisited node which means that even though we have some other some more time to jump but since there the frog has nowhere can go so he can just she has to like keep jumping uh keep jumping at the current target until we reach the uh the time here that's why we can simply also set this like the probability to the answer here cool yeah i think that's pretty much it is for this problem i mean it's uh i don't think it's that hard but the only things you uh need to you guys need to be careful is the uh what's the uh the ending point right what's the uh what's this the base case and also uh the uh like this is how we uh basically calculate the current probabilities and also the uh for each of the dfs we also need to use a kind of like backtracking to make sure the visitator is correct a current visited for each of the dfs call is correct and also and then we pass in the updated probabilities and also the updated node and time cool i think that's pretty much it is for this problem yeah and yeah thank you so much uh for watching the videos guys and uh stay tuned see you guys soon bye
|
Frog Position After T Seconds
|
number-of-comments-per-post
|
Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.
The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`.
_Return the probability that after `t` seconds the frog is on the vertex `target`._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** n = 7, edges = \[\[1,2\],\[1,3\],\[1,7\],\[2,4\],\[2,6\],\[3,5\]\], t = 2, target = 4
**Output:** 0.16666666666666666
**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after **second 1** and then jumping with 1/2 probability to vertex 4 after **second 2**. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 \* 1/2 = 1/6 = 0.16666666666666666.
**Example 2:**
**Input:** n = 7, edges = \[\[1,2\],\[1,3\],\[1,7\],\[2,4\],\[2,6\],\[3,5\]\], t = 1, target = 7
**Output:** 0.3333333333333333
**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after **second 1**.
**Constraints:**
* `1 <= n <= 100`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `1 <= t <= 50`
* `1 <= target <= n`
| null |
Database
|
Easy
| null |
771 |
hi my name's david today we're going to do number 771 jewels and stones it's a easy level record problem and the language we're going to use to solve it is will be in javascript so it was a fun one it took me a second to understand what's going to be asked though so basically you get uh you're taking jewels and stones so you get a string of jewels and a string of jones stones and inside of this you have each character and you see that there's three of these inside of stones so a lowercase a is here once and then uppercase a is in there twice so that'll be three in total and so the second one lowercase c there's none of it so output is zero and it's case sensitive so basically how we're gonna do this we gotta keep track of all every characters inside jewel strings and match it with the stone strings and the a good way to do this is to create an object so let me do the pseudo code so first thing you want to do is create an object create map object and next we're going to create a variable object to hold the output create output variable okay so that's just to get started and next we'll have to loop through the jewels string and as well looping through what we will need to do is that we'll need to put every character of this inside our map object so we set we uh put every character put each character of jewels inside of map and basically how we do that is that we set it set the value equals equal to true so that's how we're going to do that inside of the loop so now this map object has all the values that we need from joules and next we have to loop through the stones string and i see that we create a condition create condition if the value of the index is true inside of is inside the map of the map and then if it's true increment output if true so that would match it as we wanted and lastly we'll have to return output variable okay so first we create the object map next we create the output variable and it starts at zero afterwards we loop through the jouser string okay and inside of this for loop we will have to set the update the map so we have to do map joules so that will get the value and you get true and now we do the next loop for let j equal zero j is less than stones dot length j plus now we have a condition if we're going to change this to stones and change that to j is equal to true so if it's inside that object we will increment the output and lastly return let's check nice so that the complexities the time complexity will be of and since we're doing loops but these aren't nested and also the space complexity will be o and because we have to create this hash table to store everything thank you
|
Jewels and Stones
|
encode-n-ary-tree-to-binary-tree
|
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.
**Example 1:**
**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3
**Example 2:**
**Input:** jewels = "z", stones = "ZZ"
**Output:** 0
**Constraints:**
* `1 <= jewels.length, stones.length <= 50`
* `jewels` and `stones` consist of only English letters.
* All the characters of `jewels` are **unique**.
| null |
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
765
|
67 |
hello world today we're doing problem 67 at binary this was a problem given by tesla so let's see what even musk actually wants from us and is it too crazy i'm gonna remove that and let's read the problem given two binary strings a and b return their sum as a binary string that's pretty much it so what we should do now is hopefully write them down and think of a solution if it's going to come to your mind now probably you're not going to get with the solution at the first glance but what we can do is just put them down and just go through it on a pencil paper or just you can do it in notepad it doesn't really matter what is going to happen if i place one at plus sign here and i place one on the bottom now mathematics are the same doing that in binary hexadecimal octa it doesn't really matter you can just put things down and once we actually hit the 10 mark then we have a carry this is going to be in decimal and in binary one we once we hit two then we have a uh did you go to carry so pretty much this doesn't change if i actually take this one and one i can start summing them up if i sum one i'm also going to get two which is going to be one zero in binary since i cannot place this i'm just going to take the first part i'm just going to place zero and then one is going to be my carry so i'm going to have a carry and i'm gonna type it here so we don't forget it's going to be equal to a1 as soon as we move here however one plus zero but we have a carry i'm just going to add here this is going to give me the same result it's gonna be two so one zero i am going to add the zero and of course i will have the carry finally i don't have anything to do and i just add the carry which is going to give me 100 number and if you have to think about binary you do it like this 2 to the point two to the second is equal to four that's pretty much it now i will go through this example as well but i want to show you that it is nothing really more than just let's say 97 plus 5. here we have 12 and i am going to write this 2 down and i'm going to take the carry 1 that's going to be my answer i'm taking the carry i'm placing it here then i get 10 right but i cannot write 10 i'm writing 0 and then i'm left with another carry 1 i'm writing it down here and i get 102. mathematics don't change so whatever you do don't just panic write it down think about it and we're going to come up with a solution and just to be completely full let's write down the second example one zero one and see how is this going to turn out this here obviously we're not going to have a problem it's going to be simple one here however we're going to get two which in binary represented is going to be o 1 actually not a 1 o that's why we're writing the o and we're having a carry of 1 as a size zero plus zero is going to give me zero obviously with the carry one i'm just going to add one is going to give me one zero again so i'm just going to add zero and have another carry of one and finally just add the carry because i have nothing else to do and as a result i'm ending up with this number 10101 which is this and if you want to see it's in binary it's going to be 1 plus 4 plus what is this 16 so it's going to be 21 if i calculated that correctly all right well let's see it in code the code is a bit difficult to understand i'm going to go through it quite extensively but just embrace yourself probably you're not going to understand it in the first try so you can always rewatch the videos and if you have any questions leave them down below and of course subscribe because otherwise i'm not going to be answering your questions all right let's go the first thing i want to do is just going to say first string index i want to iterate through both of them and get the numbers one step at a time calculate them create a sum create the carry all the things that we have been talking about just as of now in order for me to calculate the first string index i am going to say a length minus one same thing i'm going to do with the second one so this is going to be int second string index this is going to be equal to the length of b minus one obviously you get it we are going to the end of both of the strings that's why we are having a length minus one here okay now we need to take the carry which is going to be zero at first of course and the sum which is going to be zero at first of course finally we are expected to return a string so this 100 is not going to be a number it's going to be a string and that is why we're just going to say string result which is going to be an empty string at first in order for us to do the loop i just want to make sure that both of them are bigger than no bigger than 0 because that means that we still have something left in these so i'm going to say well first string index is bigger or equal than zero or of course the second string index is bigger or equal bigger come on bigger or equal than zero yes good now here i'm checking both of them because if we go to the end of the first string as you can see here a is two characters and b is one it doesn't really mean that i have finished the calculation so i need to go further on that's why i'm checking them now i'm just going to say at the beginning of the loop make the sum equal to the carry in the beginning we're not going to have anything carry 0 and sum is 0 but at the later times we will have carries and that's why i want to start the sum with one this is the same thing it's nothing more special than what i showed if we have 97 plus five here the sum is going to be 12 to one and i want the next sum to start with this carry so i'm just going to say one plus nine right because i have the carry good so some is going to be equal to carry then i need to check couple of things now this is a more interesting part and i will explain it as well the first thing i want to do is to check again if first string index is bigger or equal than zero now i'm checking this because here i am allowing for something to be zero when i have this it means that something down there is going to be zero so definitely i need to check it so i do not break my program equal to zero then i'm going to do sum plus equal and here i'm going to say the first string which is going to be a and of course the first string index parameter which i'm going to be using minus and then we have 0 over here i'm going to explain this just let me write again the second part the same thing we're going to do with the second so if the second string index is bigger or equal than zero sorry for typing i have a bad finger currently sum plus equals and this is the second string which is going to be b and here i had to rename them but let's leave them like that now second string index minus and of course we're minusing the letter zero now why are we actually doing that um i'm going to go show you the ascii characters and hopefully i'm going to find something oh yeah there we go so one thing that i want i'm going to back go going back in lead code in a bit but i want you to note this thing over here i want you to note this right over here actually let's make this red because it's quite important here we're going to see that 0 is actually 48 in ascii and 1 is going to be 49 so what is this actually telling you if i'm getting in let's say character 0 or in our case just remember this now because we're going back i'm gonna type them so ctrl control w and here we set that 0 is going to be 48 and 1 is going to be 49. now i cannot say sum plus equal character right i'm not able to do that i am required to have an integer in order for me to create this integer i'm going to take the letter which is going to be let's say 1 and here we're going to have an ascii representation of 49 and the 0 representation is going to be 48. so as soon as i say minus this i am left out with one which is going to be the proper result the same thing actually is going to happen if i have a zero this one in ascii is going to be represented as 48 and when i subtract 48 from it i am going to be left with a zero so that's something that you need to keep in mind that's very important all right moving on forward this i think was the hardest part now what i need to do is to check if carry is equal to sum so let's say is sum bigger than one if it is then i have a carry of one if it's not i'm gonna have a carry of zero the same thing once we actually do since these are the numbers i am going to calculate f1 plus one this is going to be two meaning that i'm going to have one zero so i do want the carry to be i'm checking is the sun bigger than one if it is then take one inside the carry pretty much that's it and then i need to put it in the result plus equals and here i'm going to say sum modulus 2 and dot 2 string because obviously i want to return string as we all have we have already mentioned over here now i'm saying modulus 2 because obviously we're working in binary we don't want anything else so that's why i'm saying modulus 2 here all right the final part now is going to be a bit more different at least in c sharp and it's going to be a bit more different in c sharp because we're having c sharp specifics so i'm going to first check to see if the carry is emptied out so if carry is bigger than zero i'm just going to say result plus equal carry dot to string obviously at the end of the loop i'm saying all right do i have one as a carry as we have seen so here i believe it was you can see here and actually you can see here because once we actually finished the calculations we were left with 0 1 and i'm basically adding the carry here at the end and our case is going to be in the end but we want it to be in the beginning over here that's why what we need to do is actually what we're left to do is to reverse this string that we have been building now that's interesting because in c sharp you cannot just say dot reverse you need to actually write it strings are immutable and that's why we first cast it to character array and then we actually reverse it so in order for me to do that i'm going to say private string reverse and i'm going to pass a string i'm going to call it s now in order for us to reverse it's very simple really we need to cast it to a character array so this is going to be char array and i'm going to call it char array it's going to be equal to our string to char array function all right slick then i can just say array dot reverse and i can reverse the array which array i do want to reverse this one i'm just going to paste it here and finally i need to return it but i need to return a string of it so i'm just going to say new string of our char array that we have already reversed and that's pretty much it so what's left for us to do is to actually say return reverse and then we're passing the streak we want to reverse which is going to be result and here actually we're passing return reverse because reverse is returning something on its own so that's going to work out let's run the code and see if it's going to work because this video got a little bit longer and let's now send it to the server all right that's it so congratulations on passing your tesla coding interview the final part to talk about is of course time and space complexity and as a space i am going to say i have a linear because down there i was creating a whole new string time complexity nothing fancy again we have linear and that's pretty much it thank you for watching if you have any questions leave them down below and i'll see you in the next one bye
|
Add Binary
|
add-binary
|
Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` characters.
* Each string does not contain leading zeros except for the zero itself.
| null |
Math,String,Bit Manipulation,Simulation
|
Easy
|
2,43,66,1031
|
112 |
ranked 112 paths some come in a binary tree and a some determinable tree has a root to leaf path such that adding up all the values along the path you goes to given some believe is an OBE of no children below given a below tree or some and your journey to returns true ok time I think this is tray foolish yeah let's just kind of do before somebody is supposed to be easy so yeah force and then just be turn I guess is self-taught then just be turn I guess is self-taught then just be turn I guess is self-taught it's still recursively array because that's the cool thing to do maybe so - that's the cool thing to do maybe so - that's the cool thing to do maybe so - yeah negative numbers I guess technically could go either way I could do it this way but I think two edge cases we have to be slightly different turn true and then what's the other educates I was bringing up just technically okay you stood viewers will know that I'm doing the same thing twice but the or should early terminate so maybe that should be okay that's kind of the one it real quick are there more examples I guess not so that's well this is tester empty example which I'd like to do Oh actually I misread to so move so I think this would have been more because it's rude to leave not just any subset so we have to check but that's not a hard thing we just have to check that here we just have to move this oops and this is one two here and then that should be it because that's a test another case then I just say you know actually used to an example Pope of a different some that's we wouldn't look for five which is the route if we terminate early this would give me a force and it just terminates late then there should be a true so I'm gonna see which one we get yes Sony but be monstrous I mean usually I type these pretty quickly so that's why I'll go over afterwards for sure well I knew that I was I meant to test that case but that touch is the silly edge case okay fine how do I only handle this case in a good way that what I think the cocoa thing I would just wanted to do was just keep everything in one function but that's not necessary by the way it's just a it's literally just a cool thing to do but I guess I can really handle this case if I were help I don't think of I don't think I have one anyway okay I mean you're someone like Testament so my god but then you have to do like hey what a silly thing I'm doing for in that case I don't that there isn't this am I doing this wrong well maybe I'm thinking of five Hunter syntax considered dangerous force it not so this is force why is that visited bad to fine huh okay I should think that cuz that's not important oh I'm just being silly that should be a strength obviously so I would clarify that on a contest for someone like that I would definitely do this in two functions I just wanted to be cool like you want to cool kids let's see if I get another silly mistake oh I don't know what that tree looks like okay maybe I should step back a second babe an estimated how silly I am I thought I'd test with that case none because it goes to the right path oh okay let's just rewrite this I try to be too cute and try to get everyone function but I didn't need to do that so that's let's refresh this real quick okay so let's check if food is none and we turned for us and now if let's see if this is a leaf dammit if this is none and we just none we checked it so if some I guess we just returned some zeros but first we would - returned some zeros but first we would - returned some zeros but first we would - which McCoy would Y you otherwise then we checked the laughs left in the way okay I guess I'm still doing the same finish right maybe this is Queen let's don't put my mistakes by copying this case I guess I already did okay so anytime game progressively better let's just drink the criminal pawns this just looks like a pug okay cool yeah so just general silliness aside me washing that one to be fair to be honest so take that me take your time so I should be an interview I think to be honest if I was doing this in a contest prom I might have still washed it and got some of these educates as well because what I did was I checked when one of this child is known right one of his challenge is none but as bogus children should be none so I never watched that one because I just this is where you warm up way because you wanted to silly treat things but uh thanks for the photo for no Cucuy end of that game with an n64 right yeah so this is a quad-core you see problem and it is easy quad-core you see problem and it is easy quad-core you see problem and it is easy it's just that I'm silly a lot of votes on this problem yeah there's a three problems I definitely recommend yeah I'm gonna interview ice with every study these kind of problems and get practice people interviewers love these kind of problems are interviews so I definitely you know I don't think I have that much space for opinion just because you know your interviewers love these problems so yeah it's just about it what it is and it's all about recursion and yeah it's restructures up very easy to understand recursion do you understand maybe that's not just like easy to illustrate type of recursion so yeah definitely although that I explain like your five on this one yeah so basically the idea is that yeah recursion is the big idea which is why this is a popular interview question and the idea is that okay you start with looking at the top node where the sum is 22 so then you just look okay it's just a leaf now so then let's go down to one of the leaves and one of the children which is not necessarily and then see if you could get to try it too here well you are you still looking for 22 can't just know right because Joey have five on the top so it's gonna be five less so then now is 17 so let's go this note and be like okay from this note is there a route to leave with the sum of 17 then so forth and then you can keep on going down until at the very end you're like okay wow this is a leaf it's still and there's no children you check there's no children is to some sewer because now you know like all the math or were they even Dow and that's kind of the idea behind it yeah in terms of cleanliness the code cleanliness I guess I could just slightly better by mean this is mostly okay pretty straightforward ish yeah Anna Pascoe for stuff like that I had a functional programming in general so that's kind of you know it's a big fan of that well yeah I mean as I said I think for this problem you I would very much expect this to be an interview so definitely practice until you're very comfortable with problems such as this so that I think that's all I'm gonna say about this one otherwise it's yeah just recurs you know and we know they've been going for it cool
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
1,096 |
rotations okay and their grandma given below shrinks Emily can represent a set of lowercase first let's use all of expressions they know their set of words the expression represents okay grandma can be understood by some more examples single letters represent a singleton containing that word okay I mean I guess that's okay let me take the common delimited set up two or more expressions we take the Union book two possibilities so okay that seems reasonable ish for now you should have read all these questions but this is the know bit wordy so I'm just gonna I mean there's a link I'll link it again later upon request but no they should have to number of topside one you know I guess they don't make it to be me anyway we can cat it can carry two expressions we take to set up possible concatenations between the two words where the first which comes from the first expression and the second would come to the second expression man whatever I had for lunch tune up you guys go second okay so kind of like a course product essentially I or was it a Cartesian product right it is what we're doing you that's when you can candy two things formally the three words of our grammar okay yeah okay Gemini smelling like return the sorted list of words that expression represents oh man okay I mean this and feel it doesn't seem too tricky I'm just trying to think about it I mean in concept nothing is drug yeah I think I understand the question is what I meant understand the problem but now I'm trying to think what I within the bounds were and you already have one and these could kind of go recursive oh god this is just a set of that yeah you don't make me type John mmm-hmm are there multiple mmm-hmm are there multiple mmm-hmm are there multiple concatenations when we concatenate two expressions okay how does this combined with the gh it's at the shop so just I guess this is just to do it and a tutor to it which is a right mm-hmm okay right mm-hmm okay right mm-hmm okay and I think uh you know the thinking of just doing it naively but I also would you know I think there's no I mean yeah Mia no I wouldn't say no dependable you mean by now if they think just like parsing and recursively and generating may be the way to go I think to sing this is a really weird expression actually but what we're just trying to think yeah so I'm just trying to think what is - so I'm just trying to think what is - so I'm just trying to think what is - okay let me step back - second better okay let me step back - second better okay let me step back - second better that's the first thing I think of is maybe just doing it naively in some sense of the word which is just - like sense of the word which is just - like sense of the word which is just - like the posture expression and then just do we go so they I think the only reason why I kind of say that's good is because or possibly good anyway it's because well you have to output not just a number of expressions or number of words rather sorry number of words but you have to actually output the words so if so in general if the result is too big then got like there's no easy way to get around it like you have to be turn out an entire said anyway and after that I think it's just I like for this finger of diamonds C sharp or Java and just use my code of expressions but maybe that actually gets me in trouble so maybe not yeah we could just play yeah I think there's no easy way to do it's just I just have to do it I'm just trying to think about ways to quickest way nothing there don't want any ambiguity with expressions I think like you could just use any old language maybe then just parse the expression I think one thing that they let me think about what are the other cases that I can look at like for example can you do so you do something like recursively like so someone like that effectively means oh that's why not coloring is a little bit alright is that way so you don't have to do some kind of like because of ex questions but that's fine yeah I mean just no way around and then you're so messy anything like this okay Tammy China hey I just wanted to do something quick although the zoomin nightmare to test fit okay it was the first one that I want to do they're given a next question mmm I just do it kristef assistant yeah okay I mean I got spend enough time not doing anything mm what is setting she shot her sin never miss mr. chin hoax yeah also satisfy not for your keyword yeah I know this isn't we will fixed and in the face of a reason why I have except relators because I might do some other stuff here very well the first characters just chop it off we persevere just minification I always have to change her that's fine oh yeah merge I mean the thing that to they'll always trick just a new annoying is that there's no explicit operator I guess you century actually maybe that's what I should do should have done to begin with Miami we calculated yeah okay maybe I should have pre-processing okay maybe I should have pre-processing okay maybe I should have pre-processing in the first place because I think that was the part that I was always having a little unclear with Jen bigger really I mean yeah okay not sure no cuz you do that it's always the case I don't know if this is actually necessary to be honest but uh but it makes my life I feel like it just makes my understanding but it now actually I've got an output this my missing listen by calling something not a reduced and stuff here that's not great I can't sometimes I don't they yeah I think I'm using Java stuff better No which one is yes darling why does that be language to microwave a little strange no I'm bad at this no that's fine okay so if that's what I wanted to do okay now I can kind of just use a much more assembler maybe it's a good still people inside so by the way delete oh that stuff okay well it's fine there's quite this for you that was my bad after also handled test case for example where I would totally just skip it hmm there's so many edge cases maybe I could do more it's obviously the case I'm thinking about and there was just one for example because yeah we just don't really handle it right now so now we're just worried about stuff on the tips zoo well which I guess could contain these things I guess I'm not to care about maybe I'm gonna commerce first you back ambolyn pushes in try to figure out what try to drive drinking the same one thing if I could just waiting more naively and we'll talk about complexity and select our data not bad is such a mess oh my god okay yeah I just need to figure out well like I won't notice okay well yeah we were just took one operating at another time okay yeah okay fine yeah that's no you won't be Magister maybe that's especially in that case I don't need you know I need to do it this way they might be on a different tab I said he took give that case no okay well you find the first operator that is undone sewer Oh I was it called don't make sure that's my rational otherwise that's not the case and we'll find it first depth civil operator you should be a set yeah I'm in the corner of things and if I know it well this farm is that it's probably little tricky to test incrementally so something I have to do love debugging later maybe two because I could just have done mmm I should purchase that any tip he knows I'm going to I'm just talking out we don't want the memory issues we create so many strings here gents yeah I just mmm 12800 blame them musical concert I did have happen off-by-one suavely tennis okay I'm happy that also different dishwasher is a little off making progress quite let's just take so long they have not changed lately that's one okay so I just need to fix this Oh which I tell them I actually expected a little bit okay nothing I just don't have a base case which is actually yeah because then I can't find anything one I've got your wife saw earlier Oh actually didn't expect it to be sorted so I might you might not actually be sorted in the end it's just like a little lucky of that one also what wait for it to be actually white first baby we made some progress right we got the first test correct you know what they say getting the first test correct is the key step on getting the second example test case correct okay that's good it's Riedel son stuff it's a shortcut here expressionist done didn't know operators and no friends I guess I should also have no cost per inspection that's the same job that's fine mmm Oh mostly if I may be a bit do you want to get into signs you better stick them in forever mmm-hmm there's a big one that's fair I mean this just plum kisses I should I told about this one earlier by forgot okay expression is not time so the two cases that I have to look out for them one is this case I think the actually it should tree or even just by itself if not there I should figure out why not okay and in the other case which is discipline the day in a black mm like maybe felt on the first one so he doesn't check the second case action um now how many coal structure this okay so the post is here what I can do is just put in some additional Cartesian product things maybe I mean there's a weighted it I mean that's not the wall but make sure I get away I hope this is efficient actually I'm much with that it is and I know that missing together one day and because I tested the other case first okay yeah I think I got lucky on the fact that uh I guess there's a c-sharp fact that uh I guess there's a c-sharp fact that uh I guess there's a c-sharp cap it's character thing for every one of them to just too late come in it I'm lucky that are the places and stuff like this is before there are asking why you would just buy that thing work pays to a little bits lucky that it not look well oh I think actually my this is just one that's why because tear cord is also a little funky on it - more right hmm true well I'm quite that I found something that I'm actually I was wrong about but that's unfortunately oh because that's actually just one because the comma takes precedence on a tap yeah because actually when I actually caught an edge case because even if you have someone like a pea like what Michael does is actually it takes this and then it caught a shin product before it is and I think it should do the calm of food yeah we've W to become first all kind of me it is but that's okay maybe if I actually just do the same for me once again I didn't care what order of operation in business what happens lokah also mine stuff is not sorted which actually I expected and I don't know I didn't come out earlier so did okay so just have look what happened like and I comparator thing I'm just lazy I don't even know if so what actually returns in their way value yep yeah okay hmm make sure I still have the first one correct and also the second one because I found every place to have some other stuff that's not looks okay fingers cross and it just takes too long I don't know maybe I'll give it okay cool thanks for staying with me of you're still here John I hope you're happy I mean it's uh I mean this is a language construction I think maybe I do I had to take a notes yeah I mean I remember usage I mean I don't think it's just the size of input/output right so I don't size of input/output right so I don't size of input/output right so I don't know if I could do that much faster but how I guess is that part is - party time how I guess is that part is - party time how I guess is that part is - party time huh and certainly this computer I don't care about that per se yeah I think yeah so this is a language passing bomb I think it's an interviewee it comes up I'm not gonna be happy about it but I could see it coming up to be honest this is the way I would say it could plumb necessary but it's not a bad palm is a reasonable problem I think I mean maybe just not like to my shrink like I'm a little biased about it but I think is a reasonable qualms to be asked on this or some variation of this hour in an interview in it because this is there's not that much my car there's not that much algorithmic things to consider but it is a good problem for kinda demonstrating uh you know your programming capability oh my god this is 29 yeah shorter than I expected I just been a while since I've done these columns so I think I should be reasonably expected to code this up in good time maybe slightly use the version of this there is some like I would think this is a intentional culture which is like a little harder to kind to certain things they're definitely like slightly simpler world especially you know for kind of just making sure that we stay in is correct time like within the hour range search of you takes you like 5 to 10 minutes to just understand the problem so I will try simplified some of the language a little bit so that it could decode in time and but in this way you know like an own oh it's cool computable Rand Paul I think in general I would not ask this with any real questions it's just so many things you know wrong and also I think I would like to type of problems where you've just sit if you're a little off course you could still get onto the right path we're here it's relatively straightforward but there's a lot of like little off by ones and things to where you can't trap there's the viewer and then to be like it's hard for me to be like oh you know maybe you know you just do this one little thing and then not you know idea and because it's just all coding and sometimes you just I don't know like miss some something in this space somewhere and like you know maybe you have a typo and this comma is a period because I just type in and that could usually take me like 10 15 minutes to debug way so having on the level difficulty and stuff like this is okay I mean I think the next question that you may I just like what's the complexity and space over the space for me is gonna be output sensitive meaning it just depends on the number of whatever way that said you can imagine something like I should have done this a little bit earlier so that to pick more queer about but you could see imagine something like some like it's like quite this but someone like this where that I've got and four fifty it's just fifty three by three which is 17 say so seventeen and then well that's that way but you could do something like that actually like I meant to write something like this like basically to 2x where Jesus five with fifty expressions or where the number of character is fifty so that's ten so you could have two to the ten which is you know about 1024 so they're only ten twenty four-hour putteth want to say stop four-hour putteth want to say stop four-hour putteth want to say stop rubella I've done this analysis a little bit earlier I was just I didn't notice it I just didn't really think about it too much so you know a thousand uh it you know it should be too bad I don't know how you want to pound that I guess technically is - I mean it's technically is - I mean it's technically is - I mean it's technically two to the N over five yeah which fun fact yeah but um something like that yeah so complexes so that's the running time complexity also because that's just an output and you have to one at least half sizes so every to the N where n is 50 but not really because is a cuted and over five and then and also that way too so that's the maximum output but also you're also bound depend how you want to do the math each character because you're only each character will look we've looked at or n times because as you kind of partition them you only read each character at most n times right so be n square so you can bound it that way as well though is in this case it's not as tight bound because of the programmer sees and the operators that makes it kind of that takes up more space than n square strictly someone like that but it isn't this case because it makes it like you know tune in time oh yeah so in short I think I mean I don't like these kind of problem it's kind of sometimes but I also like reasonably would expect just to be and this is a little bit on the hotter side for an interview but in general like these kind of problems or in interviews so
|
Brace Expansion II
|
maximum-sum-of-two-non-overlapping-subarrays
|
Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") = { "w "}`
* When we take a comma-delimited list of two or more expressions, we take the union of possibilities.
* `R( "{a,b,c} ") = { "a ", "b ", "c "}`
* `R( "{{a,b},{b,c}} ") = { "a ", "b ", "c "}` (notice the final set only contains each word at most once)
* When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
* `R( "{a,b}{c,d} ") = { "ac ", "ad ", "bc ", "bd "}`
* `R( "a{b,c}{d,e}f{g,h} ") = { "abdfg ", "abdfh ", "abefg ", "abefh ", "acdfg ", "acdfh ", "acefg ", "acefh "}`
Formally, the three rules for our grammar:
* For every lowercase letter `x`, we have `R(x) = {x}`.
* For expressions `e1, e2, ... , ek` with `k >= 2`, we have `R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...`
* For expressions `e1` and `e2`, we have `R(e1 + e2) = {a + b for (a, b) in R(e1) * R(e2)}`, where `+` denotes concatenation, and `*` denotes the cartesian product.
Given an expression representing a set of words under the given grammar, return _the sorted list of words that the expression represents_.
**Example 1:**
**Input:** expression = "{a,b}{c,{d,e}} "
**Output:** \[ "ac ", "ad ", "ae ", "bc ", "bd ", "be "\]
**Example 2:**
**Input:** expression = "{{a,z},a{b,c},{ab,z}} "
**Output:** \[ "a ", "ab ", "ac ", "z "\]
**Explanation:** Each distinct word is written only once in the final answer.
**Constraints:**
* `1 <= expression.length <= 60`
* `expression[i]` consists of `'{'`, `'}'`, `','`or lowercase English letters.
* The given `expression` represents a set of words based on the grammar given in the description.
|
We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it.
|
Array,Dynamic Programming,Sliding Window
|
Medium
| null |
92 |
Hello everyone welcome you are steam bomb so you are going to solve a problem since this is reverse de notes of list from position left to right so we must have been given two positions left and right something like this and we have the notes in between these. The links have to be reversed. Okay, if you look carefully, we have a link lace. 1234 Note the links between 5 and 2 to 4. 234 If they have to be reversed, then how will they be reversed? 432 Okay, so this problem can be solved. Before solving, if you have not seen that you are reverse a link list, I have a whole link list, then please watch the previous video, you will understand it better, then you will understand this problem. Okay, one more thing to pay attention to. The one is that when we reverse the links, the head is our first note and there is no note before the head, so when we reverse, we take two variables, if you remember, previous and Current is the value of current in the head and value of previous is in the value of previous because there are no notes before the head, so if you look carefully, we have to reverse this link list and before that the note is present, so now the new one will be previous. There will be a van and a new head, you will be ours, we will assume that and hence if we solve the problem, something like this will come 234 This is what will come from both, this is right, so what is our old will become our oil and what was our old oil will become that. Our head will be created and once we reverse it, the next point of our note which is on the left - 1 position will once we reverse it, the next point of our note which is on the left - 1 position will represent our new head and the next point of the new oil will refer to our note which is on the left plus one position. Just keep this in mind, let's solve the problem, it will give us new head and previous. Okay, so if you are left, then head will be our tu, and previous will be our van, and left is equal, you will be three, then head will be our three, note and previous. Our tu note will be something like this Reflexive = 1 means if we want to something like this Reflexive = 1 means if we want to something like this Reflexive = 1 means if we want to reverse from the first note then our head will remain the same and the new head will be our na Right L count equal tu we will outlet and we will go from left to just the first one. We will make the note on the left as the previous one and we will make the left note as the new head. We will make the reverse function. This is just like the reverse from the reverse as we write, you reverse hole after link list, so here we pass the head. New head, previous left and right, so head, this is our head which we get from here, this is our head and this is our new head, which we will get from here, this van and the previous one is done, so new comes that we have taken the value which is from the current variable, we have made the previous one. To reserve a variable, we created a variable called ' To reserve a variable, we created a variable called ' To reserve a variable, we created a variable called ' Previous Race' in which we did the OK Previous Race' in which we did the OK Previous Race' in which we did the OK account with the value of 'Previous', 'This is equal to you left', account with the value of 'Previous', 'This is equal to you left', account with the value of 'Previous', 'This is equal to you left', then whatever number is on the left, we will start from there and till where we will go, ' Previous is equal to this', 'Current is Previous is equal to this', 'Current is Previous is equal to this', 'Current is equal to this, next and Will implement the count from van then what will we say when everything gets reversed then new head dot next is equal to current ok new head dot next is equal to current why is we look through this example then in the beginning when we Here we will pass the thing head new head previous left right then what will be the value of new head because it is on the left position right now the value of previous will be one and so when we have reversed it and when we have done I trade of current What will be the value? What is the value of current? So what is the current? This means who is doing our new head? It means that our love was N. Here it means that we had to reverse the note number from van because when the note, this will be our first note head. What will be their usage? If it is non- What will be their usage? If it is non- What will be their usage? If it is non- right then it means that they had to reverse the note number from van. In this case we do not have to do anything because our pre variable gives our last note and the last note will be the head of our reverse link list. So we will return it and vice versa. If the previous one is not there then it means that some notes are present even before the left position. So what do we call the first note of that. Suppose here if we reverse it then 1 2. 3 4 5 So what was the value or what is the value of the race? The van note. So now that we have reversed this part, 2 3 4, we made it 432. Now what will we do, whatever is the head, we will make the last note the head. so next is equal tu hell
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
444 |
hey what's up guys chum here again so today let's take a look at another leaf called the problem number 4 sequence reconstruction it's a medium problem as you guys can see it because a lot of downloads even I gave him gave this problem a download but still I want to talk about this problem because this is like it's a Sun it's just something that I want to talk about ok so it gives you an original sequence from the range is from 1 to n right it's the from the 1 to the length of N and it could be anything it's a permutation of the 1 to N number okay and then the second parameter is the sequence tells you the from like you have to have you need to have one first and then to right and then here it's like 1 & 3 you need to have so here it's like 1 & 3 you need to have so here it's like 1 & 3 you need to have so one comes before 2 and 1 comes before 3 and it asks you to return a boolean the check based on this the sequence the given sequences can you uniquely reconstruct this already arranged in sequence number here alright for example here right the sequence is 1 has to come before 2 and 1 has come before 3 can you reconstruct 1 2 3 right no right because all we know is that one has to be before 2 & 3 but between 2 & 3 we don't know 2 & 3 but between 2 & 3 we don't know 2 & 3 but between 2 & 3 we don't know which one I mean well we'll come up first right so that's in example 1 here and example 2 here is that you know this is called it's obviously it's like it's not going to work right because the sequence doesn't even come could include all the numbers here right basically if the sequence doesn't include numbers in orange or numbers basically there's no way we can reconstruct right and the third one is this yeah so basically the number three is the like is the correct version of number are the examples three to correct the version of the example one here so besides is one two one three also gives you a like another sequence between two and three so in this case we can reconstruct one two three from the sequences here right so this is obviously like a graph problem right because for example digit is one here and so from one from the first element or the second element we're gonna have a directed graph here right one two and one two three all right and 23 right here so and under for example this one there's one two one three and two and three okay right so that's the graph so and asked us to chart if we can uniquely reconstruct this right so what we can do is we can use the like to Paul topological sorting topological sort right you know for the topological stored one way of doing it we use a like an integrate in the would increase integrate dictionary and we're in the integral dictionary so we always towards the current zero integrate node right and how can we use that to solve this problem right so as you can see here so if you think about it so let's say there are if there are two elements in that in if there are two elements in that either a zero degree kill here right for example in this case let's say there's no this edge here so once we have once we remove the but once we remove node right so both two and three will become zero integrate right so that's how we can use utilize this kill to help us determine if there's a unique topological sort right so anytime if the queue if the length of Q is greater than one right then we know okay so currently there are like more than one node in the queue which has the which have the zero in degree which means we can process either of them right then it tells us there's no uniquely unique reconstruct or unique or topological sort for this problem right basically that's the main idea and other than that it's just a few bad kid I don't know if it's a bad cases or the description was kind of ambiguous here that's why it got a lot of votes here because here it kind of makes sense right because it's we only giving like one hand to here but you know they're like some really weird test cases here for example if the first orange in the order is one right and then the sequence it gives you like sequence it's like it's - it's not even like it's not even it's - it's not even like it's not even it's - it's not even like it's not even part of the notes here right I think it is B it is because this problem it doesn't tell you it doesn't say it's a graph problem right so there's no guarantee in that the sequence you cannot assume that this sequence given here it has is it's also all of the sequence given here are part of the original sequence number right it could be anything right in this case you know because the reason with that computer is because we are trying to convert this problem into a graph problem and in a graph problem we're always thinking okay all the numbers has to be in this graph but in this case that's not it's not always the case right for example this one I mean the graph only has one node but we're giving like edge here right probably with two here graph two here and that's one case and another one is this let's say there's a one here right and down the on the sequence here we are given like one two minor minors nine okay and then one two minus eight right it's also possible right it doesn't because it doesn't the that it's not only limited to the notes two numbers within the orange in a sequence right it had its it can be anything basically so that's why in order to handle this kind of case right so basically where we have to be limiting all the numbers other numbers like we have seen so far in the sequences is part of the original sequence right otherwise we can simply return a false because we know there's something invalid here right so to do that I'm just used simply using a minimum and a maximum and maximum numbers to compare fits the minimum in the maximum in the original sequence and our and the current sequence list here if either of them is not the same then because another thing is that in order to reach uniquely reconstruct out the sequence here basically all the numbers for example here are the numbers in the oranges no numbers has to be appear in the sequence number six right because otherwise we don't know the sequence right so that's why I'm using a minimum in the magic numbers to consider to reach constraint the output and okay so it's that being said let's try to code here and works right so like I said I'm gonna finish the graph here so the graph kind of either dictionary is going to be released and I'm gonna have an integrate dictionary as well so it is like default dictionary in here right and then I'm just going to look through the sequences here I saw the sequence in sequences all right and then basically in for example is this like this list here right so basically everything from the first one to the next one for each of the combinations I'm going to create a other critter edge in the graph for example this one 5 2 is add 2/2 6/6 2 3 is this one 5 2 is add 2/2 6/6 2 3 is this one 5 2 is add 2/2 6/6 2 3 is also a rash right okay so and that's why I'm not gonna graph okay so for right for i in range to the length of sequence write a minus 1 because we always be moving to the next one to make sure it won't all be out of the boundaries so that's why I'm doing a length minus 1 here and then the graph dot so the start is the current card number right that's the I write and then the end to end is the next number basically sequence I minor a plus 1 right same thing for the in degrade right is integrate simply just the next one right so it's the to note plus 1 I plus 1 and kind of plus 1 right that's the how we construct the in degree and like I said I'm gonna have like a minimum and a maximum value here at minimum number maximum memory cost so sorry the minimum number I would have to be initialize it to the max size and the man some member has to be a okay alright so basically every time here right we just simply maintaining this minimum and next number that we have seen so far in this all sequences here right so minimum are going to be the minimum of that of what after minimum number we have seen in this sequence right so we can have a minimum of the sequence same thing for that maximum number right maximum thanks alright so that's how we maintain the minimum maximum Bursa and here before doing anything we can simply do a check right if minimum number is not one right or the max number is not equal to n right then we simply return false because we know then the sequence is not valid right so okay so once we finish that checking now it's safe we can finally get down to the real topological sorting algorithm here right basically we create a queue here right so this is like the cute hold dear all the nodes that have the zero integrates right to start with we have two collections EQ right and then I'm gonna start it start with base T what is that C sequence that's a good number okay for number in range right in range one class and I'm plus one because the note that ranges from - Ellen right that's why I'm to start - Ellen right that's why I'm to start - Ellen right that's why I'm to start with I just need to get the current zero in the green node which is the ones that does not exist in this in degree node right because anything that exists in the current in degree no that has in degree value rights and to think thinking in the opposite way that anything that's not in this integrator has a zero in degree okay if not in integrate all right and now for a while queue here right so like I said I need any time we do a track if the length of Q is greater than 1 then we simply return a false here okay and then note equals to Q dot pop left right and then for the neighbors right for neighbor in our graph yeah and graph no yeah I'm graph node here and we'll be removing the integrase from that right in the gray neighbor minor we decrease it by one and then we track if this in degree is become to zero right of this current node never know this is equal to zero then we can simply add this add the final one yeah we can simply append that this neighbor to the Q here okay and then in the end yeah in the end okay sorry so how can we check right how can we know if it can be reconstruct to the correct answer right so we need to have like a bouncer right to hold out the current topological sort result we have here right basically every time when we have a 0 in degrees we are we whip out be appended to the answer here and in the end we need to compare right if the answer we regard from this like reconstruction sequence here is the same as the origin all right if that's their same then we know okay it's true right like for example this one the nut the answer we got from this topological sort is 1 & 2 & but the orange we know sort is 1 & 2 & but the orange we know sort is 1 & 2 & but the orange we know is 1 2 3 that's why it's false right okay I think that should just work okay let's try to submit it cool so it passed all right so it's kind of like an interesting like a topological sort or graph problem right and basically we're using this like a queue we check that the number of the length of the queue to figure out if there's a uniquely a unique way of reconstructing to basically to get the unique topological sort answer right and the little a few edge cases is to for the invalid sequence number here right which does not exist which don't exist in this orange and all list that's why I'm using a minimum and a maximum value to do a pre track here like this one right and then after that it's just the regular topological sorting by using the integrate dictionary right and in the end we simply return the answer is orange in the answer okay cool I think yes I think that's it for this problem yeah thanks so much for watching the videos and stay tuned I'll be seeing you guys soon bye
|
Sequence Reconstruction
|
sequence-reconstruction
|
You are given an integer array `nums` of length `n` where `nums` is a permutation of the integers in the range `[1, n]`. You are also given a 2D integer array `sequences` where `sequences[i]` is a subsequence of `nums`.
Check if `nums` is the shortest possible and the only **supersequence**. The shortest **supersequence** is a sequence **with the shortest length** and has all `sequences[i]` as subsequences. There could be multiple valid **supersequences** for the given array `sequences`.
* For example, for `sequences = [[1,2],[1,3]]`, there are two shortest **supersequences**, `[1,2,3]` and `[1,3,2]`.
* While for `sequences = [[1,2],[1,3],[1,2,3]]`, the only shortest **supersequence** possible is `[1,2,3]`. `[1,2,3,4]` is a possible supersequence but not the shortest.
Return `true` _if_ `nums` _is the only shortest **supersequence** for_ `sequences`_, or_ `false` _otherwise_.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[1,2,3\], sequences = \[\[1,2\],\[1,3\]\]
**Output:** false
**Explanation:** There are two possible supersequences: \[1,2,3\] and \[1,3,2\].
The sequence \[1,2\] is a subsequence of both: \[**1**,**2**,3\] and \[**1**,3,**2**\].
The sequence \[1,3\] is a subsequence of both: \[**1**,2,**3**\] and \[**1**,**3**,2\].
Since nums is not the only shortest supersequence, we return false.
**Example 2:**
**Input:** nums = \[1,2,3\], sequences = \[\[1,2\]\]
**Output:** false
**Explanation:** The shortest possible supersequence is \[1,2\].
The sequence \[1,2\] is a subsequence of it: \[**1**,**2**\].
Since nums is not the shortest supersequence, we return false.
**Example 3:**
**Input:** nums = \[1,2,3\], sequences = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** true
**Explanation:** The shortest possible supersequence is \[1,2,3\].
The sequence \[1,2\] is a subsequence of it: \[**1**,**2**,3\].
The sequence \[1,3\] is a subsequence of it: \[**1**,2,**3**\].
The sequence \[2,3\] is a subsequence of it: \[1,**2**,**3**\].
Since nums is the only shortest supersequence, we return true.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `nums` is a permutation of all the integers in the range `[1, n]`.
* `1 <= sequences.length <= 104`
* `1 <= sequences[i].length <= 104`
* `1 <= sum(sequences[i].length) <= 105`
* `1 <= sequences[i][j] <= n`
* All the arrays of `sequences` are **unique**.
* `sequences[i]` is a subsequence of `nums`.
| null |
Array,Graph,Topological Sort
|
Medium
|
210
|
1,401 |
hi friends uh let's have a look at problem 1401 Circle and rectangle overlapping in this video we're going to explain a solution by locating the nearest point in the rectangle to the center of the circle so this will enable us to give solutions to this problem so in this problem the problem statement is very simple we have a circle and we have a rectangle so we want to check if they have overlap so here are three examples uh in the first example and third example the returns are true and in the second one it's false so here are some constraints so notice that the radius is uh strictly positive it's bounded below by one right so also we know that X1 is less than X2 and y1 is less than Y2 in other words X1 y1 is a lower um is the lower left corner of the rectangle and the um X2 Y2 represents the upper right corner of the rectangle so with that said uh we're ready to do the coding and Analysis so this problem actually is a Google interview question so this logic actually is simple if we can quickly digest the mathematics otherwise atat uh be challenging so here our strategy will be very simple so we want to find the nearest point in the rectangle to the center of the circle so basically we want to check this distance so this is actually very well known so for this problem here we are in working in two Dimensions so actually in the generic and dimensional case so the method will still work here I want to F the this uh the point which is near nearest to the center so I'll um define capital x and capital Y to be uh to be none at the very beginning so we want to assign the values so for this problem we need to check each Dimension so here we have two Dimensions we have X Dimension we have y Dimension so basically we want to check the closed interval corresponding to each dimension in the uh rectangle and then we compare with the corresponding coordinates in for the uh center of the circle so if the center the corresponding coordinates lines in the closed interval corresponding to the rectangle so the corresponding coordinate will be set to be the center coordinates component otherwise we either choose the two ends depending on what's the relative location of the center coordinate with respect to the closed interval so here let's examine the X Dimension so for X Dimension we know that so uh the rectangle runs in this closed interval from X1 to X2 right so basically if um the X Center is in this Bond less than or equal to uh X2 so in this case we are going to set I to be the X Center right so otherwise so if uh X Center is less than X1 so then we want to set capital x to be X1 other case we're going to set to be um X2 so we can do the same thing for the second dimension so this y1 and Y2 right so if uh y1 less than or equal to y center and less than or equal to Y2 in this case we are going to set capit y to be uh the y center and otherwise if y center is very small see less than y1 so we're going to set uh y to be y1 and otherwise so the Y Center will be greater than Y2 in this case we are going to set y to be Y2 so in this case uh up toal so we actually determine the XY point which we want to compare with the uh Radiance so basically what we want to return is we want compare the distance of this point XY with respect to the radius right so that's consider this to X Center right so here I can consider the ukian distance square right so y minus um y center so ra to the power two and then we compare if it's less than or equal to the radius uh Square so notice that we include equality so in this case the touch right so this will be a solution to this problem so the logic actually is very simple if you dig the mathematics so now let's first do a test yeah it passes the first example so now let's look at the generic case yeah it passes um all the generic cases so this is the one solution so overall basically uh we want to check each Dimension right for each Dimension the rectangle project to a closed interval and then we want to consider the corresponding coordinates for this uh component for this comp with respect to this uh closed interval so if X Center Less in for example this interval then we're going to set the corresponding coordinate to be this value if it's too small we are going to set it to be the one end say X1 if it's too large another end so it actually works for all Dimensions so once you set down this point and then you just need to check if the distance of this point with respect to the center is less than or equal to the radiance if so they have overlaps otherwise not so this the one solution so this solution is very analytic so next I want to explain a geometrical one so the reason uh we want to explain the geometrical one is due to the fact that so this geometrical one help us to digest or help you digest the problem so here you can look at this one so you have a um rectangle so here C is the coant for the center of this rectangle so from the center to the um see top right corner that is a vector corresponding to H right so the center of the circle is p and the radius length is R right so uh we can compute or we can see we can move the coordinates we can establish a coordinate Center or origin using this Center for the rectangle so this corresponds to use the uh coate of P minus the coent of C right so then you are in this scenario but this uh CP Vector can be e in uh in each of the uh quadrants but you know if we take absolute value it corresponds to map it to the first quadrant basically this is a good reduction of the problem so once we have this is also we know the H right and then we use this v is the vector corresponding to C and P right starting from C and ending in the p and then by triangle rule right so this from this corner to this P that's the right one is nothing but V minus H as a vector so this Vector red one basically can measure the distance of the circle with respect to the rectangle right so if this length here actually is the distance from the to the circle and then for this one basically in this case the red vectors in other words so V minus H actually the x coordinate will be negative and y coordinate be positive so this if we set the S coordinat to be zero then this rectangular one corresponds to the nearest distance similarly you can look at this case corresponds to the fact that the Y code um component of vus H is negative then this one the X distance will be the nearest distance so this case both X and Y coordinates of vus H is negative in this case actually set u equal 0 so in other words see in this one so this part actually this solution is the same as the solution we provid it but is more geometric still we want to find the nearest distance of the center with respect to this the rectangle so this one actually corresponds to compute the co or dot product with respect to this line so you can regard this line as a vector right so it's one zero or netive one Z but you know distance is the same so this one correspond to computer's projection uh to the um this to x uh coordinates right so correspondent to again do product so if you have some background in mathematics you can write in a component uh in a vector format but for our purpose we can do it very easily so first I can get the uh we can get the X Center the Y Center so this is very easy to compute right so this is X1 + X2 over two and this the this is X1 + X2 over two and this the this is X1 + X2 over two and this the one and then y1 + Y2 over two so this one and then y1 + Y2 over two so this one and then y1 + Y2 over two so this way we get the C in the graph right so Vector C so now we know we already know the P Vector is actually the um so the P Vector is X Center y center right so now let's compute the rectangle Center to uh Circle Center so this is nothing but the um HP Vector so uh here I'm going to use um X C minus this rectangular center right so y center minus rectangular y but I want to map this to the first uh quadrant so we're going to take absolute value so with this done so we have the necessary information now we use this Vector minus the H so how can we compute H so basically this is how rectangle see I'll write some um suggest name half diagonal see Vector let's see half diagonal means that this Vector will have a length of half the diagonal l so here is X X2 minus uh rectangular X Y2 minus so Y 2 uh minus rectangular y right so now we have this two Vector so we can compute a big Vector that is uh so this is nothing but H Vector you can think so this is a HP vector and also you can call it Vector H and this is the vector oh no this is the V this is the H right in the that graph and then X basically is V minus H so we can do something like this I can use the um list comprehension right so I can take Max so a b or zero right for a notice the order is important zip I want to use this one rectangles to this one or minus this one so basically this Vector length will give us the nearest distance from the center of the circle to the rectangle so if this one is less than uh the radiance then we are going to have overlap otherwise not so here we just need to return x notot uh square plus y KN right uh Square so let's see if it's that than Radiance uh Square so this is actually a more geometric solution so this one is more analytic right so now let's test stage first why is not defined let's see uh where so X not X1 so let's run it yeah it passes one example now let's look at the generic case yeah it passes all the cases so let me make some remark so this solution is more analytical right so for this one it's more or geometric right but these two solutions are actually the same idea based on the same idea so you can also write so in a vector format so notice that here we have two Dimensions right so in general if we have n Dimensions you can do the same thing right but you can use vectorization so similarly here you can use a for Loop to do all the things and then do comp Pary so with that said I guess we finished this video thank you
|
Circle and Rectangle Overlapping
|
number-of-burgers-with-no-waste-of-ingredients
|
You are given a circle represented as `(radius, xCenter, yCenter)` and an axis-aligned rectangle represented as `(x1, y1, x2, y2)`, where `(x1, y1)` are the coordinates of the bottom-left corner, and `(x2, y2)` are the coordinates of the top-right corner of the rectangle.
Return `true` _if the circle and rectangle are overlapped otherwise return_ `false`. In other words, check if there is **any** point `(xi, yi)` that belongs to the circle and the rectangle at the same time.
**Example 1:**
**Input:** radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
**Output:** true
**Explanation:** Circle and rectangle share the point (1,0).
**Example 2:**
**Input:** radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
**Output:** false
**Example 3:**
**Input:** radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
**Output:** true
**Constraints:**
* `1 <= radius <= 2000`
* `-104 <= xCenter, yCenter <= 104`
* `-104 <= x1 < x2 <= 104`
* `-104 <= y1 < y2 <= 104`
|
Can we have an answer if the number of tomatoes is odd ? If we have answer will be there multiple answers or just one answer ? Let us define number of jumbo burgers as X and number of small burgers as Y
We have to find an x and y in this equation 1. 4X + 2Y = tomato 2. X + Y = cheese
|
Math
|
Medium
| null |
11 |
hello guys in this particular example I will be discussing about lead code problem number 11 container with most water so in the problem you are given an array indicating the height of the lines you have to find the container with the most water the two points with which can have the most water say for example in the first two points right what will be the water so it will just be 1 into the area of Base 1. so if you take this example between these two red Point what is the length it is seven one two three four five six seven and what is the height seven so the area in this case will be 49 and similarly you can calculate for other points in a Brute Force way and you can indicate what is the maximum area but we definitely don't want a Brute Force approach so let's dive into what are the quick observations that you will be able to observed so the first thing is what is the maximum length that you can obtain in this problem it is just the end points right so if the length of the array is 9 it is just between these two points and the length will be equal to 8 that is n minus 1. the second observation you can draw even in this example is the minimum height between these two will act as the breadth of the or height of this particular area so you can multiply these two to get the area what is the third observation that you will be able to draw you always prefer to have more height so the first and the third observation are very important the first indicates that you need to use two pointers and you have to place it at either end the third Point indicates that you have to choose always the higher height and you can neglect the height that are actually lesser so let's get into the diagram and let me explain so in this first case the pointers are at the either end so the height is 1 and the other side the height is uh seven so what is the area the first area will be eight because that is 1 into 8. so you don't want this right so you will just be moving this pointer to next that is if this height is lesser than J's height you will just be move doing I plus so in this case this has the higher area and this has the lower so you will just be moving here similarly this has lower so you will be moving so now both of them have equal weight so you can move any one of them it doesn't matter so let's say you move this similarly you will be moving again because this has lower height again you will be moving this pointer again this and I have also indicated the area so what is the maximum among all of these it's 49 so 49 will be the answer so I have written the sudo code also so first thing you need to do is get the length of the array and you will initiate the two pointers first one to zero and the last one to n minus 1 and this will be your answer so what to do at every point you will calculate the area that will be equal to the minimum of these two that is the height and whatever is the length that is J minus I so the next thing you will be doing is if a of I is greater than a of J that is ice height is greater you will do move the J pointer that is you will move to the left side otherwise you will be just moving it to the right side and you will be returning whatever maximum that you have obtained so let me show you the actual code this is in Java let me run the code and let me submit this as well okay so here we have the solution thank you for watching please like And subscribe
|
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
|
714 |
hey what's up guys uh this is chung here so today uh today's daily challenge problem number 714 best time to buy and sell stock with transaction fee right so this is another very classic buy and sell stock problem the only difference for this one is that you know each transaction has a fee right so again right you're given like a array prices right uh where the price prices i is the price of the given stock on the ice day right and the integer fee representing a transaction fee so this transaction fee means that in every time when you sell a stock you need to pay this amount of fee and our task is to find the maximum profit we can achieve and we can complete we can buy and sell as many times as we want but we have to pay a transaction fee for each cell right and you can we cannot uh buy and sell at the same time and then we must sell before you can buy it again right so yeah i think i'll we'll just dive into that the solution directly so basically you know i think i also write i already uploaded two by sales stock problem so the way i solve this problem is that you know it's always i always define like two dp arrays here so the first one is the buy and second one is cell right so the buy eye means that you know the last transaction we the last transaction uh we have ever done was buy right and what's going to be the max profit right this is also max profit last was buy and this one last was cell right so i always try to define this two kind of a helper like dp or right here you know so this one means that no matter let's say we are at days 10 here right i mean it doesn't really matter how many transactions we have ever done so far it doesn't really matter but this one is telling me that you know as long as the last transaction as long as the last action was by then this is what the what it is means right and cell means that you know the last transaction was sell right because you know on certain day we can do nothing we don't have to buy or i mean or sell right and that's the definition of this 2 db right here so the reason being is that you know the reason we need to this we need this 2dp array is that you know when we calculate the cell i or by i will need we'll need the we need the other arrays to help us because let's say if you if we want to sell at the ice day right so the prerequisite is that we have to buy the stock first right so that's why you know when we calculate cell i here you know since we need to know like we have to buy the stock first that's why you know uh we it's going to be the buy i minus one right and then plus the price that's going to be the uh the state transition for sale and similarly to buy right so to buy the stock right to buy the stock i mean we have to somehow sell the stock first right before we can buy it again that's why we have cell i minus one right and then we decrease the price of the current one that's what you know as you guys can see that's why we need this two separate uh state of either the last transaction was buy or the last trend transaction was set what was sell only then we can be sure we can either do the we can you can sell at the current state or we can buy at the current state right and the final answer will be the s the cell of an uh minus one so this one means that you know at the last day right and the last transaction was sell right what's going to be the uh what's going to be the max profit okay cool so that's going to be the idea here you know and then let's start coding here so we have and we have by zero right start this one cell zero n right so the reason i do i define this one with zero is because you know the worst case scenario is that we never buy and sell right which means that we the max the worst profit we can ever get is zero you know let's say if the price never goes up let's see the price is like this four or five four three to one right it's always going down so in this case basically we'll never buy and sell that's why the worst case scenario is zero right and then to start with the since we have uh we need to use the i minus one right so which means we have to initiate the buy and sell for zero right prices okay zero right and then the uh the cell actually cell is also zero so here so the by zero means that you know at the days i if the last transaction was a buy you know it means that we have to purchase the first uh we have to purchase the stock at the first day which means that you know the profit uh for this uh if we if the profit for the first day and the last transaction was buy it's still is the price the negative value of the price right and the sale is obviously zero and then for i in range of one to n right and we then we can do our uh state transition function here you know for each of the bind sell here you know we have two options right like i said we can either buy at the i stay or we what we don't buy right so if we don't buy what's going to be the value of course it's going to be i by i minus 1 because the uh remember so if we don't buy at the current day so the uh the profit won't i mean won't change right and the last i mean and the last transaction is still a buy right and if we decide to buy at the current state it means that we have to somehow sell the price right be before which means there's going to be cell i minus 1 and then we subtract the price of the current day right so similarly if we want to sell at the car at the ice day right the first scenario is that we so sorry this so this state means that you know the last transaction was sell which means that we don't have we don't necessarily we're not necessarily need to sell at the current i state right so if we don't sell at the current i stay it means that you know the last transaction is still a cell right it's going to be a cell i minus 1. because this one means that even though we don't sell at the current i stay but the definition of the cell means that you know the last transaction has to be the cell that's why we use the cell i minus one right if we don't sell at the current i stay and then we do uh but if we decide to sell at the current day then we have to buy it beforehand which is by i minus one and we do a price of i right so since we sell at the current day and for this one the only difference is that we have to subtract the fees here and in the end we just return the cell minus one right so if i run the code accept it right yep cool so i mean the time complex and space complexity so for this one i mean obviously the time complexity will be the o of n right since we only do a loop once and space complexity is also of n because we have buy and sell uh to help us calculate the next state right but if you watch closely actually we all we need is that i minus one state right so which means that we can compress this space complexity from o of n to all of one okay so and the way it's doing is sim is kind of straightforward so instead of array we just define two variables right so we remove that you know so now the by will becomes to this by right and it's going to be the i right so similarly for this cell right we simply remove those two things and by actually so for this one um i think the easier way is that you know uh since we need to use this one to store the uh the previously state what we can do it we can have like cell two and by two here actually so this is a by two and cell two right so in this case we're making sure right that so the buy and sell we use are still from the previously state previous state right and then the in the end we can simply uh assigned by equals to buy two right and then the cell equals to cell 2 right in the end we simply return the cell if i run the code yeah it should also work right yeah basically that's a simple technique to compress the uh the time complexity to from uh to decrease the dimension right of a time off sorry alpha space complexity since all we need is the previously one the state that's why i'm using like this kind of uh two parameters right another temporary values to calculate the current state and then i rotate right update the bind cell in the end uh cool i think that's it for this problem and okay thank you for watching this video guys and stay tuned see you guys soon bye
|
Best Time to Buy and Sell Stock with Transaction Fee
|
best-time-to-buy-and-sell-stock-with-transaction-fee
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,3,2,8,4,9\], fee = 2
**Output:** 8
**Explanation:** The maximum profit can be achieved by:
- Buying at prices\[0\] = 1
- Selling at prices\[3\] = 8
- Buying at prices\[4\] = 4
- Selling at prices\[5\] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
**Example 2:**
**Input:** prices = \[1,3,7,5,10,3\], fee = 3
**Output:** 6
**Constraints:**
* `1 <= prices.length <= 5 * 104`
* `1 <= prices[i] < 5 * 104`
* `0 <= fee < 5 * 104`
|
Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
|
Array,Dynamic Programming,Greedy
|
Medium
|
122
|
989 |
hello everyone so this is lead code 989 add to array form of integer so in this we have been provided an array and we have been given a number k and we have to return the sum of the um the number given in the array and the given number 34 so consider that if we have 1 2 0 then we have to first make the number 1200 and then we have to add 34 so there are two ways to do this problem the first one is you just simply um initially you just take a loop and then every time you take a look you just have to do sum into 10 plus num i is equal to sum and you have to iterate that then you will get the number then you can add the k and then you just create another array and then return that array as one two three or you can simply use another method in which you have to consider the concept of carry so for that we will first declare the arraylist of the type integer okay and then we will name it as answer and then we will make it okay now what we are going to do is uh we are going to start a for loop and that we will go with and is equal to now we are going to start with the last index now because if you are going to say that you are going to add 34 in 1200 then the last digit or the last index is where you are gonna add game so we are gonna start with uh dot length minus one okay then we are going to make it greater than equal to zero and then i minus okay this is how things will go now uh what we are going to do is we are going to add the uh last digit okay in the answer that is our address okay let's rename it to list that will be much better okay so what we're going to do is we will simply add a list dot add and then this we are going to do is uh num i plus a but also we are going to take the only last digit okay and then what we are going to do is uh we are going to change k to okay this is how we are going to do but there is one problem in this and that is uh consider that if k does not becomes zero subsequently that is it keeps on increasing uh as our iteration ends so in that case uh we are going to change one thing and that is we will have to take a condition where i is actually greater than equal to zero okay uh in this we are going to put our this condition and when i in other condition where k is not equal to 0 even after that we have to keep adding it so we are going to do is list dot add and k and also we are going to um reducing the digits of the k but since we have added this condition where uh if i is greater than equal to zero we need to add a condition of or where we are allowing that k should uh k should be greater than 0 so in that case the loop will continue to run until and unless k is greater than 0 that is the carry will keep on increasing like consider that we have the condition of 181 and we have to add 274 so in that case let me show you what's gonna happen is uh sorry let me show you for two and five plus eight zero and six so you can see that we get one extra the length of the new array will be greater than the num that is for the length will be 4 but for this case only we have added this condition of k greater than 0 because we might be decreasing k again and again but we need to allow the loop to continue till k is greater than 0 okay but there is one problem and that is if we now run this code okay i have not added the return statement um in this case the digits are not reversed you can see that it's what we need one two three four but we are getting four three two one so for that the simplest thing is we have collections dot reverse okay this is faster than 77 of java solutions thank you
|
Add to Array-Form of Integer
|
largest-component-size-by-common-factor
|
The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104`
| null |
Array,Math,Union Find
|
Hard
|
2276
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.