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
42
so if I was to give you a elevation map represented by non-negative integers represented by non-negative integers represented by non-negative integers where each width of the bar is one how much water is there in this graph so the water would be falling into these uh troughs or pits basically so how would we go about calculating that so if we let's think about this example so we can obviously see there's an elevation of one here and an elevation two of here so therefore if there was rain there'd be water between these two blocks at an elevation of one uh if there's two blocks here and three blocks here then there would be obviously rain water falling between the two and if there's a bar here and a bar here therefore it would be there would be four units of water um between these two bars or boundaries and obviously over here we've got a section here in a section here and a section underneath there'd be watery trapped in there okay so the question is how do we calculate this and obviously we're given an array so we want to know like how do we go about this so the first thing you always want to do is think okay how would I Brute Force this so one Brute Force solution is that you could maybe find the maximum peak of this entire elevation map so you could think of it almost like a 2d Matrix or a grid and you could find and you could base it like okay what we're going to do is we're going to iterate from this top left Square iterator iterate across and if we find um uh two values right like a left boundary and a right boundary then therefore everything between those boundaries has to be water basically um and if obviously you only have one boundary but only one left boundary say but no right boundary then there's no water so you could basically iterate across this entire grid um so you'd iterate across say this row and you would find no water then you would iterate to the next row right and in this case you'd find a left boundary which is this Square um and a right boundary right and then you'd find three water units between those and then you'd find obviously you'd find a left and a right here but there's no space in between so there's no water and then you'd find a left here and a right here and then there'd be a water unit there and then obviously there'd be no let right boundary to this empty Square so you'd leave it as is then you go to the final row and you basically repeat the same process and you're basically you'd find all the um all the water that way but the problem is um the cost the time and complexity of this would be um obviously whatever the max let's say the maximum uh Peak is M and let's say the total length of this list the height list is n therefore you'd have to go n times M time complexity which is you know it's not great but it's better than nothing right um now what if we like uh what if we were to somehow get this down to just n so we iterate over the array once and then we can do the calculation so think about it that way um we know there's some sort of relationship between like a left side like we know if that like if there's some sort of relationship between like a left and a right and we can think about it as like well what if like we somehow um you know and we also know that there isn't just going to be one trough or one bucket basically we know there could be multiple Pockets so we know um there's some sort of relationship here or strategy so um like another idea would be like what if we found the maximum left Peak and the maximum right Peak right if we were to find the maximum left and right Peak then we know that from the left if we're descending downwards that has to be water um and if we're descending down from here that must be um if we're descending down from the right and we're lower than the left then there must be some sort of water in between basically right so there's this idea of thinking about it as like a bucket and you have like a right Peak and a left Peak now the problem with finding the global maximum right peak in the global left maximum Peak is that well how what do we do about if we if so we calculate the water in this bucket what about the buckets on the left and right side right now A naive approach would be like okay maybe we can kind of reverse engineer something where like if we know the left Max Peak we can kind of figure out this or something right and if we find the max right Peak here we can somehow reverse engineer going this way um but in doing so you know I don't we it's difficult to know if we can achieve that in end time so that's the goal is that we only want to do this and end time so what we can also do instead is maybe we can um uh you know maybe we can think of uh multiple buckets so instead of just thinking of like a Max right and a Max left Peak what if we like had um we had a Max and right Peak at that instance of the elevation map right so what if we found like a local maximum left and a local maximum right and then base the calculation off that so for example what if we like found we started from position zero and moved right and check to see if we can find a maximum left at that point in time so for example we could find that there is a um a left Max would be zero at position zero so and then at position one our left Max would be one um and then since if we look here we've descended one unit and since we're lower than the left Peak then we can safely add one unit of water and then when we get to the this two right as we're iterating across with like I say a left pointer we can say the new left Max is now two right so then when we descend below we can add one unit of water or add two units of water because we're at or less than the left Peak now you're probably thinking well how can you guarantee the right side like what if you have like say a bunch of squares and then it just goes nowhere and there's no right boundary ah what we can do is that while we're iterating across from the left we can also iterate from the right and we can calculate what the maximum right boundary is and we can base off how we iterate based on whether the right Max is lower or less is less than or equal to the left Max so let me explain this right so basically let's say we're moving from the left to the right and moving from the right to the left what if we say um we only want to iterate our say left pointer right if our left Max is less than our right Max right and if this is less than or equal to and if this condition is not true we want to iterate our right pointer now the reason we're thinking about this way is like almost imagine it like we have two buckets right so we have a left bucket and a right bucket and we need to capture all the water in these buckets and then we also need to know when these two buckets merge into one big bucket basically right and we basically only want to iterate the smaller bucket first until um uh or the lock the bucket that's lower before we iterate the bucket that's higher so um so how do we do this how do we actually do this we have to think about like calculating so for example the left Max would be zero and the right Max would be one so therefore since the right Max is higher than the left Max we iterate the left Max and now the left Max pointing here the right Max is pointing here and they're on the same height so basically what we want to do next is then okay let's iterate the left pointer across and then we see there's water and it's left in the left Max so at this point we guarantee that this has to be water right then what happens is that we iterate and we see oh there's a block of two so this is our new left Max now since the left Max is greater than the right Max we're going to iterate the right across so now the right Max is pointing here and since we've ascended and on descended there's no water in this instance right then since the right is the same as the left we iterate the left so the left is the left pointer is here and now we're going to add one water unit so it's basically um how you calculate that water unit is basically the left Max minus that current value so this current value at this position is one right and the current left Max is value two so to get the water you just go 2 minus one or left Max minus the left whatever the left point is pointing at okay then you do the same here you add two units of water and you go here you add one unit of water and then obviously you find the peak here right which is the left Max which also happens to be the global Max and then obviously you iterate the right pointer here and since you're descending you add the water unit here and then you increment here and then eventually what happens is that you can end when the left and the right pointer uh crossover because you've explored the entire graph so we would come up with an answer of six which would be the total water units which would be accurate and it would also execute in end time actually we understand the concept of the solution we're going to actually start executing this code so we'll just say n equals the height um the length of the array um and we're going to say uh if um if n is less than three right um then we just return 0 because uh there's no there's not there's no buckets basically because you have two columns so there's no way there's any order um then we're going to do is we're going to set up some um uh left and right pointers and we're also going to set up um our current Max we're going to say the max left is going to be whatever is it high zero and we're going to say the max right is going to be what is it height n minus 1. um so then we're going to say is while left is less than right all we're going to do is basically say Okay um if um the max left is less than or equal to the max right then basically what we want to do also we need a uh maybe um the water is going to be zero um uh so um so then we're going to say if the max left is less than or equal to the max right then what we're going to do is um basically increment our left pointer um yep and then basically what we're going to do you're going to say the water equals the Maxell the max left which is the and then minus the height which is at L basically so for example if we're going left to right and we see the first block we'd update the Maxell um and increment the left pointer so then we're going to say um uh we also want to update the Max L to be the max of the L and the height so the height L and the maxill thank you um yeah and then we're going to do that and then we're going to do the same else um we'll increment the we'll decrement the right pointer we'll say Max try equals the max R height r um and then we're going to say water equals Max right minus height right um and then we simply return the water so check this Oh What A plus equals what a plus equals run this okay equals that it's gonna debug sell water plus equals High Max L an so that's fine else R minus equals one max out oh left my mistake the right pointer should be set to n minus one not zero yeah there you go now if we run this we submit it and we get the solution
Trapping Rain Water
trapping-rain-water
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. **Example 1:** **Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\] **Output:** 6 **Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped. **Example 2:** **Input:** height = \[4,2,0,3,2,5\] **Output:** 9 **Constraints:** * `n == height.length` * `1 <= n <= 2 * 104` * `0 <= height[i] <= 105`
null
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
11,238,407,756
778
today we are solving swim and Rising water problem we are given an N cross and integer Matrix grid Andross and means this is a square Matrix where each value represents the elevation at that point we have to return the least time it takes to get to the bottom right Square from the top left Square we also can swim infinite distance in zero time what does it really mean it means for example in a path like this we can swim along this path in zero time so wouldn't the time required to get to the bottom right Square from the top left Square P0 unfortunately the problem statement is not that simple there is a constraint for us to begin swimming which is mentioned over here I don't know why lead code made it really convoluted I'll try to paraphrase this constraint basically says regardless of whichever path we take before we can start swimming we need to wait certain amount of time so what exactly would that certain amount of time be it depends on the path we take for example if we take this path from the top left to the bottom right cell amount of time we need to wait before we can start swimming will be the maximum elevation in this path which is five so we need to wait for T = 5 let five so we need to wait for T = 5 let five so we need to wait for T = 5 let's look at a different path in this path we need to wait for tal to 4 before we could start swimming along this path so basically the problem statement is asking us to find a path from top left cell to the bottom right cell that has the least maximum elevation so that has the least maximum elevation to solve this problem how about we explore all the possible paths and for each path we note down the maximum elevation in that path and we return the minimum of all the maximum elevations in each and every path this algorithm will definitely give us the right answer but the runtime for this algorithm is exponential can we do better than this as we know what's driving the weight time before we could swim along a path is the maximum elevation in that path so how about we avoid cells that have the maximum elevation for example five how about we avoid all the paths that go through five this will help us prune all those paths that go through five and should bring down the runtime complexity how about we do the same for all the paths that go through four this is a really good way of pruning all the paths that have higher elevation in other words what we are saying is from any cell we pick an adjacent cell to swim to that has the least elevation for example from the top left cell here there are two cells that we can swim to cell one and two so we pick one because that has the least elevation among all the potential paths then we add its neighbors to the CU in this case four and five so there are three cells in the Q now 2 4 and five we always pick the cell that has the least elevation in this case two we add its neighbor to the cube which is three out of three four and five three has the least elevation we pick three and add two to the cube we repeat the same two has the least elevation we add three to the cube and out of three four and five three has the least elevation and that happens to be our destination cell as well so we stop the algorithm here and the path we took to get to the bottom right cell is this every time we pop a cell from the priority queue it's because we are going to swim to that cell will be part of our final path which means we should take its elevation into account in finding the least time to get to the bottom right cell so every time we pop a cell from Priority Q we save its elevation and we return the maximum elevation that's our final algorithm so the runtime complexity of this algorithm is Big of and Square log n² because in total there are n cross n cells and will be pushing in the worst case all those cells in the priority Cube so we can simplify this further of n² we can bring the two over here to log n we know that 2 * log n when we n we know that 2 * log n when we n we know that 2 * log n when we generalize it is same as of n² log n that's our randm complexity and the space complexity is of square because we need to mark all the visited cells let's write the code for this algorithm let's call n as the dimension of the grid since we are starting with the top left cell let's add top left cell to the priority CU elevation of top plus cell is G of 0 and the row index is zero column index is zero and we mark this cell as visited do add 0 Z while the priority Q is not empty we know that priority Q always picks the cell that has the least elevation so let's pop the cell from Priority Q HP pop from Priority Q we get the elevation row number and the column number from it we check if this is a bottom right cell if row equal to nus1 and column = to nus one that means nus1 and column = to nus one that means nus1 and column = to nus one that means we have reached our destination we have to return the maximum elevation along this path so let's call that as Max elevation and initialize that to zero so we return that before returning that we need to update the max elevation if the current elevation is greater than the max elevation if this is not the bottom right cell we need to add the unvisited neighbors of the cell into the priority Cube so let's explore these Neighbors neighbors for new row and new column number in all the possible Neighbors which are row minus one and same column which is the top cell and row + one column is the top cell and row + one column is the top cell and row + one column is the bottom cell this is the left cell and this is the right cell if the neighbor is already seen in scene we don't add this to the priority CU if it's an unvisited neighbor then we can add this to the priority Q keep push to the priority q and the elevation of it is grid new row and new column and the row number is n r and then C is the column number in the next round we again pick the cell with the least elevation and keep updating the maximum elevation that we found so far so this will ensure we always pick a neighbor that potentially has the least elevation out of all the possible options so finally we return the maximum elevation we have found oh one thing I forgot to do here is I need to ensure this neighboring cell is not out of boundary so if new row is less than zero or new column is less than zero our new row is greater than or equal to the number of rows our new column is greater than or equal to number of columns in this case we skip this cell I also need to add the unvisited neighbor to the list of neighbors visited so let's add that scene add NR NC as you can see this solution works if you found this video to be helpful please support by liking the video and subscribing to the channel I will see you in the next video thank you
Swim in Rising Water
reorganize-string
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
Medium
358,621,1304
37
So this question number 37 is only box, so it should have all the 9 elements from van to van, like I have written the condition here, now we will solve it using reasoning, so first of all what will we do, so what will be our first step that we will People will check what 129 will not happen in our show, first of all we will put it there, after that we will check whether it is safe or not, if we will put it there, if it is safe then we will let it stay there, otherwise the second element. The team will check. Now let's go towards the code, what will be its code, inside which all the characters will be filled, which is named as board, from there we have called the function which starts so we have checked. Our first dot will come After that we put the element in its place and in relation to the same element which we have written the function on line number three, from this function we passed it to the character and from that we first used the function. Checked whether that element is already present in the row. If it is then turn to the fall from there. If not, then check from there whether that element is present in our column. This is our second condition in which we will check whether it is Is that character already present in the column? If so, then we will turn from the fall. Otherwise, we will check our third condition in which we will check whether the element is already present. If not, then we will replace the element in its place. If not then we can return from there and we can put the character in its place and after that we called our solve option recursively. If our function returned true then we repeatedly put it in place. They will go increasing otherwise we will dot put it at the place which was already given by our condition, after that we will be able to turn from fall, man, when our for loop has been checked from van to nine, we have checked that from van to nine. Gave the element team till 9 but if the element crosses 9 then we will turn from pay fall there otherwise we will return to Atlas.
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy **all of the following rules**: 1. Each of the digits `1-9` must occur exactly once in each row. 2. Each of the digits `1-9` must occur exactly once in each column. 3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid. The `'.'` character indicates empty cells. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\] **Explanation:** The input board is shown above and the only valid solution is shown below: **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit or `'.'`. * It is **guaranteed** that the input board has only one solution.
null
Array,Backtracking,Matrix
Hard
36,1022
51
Hello hello viewers welcome back to my channel thank you are in extreme level shoppers stop and thank you so much for deep 124 response to destroy subscribe series is really no one by banai reddy comment and everything thank you so much sona will be back to Replacement Released In The End Today Will Be Discussing A Problem In Swings Problems From SD Sheet 200 What Is This Problem All About The Problem Settle Give In Advance And Support Rights Which Sport And What Will Be The Class Exam Clear And Queens Pocket So Let's Understand etc question awadhi so maza-5 na sona please do not awadhi so maza-5 na sona please do not awadhi so maza-5 na sona please do not disturb question 100 basically inches video subscribe 449 ka name indraprastha sports board this exactly place in quote 4 means ok na users can not 14 prince antiseptic you have to follow certain rules and son hot 200 2003 Rules Are Rules Falguni Rosada Between E Agri Column Chudha One Queen Inside 300 Important Jobs Vis Attack Beach Yadav A That Not Only Question Side Agri Rohila And Any 9 And Also Place Of Queensland Pictures So Let's Imagine A Place In Queensland This Page Please Guys Like This Vacancy In This Column I Want To Win In This Column At Exactly One Queen In This Column Exactly Win In This Rooh Exactly And Naveen Indru Exactly And Naveen In This Royegi Delhi-110 Exactly One Can See Royegi Delhi-110 Exactly One Can See Royegi Delhi-110 Exactly One Can See That Everyone Who Has One In Every Problem Has Been Told Them Not To Win But 11 Inches Till Heart Attack In Delhi Election 2014 That Indresh In Desh And Shudra Interaction Between Ghanta Ek Subject Skin On Tight Skin Introduce This Dish Jewelers This Is The Meaning Of this and solid condition want to know data is the most important condition open ten apart from this you can not be no answers ko whatsapp ipl se koi new voter place for india vote for play shak hai this notification koi new na mixer ko condition the first Column Harappan Respect In Column Always Win The Third Problem All Work Harder For Them All Sadhaks In The First Roles Uso In This Country Who Also To A Limited extent In Third Roger No Sleep Sutras And Zameen Daddy Of Baneta Replaced Left Leg Spin Attack In This Generation I Don't See Animal Rescue Institute In This Direction The Tiger Nal Pregnancy One This Point Canteen Reservation But I Don't See Any One This Cream And Different Directions Are Don't See In This School I Am Sure That In This Generation Definitely Would Like Every One Is Keen That In this August Swift hui is note that any one who discovered planet and you individual in this and you will in the streets in this channel and even in this also not taking any one interested in the invisible in this and this one response To Also Not Taking Any One Is Such A Default Distraction This That Country-Foreign And Space Between This Also Not Country-Foreign And Space Between This Also Not Country-Foreign And Space Between This Also Not Taking Any One Can Definitely Possible Solution To End Queen Shop Bigg Boss-8 Is Exactly Then Shop Bigg Boss-8 Is Exactly Then Shop Bigg Boss-8 Is Exactly Then Queen Significance For It's polling all other conditions is not only answer no 19 one more and more so imagine if one mosted then please- and more so imagine if one mosted then please- and more so imagine if one mosted then please- please ko yeh please haq hai yeh please a new song again can see in more please subscribe ball shree condition you first subscribe question is Very Simple and Straightforward Will Give and a Witch You Can Place and Coins Making Shakti Three Conditions for Land in an Cross Inches Bodh One Over a Billion Example of Anybody Who Can Do Anything Just Need to Make a Condition Avoid Conflicts and Queens Subha Movie Dinesh Lal Yadav Video Limit Lifting Dangerous Is This Period Largest Building Education Company And Laptop 1050 Kepler Students A This Course In Programming In Different Languages Select Place This Solution Is Also Course For Machine Learning And Development Has Significant And Quality Is Exceptional Qualities And Exports From It stands for emergent Facebook do you want to support and the tree outswing time date one acidity per cinema's is a really well structured and some men have benefited from it's a grace you should 2015 0 district description travel desk question also edits now in which Has Already Present These Years Back When Quite A Simple Problem Is The Boat Generating All The Possible Website For The Best Way The Best Web Tools Problem Definitely To Use A Question Maker App To Generate All Possible Ways And Know English No Problems With Meaning Of Requests Solution So How Will You Plan Your Records Solution It's Very Simple One Drops Uses Ok And Droos And Skimming It's Lipstick And Crops And Support 100MB Drawing With Small Slip C's Incomplete Sports Authority Can Understand Any Potato Operation Raghav And In This duets ultra dual question awadhi ish call me yes your travel tours to feel every school not only very simple question you have best support i india starting with the or school prayer when you were my very simple question tube se supervisor hi hua tha a fast Any New Question Any New Since 1 Hour So You Tried To Write And Read Them Which Provides All This Provision For Placing Queens So Let's Almost Default Swift West Is That Please Division Deposit Roy Please Subscribe On The Second Basis Description Placid Over All Ex President is and Roadways Why Don't You Try to Preserve Slow Stomach Clear Plaster Any River 0.5% Add Wave Stomach Clear Plaster Any River 0.5% Add Wave Stomach Clear Plaster Any River 0.5% Add Wave Question Box This Reception Will Be Called At First The Invention Question Is That Compound Old Son Of Cases Graduate In This Question Record From Chennai I Have Chilli And 3000 Olympics Jacqueline Any According To The Rule Column Doing Only One Koi Writes Let's Move In A Column Notification Where Can You Play Shakun 24 New Play Sethiya Tha Just Hypothetically Thing You Please Sakuniya What Will Happen Ranveer Singh Distic Police Attack Place Yes Not Think Any Place Any New Dating Distic Will Take Place That This Pressure Koi Naya Yes You Can Us This Will Not Take Any One Can See It Was Not Possible For Placing Koi Superintendent Neeru Electronic Product Ka Note Babuji This Can You Please Koi Naya Yeh Seat Definitely Play Se Koi Naya Select Please De Hai Na Again I Know That's one-and-a-half possible 200 Hai Na Again I Know That's one-and-a-half possible 200 Hai Na Again I Know That's one-and-a-half possible 200 left possible They will be accepted in first in recognition Sunehri The second column I like it only from one Any question will you like this Olympics now Let's check out Can we please queen in this note Replace definitely please note This Is E Reply Yes We Will Not Be Able To Beat A Single Column Hands In This We Is Definitely Not Possible To I Will Go Back To Remember When A Boy Goodbye Akshar You Remove This Thank You Because While Coming Aaya Please Subscribe Going Back To You Remove This Thank You From Doing This Award Backtracking On Back Movie Picture Please Avoid To Remove Nuvve Please Secretary And Developed Attacks Can You Please Give Me Yes No Possibility Of Attempts Suicide Any Doubt That A Second And Default Index Rock To Please a sacred place a kyun kiya ise yadav they can you please like you know in school for this pattern of placing the only place on ki naav hua tha your comment on this column purchase this last one can you please give India no No Veer is not able to love lasts or not satisfied is the condition of every problem not possible to go back to give you any possible way subscribe now bani started my play singh koi new you could not find any solution member also not possible for Him To Go Back When E Go Back Pitch Curated To Remove Right Cycle From Marital Broken Any New Edward Norton Solution Noida Next Possible Stop At A Pleasing To Win Over Select Pilot Shri Narsingh Ji First Column Hardik YouTube Definitely Mukt Din Column A Lips And Stand Up less accuracy definitely play list play ki Naseer Sahab please like you here everyone move to the next column cholesterol plus you can you please give your data this no one to plus click on subscribe and over friends please War and this hasn't been quite well attack please 60 and this is not interested in you please give up it's not attack can see only you can find the last please over tomorrow morning laptop click it 300 place 109 person hanging that Icon Se On The School An Only Place 10 And Movement You See Your Point Missing Husband Successfully Please Active At Every Position A Special Se Data Side Definitely Have Play List And Win In Interest And Justice Board Making Shot No Other Conditions Awards And This Can be one of the possible and suggestion is able to the senses problems and asked for selected text to dance on not want to go back to the time the moment you go back to make you remove this thank you again to go back to make hair remove This thank you again you to go back to make sure remove 10's heroine will be remembered hundred percent go back to meet you go back to remove 10th over 10 vacation college complete because while coming years back when I go back to remove the distance vote backtracking is You Need to Make You Remove Vain Trying to Do the Calling Regression in Subscribe Comeback the Question OK Subscribe You Will Also Get Your Data Mortality Rate and When You Love You Will Not Enter Subscribe Not Find Any Answer Saw Your Points 211 But Sure This Might Thought Process Simple Equation Will Definitely Have Fallen Into A My Tablet Hui Or Around Next Clubs Didn't Call So No 200 NS 160 Cancel 3 Say Zinc Please Do The Withdraw End Column 1 Column Movement You Will Win Over 200 Points 115 Apne Column But This Award Is Going On In Welcome Back To Back Due To Bigg Boss Next 9 News Room Report Subscribe Now Discussing Difficult for this particular question Select one Space Start From Where Should I Want A Vector Offsprings Basically A What He Wanted To Attend Cross Inches Voters In West Up For Research And Way Din Ambrose And Just Want In Fact Price Saudi Want All Riches Boobs Attention Hundred-Hundred Basically Half Android Boobs Attention Hundred-Hundred Basically Half Android Boobs Attention Hundred-Hundred Basically Half Android Half an order I declare and decided to run and declare now actor of string of board of science and mischievous board center strength of doing basically doing and subscribe imported into director writer director and size the place and physically this is or size and job sites for every Distic Will Have Something Is This 0123 Talking About Anybody Who Specializes In One To Three For 16 2013 Lashes Vector Operating System Factor Of 10th Board Of This World Of Nowhere Chilli Word Is Put Mt Stream Consent Springs Nothing Else Is Patented Enemy Friend Prince Student And Teacher Support's ninth writing recursive function solve and give columbus shooting gold and passing is midday service tax christos all two sports and cricket and electronic or sometimes absolute and ultimate fighting championship a stop you comment 20 electronic to vote for trying for every problem after every rule simply In this format yes from CO2 and minus one destroy every truth and dare see from this tuk place between one and a half drink from this get this taste board latest departures gold this and you would win over any process any new any place Vinya or chatting difficult check half minute done Will Discuss About The Function Of To Disturb You Know It Is Back Which Tells You What Is It Say To Play Sakun Diya Know In Italian Ho Edit Se Abhishek Vinya Italian Home Made Terrific Vindhya Valley VS Existence And Movement Specific Playlist Ko India And You Cold Drink Question Awadhi Column In Question Quite Simple And When I Came Back From The Question In Which I Love You Want Just You And You Know You Tried To Control Urine Electro Steel Pipe Either Aishwarya And Meeting Is Very Important Richyou Tubelight Doing Over All In The Records In the field of every observe and keeping up meeting should and working of its annual about this feeling of every club but maybe not been stated wit piece that Bigg Boss from this problem turn off the disco light - Tweet A Roast Rangers Mixture Us To Renew VectorVector Due Point Of Innocents Who Gets Into Death After Two Years And Are Returning Welcome Back If you have not subscribed till kilometers then please subscribe now in Kollam This is not normally one site this gap video Below Sports Govind Check More Right Votes During This Period Between Not Been Placid In The Night Clubs Were Moving From Left To Right Choice Filling Peace Unity Project In This Office Notification Light Has Not Been Field After Two Years Not Two Years And In Which Direction To The Answer Is The Channel Like This Is The Left Roop Jagdish Singh's Album Play Kar Do Ki Hum Pisi Yeh Which Disha Mein Koi Album Play Singathiya The Consideration Mein Koi Shaak Nahi Se Ifiks Reel Doosri Gas But Desperately Mix And Pradesh Someone Else Not Right To Vote Bill-2012 Yes I Will Just Right To Vote Bill-2012 Yes I Will Just Right To Vote Bill-2012 Yes I Will Just Yes Go Explanation Inverter Check Ethically Reduce Rose School Moving Caused Soil Decrease Volume Decrease Affair Is The Meaning Of The Return Of The Day MP3 G Black Role Women Torch Dry In This Policy Nahi Se Alag Gendu Sam Lallu Left End Find The Columns Niketan School Amazon Rudraksh Ke Danon Ko Lamba Koi Problem Isko England This Is A Direct Link With Every Condition Not Met In All Directions And Not Minors Ise Subscribe Our Channel Like This Is Not Know Why Bigg Boss Vikas Bhaiya Using Producer Bhigo Of Withdrawal Dravid Bigger And Bigger Luvin Saturday Morning Another And Real Look Check Your Physical Activity Which Way Can Avoid Being Widowed Mother Died On So Let's Talk Person Magicians Of These Checking Using a Single String of So Imagine Images Set Play Suspected That Might Be Enter Ru Talking About This Channel Subscribe Like It Means Place for Astrophysics Please Subscribe Historical Experiment Again Play List Will Give You a Fine Understand How Will you do that solve bigger channel subscribe to-do solve bigger channel subscribe to-do solve bigger channel subscribe to-do list of 1000 2000 subscribe to e want 2051 S2 version to INS patient 14.5 want 2051 S2 version to INS patient 14.5 want 2051 S2 version to INS patient 14.5 subscribe 28000 212 history two plus two five to six 769 3000 free plus subscribe all the thing e So Sudhar Field Aap Nine Day Part Seat A B C D Pathak Hu Invent A Plate Singh Someone New Just Checked In This Crisis This Cut Means The Means Is You Can Us Them Yes Thank You Can Tell Him Half Spoon Schezwan Chahiye Means Of Two Minus one size on this 10 size maintain and placid in just 1 inch plus three latest updates text-21 subscribe three latest updates text-21 subscribe three latest updates text-21 subscribe 100 directly to turn on the damo mein deputy sp 7plus vo 11:00 damo mein deputy sp 7plus vo 11:00 damo mein deputy sp 7plus vo 11:00 update 11:00 to update 11:00 to update 11:00 to be the highest in religions Depression any new four verses also when placid in the most difficult to note that this app helps you that any industry world channel Radhe-Radhe that any industry world channel Radhe-Radhe that any industry world channel Radhe-Radhe Comment if he wants nothing but when e placid at just mark plus column in this channel ABS one liked The Video then subscribe to The Amazing To-Do List subscribe to The Amazing To-Do List subscribe to The Amazing To-Do List Play List Note Size Bittu - 2 Play List Note Size Bittu - 2 Play List Note Size Bittu - 2 Ki Hogi 100 Behav Do Padeer Left Back Left And Rome Band Lo Diner Choice Se Appointment In Odisha Dial On Phone Very Simple Was A Very Simple But What Do We Call The Formula Off a Link - One Plus Minus Call The Formula Off a Link - One Plus Minus Call The Formula Off a Link - One Plus Minus 40 Right 7 - 30 Inch Plus Sure - 151 - 03 40 Right 7 - 30 Inch Plus Sure - 151 - 03 40 Right 7 - 30 Inch Plus Sure - 151 - 03 2010 What Will Be the 3112 11-11-11 10 2010 What Will Be the 3112 11-11-11 10 2010 What Will Be the 3112 11-11-11 10 Subscribe To I Morning Since Field Are You Can See Slide 012 For Example History Playback India Thoda Is Purpose All Create We Pure Ghee * Thoda Is Purpose All Create We Pure Ghee * Thoda Is Purpose All Create We Pure Ghee * - 102 Previous End Next Step - 102 Previous End Next Step - 102 Previous End Next Step Any New Just Apply This Formula On Gender And He Gunawan Santan Ka Album Art In Its Affidavit Available Any New On This Side 2 And Settings Idly Check Again Using This Formula And Smart And Will Be Quite as all the different types of force so you can easily get it not rise in this way you can shake you all directions pending in all directions issued against Yash love you and size two one minus one will have a lot like love two minus one To Know the Question in Freedom Calling This Just Dance Between Sexual Hatred Unwanted This Time Will Tell You How to Make the Model of the Wild and Just Leave Every Idea Alone and Stop This Is A So This Will Bbc Plus Co Do I Am Not Explain Visa And Difficult Question Well As More About This Context And If Even Odd Jobs For The Video Cat Very Well And Assured Nris And Believing Linkup That Java Coding Description You Can Watch Explanation For The Cockroach Explanation Per Code In C Plus Co Dependent chakoti outward rise education lage tab pattern and structural ashram love just use different districts like and inspector are you something black lips to be active on different celebrity cold drink and destruction music dance and even today the explanation events to decode please make sure you like This Video Watch Till Now And New To My Channel Please Do Consider Subscribe Into Agony Of Great Help With Salgira Pinup This Video Lakshmi Apni Next Video Viral Bhi Recent Updates From That Branded 2009
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
1,716
Hello and welcome to this channel again this is Shaur Awasti and today we will talk about easy level problem of lead quote which is calculate money in lead quote bank so basically this problem says that there is a man named Harsi and this man keeps his money lead code in the bank. Saves and saves in this order that he gives a dollar on Monday, then on Tuesday he gives $ and so on till Sunday, meaning every day he keeps gives $ and so on till Sunday, meaning every day he keeps gives $ and so on till Sunday, meaning every day he keeps increasing one dollar and then on the next Monday he gives one dollar more than the previous Monday. It gives more dollars, okay and then so on and keeps increasing one dollar throughout the week, that is, every week it increases one dollar for the duration of the entire week and as soon as it jumps to the next week, it increases on the next Monday and on the previous Monday. Plus one is given, okay, so how do we understand it on the white board? Let's propose that if we have 20, that is, we have 20 days, then how will the person give that person will give a dollar in the first week, then he will give a dollar again on Tuesday. He will give D, then F, and then six, and then he will give sen. Okay, on Sunday, similarly, in the second week, that person will increase one dollar from last Monday, that is, now he will give two dollars, then give three, then on Wednesday, he will give four and so on, increasing one dollar each. If we talk about week three, then similarly in week three, he will increase it by one from the previous Monday, i.e. if we had increase it by one from the previous Monday, i.e. if we had increase it by one from the previous Monday, i.e. if we had given two from the previous Monday, then it will give three on this Monday and then further by one in the whole week. -Continuing to give three on this Monday and then further by one in the whole week. -Continuing to give three on this Monday and then further by one in the whole week. -Continuing to increase by one, it will give four, then five like this and here finally it will become nine. So if we look carefully, a pattern is to be formed that in all the complete weeks, the sum of seven terms will be 2 or 28 which is the previous sum. It is there, it will always be there, 28 will be there in everything, brother, okay, after that see, in this, one in every number has increased, by how much will the total become, and in this, the previous number has increased by two comparatively, from three to five. In this, if we increase two terms in seven terms then it will become 2 by 2 and it will continue like this is how much will be there in W Weeks i.e. in W Weeks, if it how much will be there in W Weeks i.e. in W Weeks, if it how much will be there in W Weeks i.e. in W Weeks, if it continues like this in W Week then 28 will definitely go plus extra. How much will be lost if there was 2 in three, then in double it will become 7, double minus and in 7, it is ok. Clear like this, if it becomes dl psv here i.e. in here i.e. in here i.e. in double dl psv week, in dub psv week, how much will go in dpsv. If we look at the week, then 28 will definitely go. If it is D, then D in will go into 7. In Extra, 28 will definitely go and from Plus D, then D in will go separately. Okay, it will be like this if we calculate week wise. Okay, now let's go. Let us understand through example, if we have 20 days, then what will be our first step? First step is to take out our complete weeks, that is, we take out the data of complete weeks. First, this is our first step. Second step, what will be ours? Second step will be ours. That the number of remaining days that we are remaining in the complete week is required to be in a small number of complete weeks, like it is suggested that it is 20, but if we divide it in the following way, then the six that is ours will be left in the reminder, so this is the number of days remaining, after that the task of calculating the remaining days will come. Let's talk about the remaining days. Now let's talk about complete weeks. Now what is the technique to find out complete? To find out complete, we will do A by 7 and to find out reminder or remaining, we will do from A model. Okay. This will come our peak i.e. Okay. This will come our peak i.e. Okay. This will come our peak i.e. W and this will come our reminder i.e. W and this will come our reminder i.e. W and this will come our reminder i.e. remaining day i.e. A, okay after that we will remaining day i.e. A, okay after that we will remaining day i.e. A, okay after that we will see how we will move, so first our task will be to calculate the total weeks, then how many total weeks are ours ? In the answer, what will we keep plus equal to, ? In the answer, what will we keep plus equal to, ? In the answer, what will we keep plus equal to, how many total works, how many doubles we suppose, then double time 28 was coming, then double time 28 will come, after that we add the extra part which was being added in this series. If we see our extra part which is being added, in which order it is going, this brother is a A, okay how 7 2 * 7 3 * 7 then like this n - 1 w - 1 * 7 2 * 7 3 * 7 then like this n - 1 w - 1 * 7 2 * 7 3 * 7 then like this n - 1 w - 1 * 7 then w * 7 so Basically, if we look at the then w * 7 so Basically, if we look at the then w * 7 so Basically, if we look at the number of weeks here, let us assume that if we are talking about w weeks, then w weeks will last till w -1, w -1 will last and w -1 i.e. will last till w -1, w -1 will last and w -1 i.e. will last till w -1, w -1 will last and w -1 i.e. how to calculate the sum of n - 1 terms. how to calculate the sum of n - 1 terms. how to calculate the sum of n - 1 terms. What will be the sum of n-1 terms n * n 1/2 What will be the sum of n-1 terms n * n 1/2 What will be the sum of n-1 terms n * n 1/2 Similarly here what will be w nad 1/2 in 7 Similarly here what will be w nad 1/2 in 7 Similarly here what will be w nad 1/2 in 7 then this will be added to the extra, this will multiply all the sens in the sub and this will find the sum of n minus terms. If we find out the sum of the two terms, then how much is the sum of the two terms? It is okay to go into the two terms by buying these. It is clear. If it comes like this, then this is our work. Now we will talk about the second step which is our reminder. Or how will we calculate the remaining days? Similarly, we will calculate the remaining days too. Brother, there will be complete weeks in the remaining days. If not, then if we remove the extra in the remaining days, that is, after completing two complete weeks, we will enter the third week. Here two will come, after completing two complete weeks, we will enter in the third week because here the value of pay week is two complete weeks for 14 days, after that we have six extra left, so we will enter in the third week, so first. So let us see, if we find out the sum of six terms for six days, then how will we find it will come out reminder into reminder psav batu, this is our sum is fine, after that after we have talked about the extra terms, after that the remaining. Our terms are getting extra added in days which were not getting further incremented in every week, so how much will be there in it, then how will they calculate, double is double week, okay why kept double because look if the value of double is double week i.e. To thi because look if the value of double is double week i.e. To thi because look if the value of double is double week i.e. To thi tod pv week me d in se lagta hai extra me to d into yahan pe add karenge w * 7 but yahan pe kya sen likhenge karenge w * 7 but yahan pe kya sen likhenge karenge w * 7 but yahan pe kya sen likhenge hum nahi yahan pe sen why not write sen because if there were seven elements here i.e. there were complete seven days. This would have been a whole i.e. there were complete seven days. This would have been a whole i.e. there were complete seven days. This would have been a whole week, but here there are not seven days, how many days are there, then we will add the remaining days, okay, we will make full return on this total will be our answer, once we see the code, first of all we We will take int weeks i.e. how many complete weeks are we take int weeks i.e. how many complete weeks are we take int weeks i.e. how many complete weeks are we getting and from n ba after that we will take e reminder how many days are left or how many remaining days will we have and represent them in aa will be a mud se after that we will take int answer. The first step was in the answer we What will we put in 28? We will definitely put it because all the tricks will go to our complete 28 plus what was going to our extra? What was going to extra? How much will it be? So I have already given the sen mark here. Weeks will be in 7 minus the sum of the terms. Weeks into this is Manav Batu. After that we will give the answer plus the addition of our remaining days. So how will we calculate the remaining days? That is also the same task, the remaining days that will come will be from our Ad Pv week, so first of all the remaining days that we will have in D Psv week, we will calculate their A, i.e. sum of we will calculate their A, i.e. sum of we will calculate their A, i.e. sum of A, then how much is the sum of remaining days in A Pv. Batu, ok, what will Plus do? That is, which week is he talking about? He is talking about us. So, how much do we do in the second week. Let's see in the second week. Here we were doing 7 days extra there which is getting incremented every week but here we will not do sen, we will do in arm i.e. but here we will not do sen, we will do in arm i.e. but here we will not do sen, we will do in arm i.e. sorry, we will not come, which is our remaining terms, why because here we cover seven days in the last week. No, only the remaining days are being covered in the last week, after that we will return our answer, so let's run it once and see. Yes, all the discussions are passing. Let's see after submitting once. Okay, so it is successfully submitted. Thank you so much for watching this video. If you like the video then like the video, subscribe the channel and see you in the next video. Till then bye.
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
916
Hello hello guys welcome oil hot midding on whatsapp subscribe And subscribe The Amazing Bramble your subscribe Video subscribe award from every subscribe to a vital role of all the universal what can you do subscribe my channel do n't forget to subscribe and subscribe to every word that IS PRESENT IN THIS FRIENDS LET'S MOVE Topics Every Living Being Observed and Subscribe Bill Sexual Frustration and subscribe the Video then subscribe to The Amazing Through Every Village in the Complexity subscribe Video that * Bodoland So How Can They Withdraw All that * Bodoland So How Can They Withdraw All that * Bodoland So How Can They Withdraw All Time Complexity Do We Need To The Amazing Distic President What's The Thursday Subscribe All India Seervi Maximo Mini Van In It One Time Movie Code That Facility To Avoid Drink David World Bank President Subscribe In This World And Give Result subscribe to the Page if you liked The Video then subscribe to the Page Bhi Neetu Jab Check Famous Traction Subscribe Thursday Newly appointed Pimps Usme Zameer Vo Da Ki Binae Bune Lutaye Note Events And in this target below gams divine name and divine form reduce kar lu ki and travels contact you can change withron it's not remember every video subscribe 999 hai ki va aadat dala check do subscribe and subscribe The Video then subscribe to the Page if you liked The Video then [संगीत] [संगीत] [संगीत] subscribe to the Page The present episode in it is not a subject in its implications for United otherwise is set a good person more wedding part electronics ko doctoral thesis on ki hindi dj are no when protest ko You can Tweet School Van Video subscribe and subscribe the Channel subscribe our
Word Subsets
decoded-string-at-index
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
String,Stack
Medium
null
463
Jai Hind in this video national grid problem number 460 free ireland per meter give way to learn great depression in this map and greater physical world one drops loop and create a physical 50 per cent of total arm hole 100 water is a silent in directions first Rot in directions sample which is ireland which control cars violet terrorist control amazon throw first president in a letter send a more can get government edelweiss where delhi and it will not agree and kin harvest its result further tick na direct jagdish completely surrounded by water and executive Violence in the district after more connected lands in the total area buried only one knowledge always circulated to weather dowry meaning water incident connect with water all around 100 Arvind cyber aspects are this year grind the work is the length of the square sizes we the great is Red color and vikram bhai darna taxes hour terming the perimeter of this gallant pride and in this korea money amount and the perimeter also 40 account all four sides 1234 which arm hole cancel country common FD account for and money on all its one beach directly lakhs subscribe Due to which the common example is 62 F Three 45 to 60 600 half please do subscribe our secretary and but increment parameters for at the same time flashback is not ready here but that look on kids fog - is not ready here but that look on kids fog - is not ready here but that look on kids fog - Deep Par meter reader for low medium player will find allocation policy Hey wait hair directions of generals of four in me abhi point looti day 384 MB [ __ ] me abhi point looti day 384 MB [ __ ] me abhi point looti day 384 MB [ __ ] hair main isi hour dowry increment Jabalpur Indians players like Pimple Sudhir 1.22 Indians players like Pimple Sudhir 1.22 Indians players like Pimple Sudhir 1.22 meter survey on sharing - 2019 meter survey on sharing - 2019 meter survey on sharing - 2019 born will get it well - to habitually - 2 born will get it well - to habitually - 2 born will get it well - to habitually - 2 eggs Hain to is look at only deti em well eat to sleep darshan born into three 45 to 60 past day that account yes bittu area this 2.1 account time yes bittu area this 2.1 account time yes bittu area this 2.1 account time woman this third 60 half hour click hair let steve wa on meter reader 1200 follow point i20 Election Gotland Plus Here Paint G Absolutely Zero Site Reader Came And Support I Don't Like This To Z Plus That Alarm Is Set The Breed Phase Pin Code One Ranger To Increase The Perimeter Back For More And Then Meter Classical 248 Same Time Minute Want IS GREATER THAN 20 FEB - To get forest rights Want IS GREATER THAN 20 FEB - To get forest rights Want IS GREATER THAN 20 FEB - To get forest rights Jain - meter is back to two Jain - meter is back to two Jain - meter is back to two - above this meter - 222 two - above this meter - 222 two - above this meter - 222 two 98100 was graded up that I did two - to get tickets to the people Janata meter two - to get tickets to the people Janata meter two - to get tickets to the people Janata meter 8 - e request oo to find your payment is 8 - e request oo to find your payment is 8 - e request oo to find your payment is clear that Electronic code the kid all cutlets submit loot literate train timings for millisecond faster than 900 to 1000 jawan information that common let year country sensor mortgage slide change only to places and sacrifice to which alarm select language is servi is doolan principle this oil scooter audience typing Kam or ya Chandran product hai soon only in the upper left side Top loot in the country from this 2012leave a comment for 98.4 loot in the country from this 2012leave a comment for 98.4 loot in the country from this 2012leave a comment for 98.4 percentage of RS for online submission for alleged premiere in next video will solve different plate any problem eat for watching hai
Island Perimeter
island-perimeter
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. **Example 1:** **Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\] **Output:** 16 **Explanation:** The perimeter is the 16 yellow stripes in the image above. **Example 2:** **Input:** grid = \[\[1\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0\]\] **Output:** 4 **Constraints:** * `row == grid.length` * `col == grid[i].length` * `1 <= row, col <= 100` * `grid[i][j]` is `0` or `1`. * There is exactly one island in `grid`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
695,733,1104
73
It is 100 friends, today we are going to see question number 108 Matrix Russia, it is good that the playlist of Swar Din Bhi Alarms Show should be checked in the description. A question is simple that wherever we are seeing many heroes, its whole soul is zero to the entire column. I do it, okay, I will explain the rest on the copy and I have written the code first, it is a waste of time for 10 minutes, it will take a lot of time to explain the job, so just look at it once and I will explain one line, okay coffee. But I understood, it's good, let's go, copy this show, there is a question, so I understood, don't do it, how can we do our first approach, look, I have already made four for you because don't know how many will have to be made, so I will explain. Right, and I am telling you the first method of doing it in 3 ways. Now it will come to your mind that there is a zero here, stop this whole thing, start this entire column, this is a test, right, you need to do something else in it. So look, my brother, it will be zero, so this also happened and if it becomes zero, then it means that now when the second or our will start, the rippling here, whatever it is, then people do this York, okay, it is going to be a vegetable ultimately but the method. This is wrong, how can some people live where the sacrifice was prohibited from drinking everywhere, knowing this, it will become a vegetable because of zero, otherwise what will we do, if we have got this input, then here we will create a copy of it, okay So from the article there is only one Ambrose and if he does not have it, then what will become of our complexity, our nursery space, that I came to the comment bank that it is Mintu, so what should we do, that our project is needed for Abhishek, that we will see what is available here can be made here. If it is starting then it is zero here too. If it is off starting then it is one. No problem, we will check from here and update it. If you want to see this thing, then there is no problem. If you see zero, then it is okay. Update. Yes, I will also do all this. It reaches zero and even below it grows from everything before or at the moment. If we look here at the ultimate answer, then it means not to tamper with it. There is life in the doctor's house, don't tamper with it. After seeing this, we definitely came to know that this is Let's go with zero, it has been made a hero, but now it must be made, you are seeing that rapid work is being done, so now we are coming to the fore that this is not a good way as the work gets repeated and due to this zero is open. Had to come, okay dad, our God will give this and this ultimate to all these heroes, one thing is coming to the fore that amendment is good, okay, you can batter it, definitely, what will be our method of battering, why don't we have such a space here? Let's say that update the Roar column here means we will check in the Road column here, if we get zero somewhere then if it is updated here then this is well also what name is this Guava Laharian column then definitely open plus will be done here with date. Even better than mm, by making an indirect copy, one thing is that if only one Rohit, one row is placed here and there, then what will happen, this is seen in this, there is one, no problem, seeing zero, I cut it from here, it said that if there is a mess here, then there is a mess. Do n't leave us, this is the thing, there is no problem, Zero is Zero, Das had bitten me to take milk, Zero was bitten here after seeing the messages, I moved the record aside, I forgot to tell you, see, this one and this one, neither will go here. Were also bitten - If you saw this zero, it has bitten here too, the - If you saw this zero, it has bitten here too, the - If you saw this zero, it has bitten here too, the thorn has got stuck here, third this stops from here, ok stop, I can't do anything, it stops from here, it is planted here and the principle of this, so ultimately you know all of them. Yes, they will give zero because our day is going to make it zero, no, the answer was this, but then we reduced the space complexity, we can go to Tehsil Batter, yes of course we can go, now what do we call this thing in these places. Doing this is making you goals. I ask myself brother, why am I making this, why not? If this is made then I will reach a little later to see whether it works or not. Growth serum will have to come. Now we are saying this. I used to put it in every corner unnecessarily, just put it on, don't put it on what's the problem? Look, what was this to us, it was like a point, it could be said that it was checking whether we want to update or not, so update within. Do it, what is the problem? Okay, now tell me, seeing that there is no one there, but the problem is that you are doing this work. I said, the matter is settled brother, so what do we do, let's take it completely, only two of it. Let's agree that you will say, if it happens in the operator, then let's start updating the column, okay, this is three, this update has to be done separately, Brahmin brother, let's take a separate take here, let's take a separate take on dishes here, the column is over. Gone is our tri-color man A call got over. Gone is our tri-color man A call got over. Gone is our tri-color man A call got marked Hit the bus Had to take Nicholas for this side stop Come on, we will have to make a record PM I was thinking then who was reading ok 1958 So see from the point of view of understanding that If I made 1236 E one off, then one thing happened to us, That is this column, British Columbia, I checked the three shops of this column, what time did we please, suppressed this alarm that was given, increased it and will we stop, what will we do? I don't see where I should put it inside, I am doing it for you, which is 22, isn't it, this is a less total number of runes, if added then it is - Vansh Hum, I placed it in this, the if added then it is - Vansh Hum, I placed it in this, the if added then it is - Vansh Hum, I placed it in this, the last one with tobacco saver, so I took it as election, initial Hum What will we do with this, we say it daily, okay, I will code it and show it, so initially I will pause it, then see what happened, go to the condition, what will happen to you, whenever our value, what will we do with them, first we will do inch life, okay and then where we Zero is visible, right, this zero is visible in these places, we will input that above it with zero, okay, if I tried carefully, then I made this zero, I fitted this zero, for this I did not just show it here, so I told you. Know, ultimately yes, zero is going to come, let me say it again a little, okay, do you like the mantra, when I saw the spot, then think brother, I will make zero above, ultimately the whole column fairy is going to cry, there is no problem with it, but we know that if we We will zero it initially, we will set it to zero, then we will just set it, okay do this, what will happen now wherever you are looking at me, John Carter is showing the tower, assume the position, two pose etc. Jahangir, he will cover the entire area. Remove it and make it vegetables, no problem, okay, rescue system above, so what to do in it, then look at the top where you will see the valley, I will explain it to you, okay, I feel that it is necessary to show you the code, so if the code I am not able to see you around, so see what I have done, I am showing it to the court and I am telling you what ROC I have taken in this party, but the row and column are reserved, this stitch is fine, we have made the row and column, it would have given the length to all the people. In matters, we have length, meaning the way we have given the list input, neither stop, we got the length, so for love, matrix neither matisse is good and this is a good thing, I forgot to tell that from to two and a half tola remain, I two, what have we done You did it, you wanted time complexity, sir, this page complexity, this or that phone, this is our cost base, rest of the work is going on inside, no, how much space has been reduced, I am explaining it with Thana Addition Solution, it is ok now. Initially, what did we do, you look at it, what to do is that I drove closer to J and did a loop of J for the Chairman column and what to do if I and J get out of the metro anywhere, okay, we are checking from this condition. If the American ID comes out to be zero, then what to do, its form is our protest, call me a column, then this song 2070 play call, what do we do with it, I do zero, like I see zero here, so I have updated it to zero here. Given, how are we jointing it, no, we have to make it zero, so let's do the same, so let's do the second step, if our I has increased from zero, why should a bad hero do this because I know that I am here, which is a stop. If it comes to 80, then for this I have taken a term memory, so I want to have units in it, so if you have increased from zero, then it means that I have to update everything, that is, if all the meanings are the same particular, then this one. Will update, there is CR here, so if it is just then don't do it brother, so for that, what I have kept in this case is that make it 8042, I have kept here that if we are able to see you are there, then this one is for today. If it is in time then what will happen to it in our place which we have made the system and from here we have made it the season, if there is a giver to start here and then there to do it and then it is bigger than zero then how come the second which comes first we We have made these benefits which can be made zero if you want, but the job is to stop the volume from getting impressed, we have only this whole thing, dip it long, this and this one, the entire column is done by the hero, so I have Your range will come, people will run, stop the previous one, take that run, it is okay for the column, then in my soul, whatever will remain, my call will keep changing, the day will keep changing, if it is zero, I will come, then who will remain with us too, then it will be any of these if If zero comes, then whoever has come to that particular place should go to zero. Time means, if even one person in the house is caught, if this gang is caught, then I will zero everyone up, down, front and back. I am fine if we go somewhere. If I get zero then oh and for whom am I doing the same work, it is important to know that for this area I am leaving the Engine Pacific University then you because I come in this, from zero those other villages make a little bit of mine that times And I had to make it 13 is 3. Now see, this is a different thing, saying this question has many good parts. Okay, how many parts are there in the 3 text questions of 23 thousand 1234 parties. Which ones will I show at the moment? Hit check here and if it is not necessary then tell me, this is showing by doing three in three, it is possible for the development of the bigger one, so all the things have to be taken care of, so what is the whole matter of it all getting changed, whatever I have said is ok here. So the first thing to do is to make them grow the lips. If zero is coming anywhere in these particular places then the skin will be sunburned. Throw the setting zero column that this is my column. Now I will definitely make this protest column here on this day. So their Do Olympic Sharad, it is 300 and this has come, so let's change your kind, so why have we called it the new hero, if this one of ours turns out to be zero, then this one will definitely come out, so this one, I have told you from the very beginning that this one is the pavilion. The one box is this particular column, if you stop then this one was eight zero, balance was made, then what will you do, if it turns out to be zero, then we will make this entire column a hero. Now see what I did in India, slide 2 one made eight zero. We will do two gas sister, when we place these, then if it turns out to be true, what will you do, we will keep changing the A column on zero and all this will become our zero, this is all right from my side, so I have come forward and I will ask. Lena, I tried my best, it seemed good to me, let's go in the next video, I am Mukesh, you are watching it, okay, let's go bye.
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
7
hello everyone today we're going to be doing a elite code medium algorithm question we're going to be doing this submission in python we're going to take a look at leak code number seven reverse and integer so the idea here is they're going to give us an integer it's going to be no greater than a 32-bit integer to be no greater than a 32-bit integer to be no greater than a 32-bit integer and the expectation is that we reverse the integer and return the reverse of that integer uh similar to if it were a string so let's take a look at the examples they provide us example one so we have an integer of one two three the expectation is the output is three two one example two is negative one two three the expectation is negative three two one so the negative sign remains at the beginning of the number as numbers should be and then lastly we have this example of 120 which is equal to 21 when reversed uh because they're leaning zero doesn't mean anything okay so there's a couple of things that i think that we need to do to solve this problem so i think initially we're probably gonna have to take a look at uh reversing uh the integer and we can do that by casting it as a string we also don't want to take that negative sign as part of the string so we're going to cast it as absolute value so let's go ahead and do that first so what we'll do here is um just drop in a note convert for an input into string okay great so let's keep a running um variable of a output string to keep track of the changes that we're making so let's make our output string is equal to uh the absolute value of x which is our input here we actually don't want that we want to take the absolute value we're gonna cast it as a string and we're going to reverse the string so what this gives us is a the string of the original input in reverse without the negative sign if the negative sign exists all right uh so the next thing that we probably want to do is want to check for a 32-bit integer so if it's a 32-bit a 32-bit integer so if it's a 32-bit a 32-bit integer so if it's a 32-bit integer we want to return a zero uh as stated here in the problem so let's take a look at doing that so let's add a little note here check if 32-bit little note here check if 32-bit little note here check if 32-bit so what we can do is we can just say if the integer version of o string is greater than 2 to 31st and i grabbed this to the 31st right from right here in the question itself so they helped us out a little bit there without having to look up how to get that value and if it's greater than uh to the 31st then let's uh let's keep our o string variable in place and set this to the string of zero okay great so we've accounted for reversing the integer we've accounted for 32-bit integers the last thing we for 32-bit integers the last thing we for 32-bit integers the last thing we want to do is going to account for negatives so let's go about this by now checking let's do let's add a note here next check if orange was negative okay so we can do a l if uh if the original x input was less than zero then what we can do is we can take our o string and put in a negative sign in front of that o string and then add in the o string so now we've checked for a negative value uh if it has a negative value drop in that negative sign in the beginning of it great and then the last thing we want to do is we want to return that o string but as an integer so we'll return that our output string and then let's cast this as integer great so i think we've got all the use cases uh taken care of uh we're reversing the original integer we're checking to see if it's 32-bit we're also checking it to see if 32-bit we're also checking it to see if 32-bit we're also checking it to see if it was originally negative and adjusting accordingly and we're going to return the output string let's run the code and test to make sure that this solves for it does all right let's go ahead and submit this so here we go our solution was 94 faster than other submitted solutions uh be sure to like subscribe and leave comments if you've enjoyed the video also if you came up with a different solution using a different technique drop in the comics alright thanks
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
172
172 factorial trailing zeros from lithgow given an integer and return the number of trailing zeros in n factorial so the question is asking us an integer is given we should calculate the factorial and see if it has any trailing zeros three factorial is going to be six and six has no trailing zero and for this example five factorial is going to be 120 and it has one trailing zero and zero is going to be zero let's see how we can solve this problem to solve this problem efficiently we can use um like math functions so for doing that in math for calculating the number of trading 0 in fact in factorial and what we can do is we can get the number and we can divide it by uh five and uh as you see here we can divide it by five and some of that number uh until n is bigger than zero so for this case it's going to is going to be seven divided by five is going to be um one and we have only one zero here and the remaining is two which is not uh like we cannot divide it by uh five anymore so we are going to have only one zero for ten we divided by five it's going to be um divided by five and sum it up here and it's going to be two zeros and for 15 it's going to be three zeros and for this one is going to be 37 trailing zeros because as you see if you want to calculate the factorial of that number it's going to be very costly it's going to take so much time and it's going to take so much memory and like most of the time it's impossible so it's whether to do that it's going to be the time complex is going to be logarithmic because we should divide the number by 5 constantly until it's not bigger than 0 anymore and the space complexity is going to be constant because we are not using any extra space thank you
Factorial Trailing Zeroes
factorial-trailing-zeroes
Given an integer `n`, return _the number of trailing zeroes in_ `n!`. Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`. **Example 1:** **Input:** n = 3 **Output:** 0 **Explanation:** 3! = 6, no trailing zero. **Example 2:** **Input:** n = 5 **Output:** 1 **Explanation:** 5! = 120, one trailing zero. **Example 3:** **Input:** n = 0 **Output:** 0 **Constraints:** * `0 <= n <= 104` **Follow up:** Could you write a solution that works in logarithmic time complexity?
null
Math
Medium
233,809,2222
838
Hello Everyone Welcome to Date Whose Light Chalu Necklace Questions Ask Dominance in This Question Will Give in This Inspirational Lines of Side and Applied Chiffon 20 York The Video then subscribe to the Page if you liked The Video then subscribe to the Video then Jhaal ke dask in the space provided a question is pair then those particular download in one particular direction and gifted to its adjoining driving direction Bulandshahr Uttar Pradesh and subscribe a push domino liquid 383 e want lips recover basically fluid question and bihar applied for 10 to meet Again Tried To Destroy Two That Taurus Applied No Flight Mode Rules And Applied Left Songs Tamil Email Want To Tell What They Final Date Of This Particular Domino Most With Water Is Particular Dominoes Under The Influence Of We The Meaning Of This Is The Winner Of The world of the world of the world of the unfit certificate one from this left and right cancel must subscribe that second example notification beehive something dominoes like this dot f9heart I'm writing this life in the top the right one at the bottom so let's Start the process since movie and left direction settings from left most terminal going after 10 seconds that 2 minutes not under the influence of benefits of Bigg Boss minutes not under the influence of electronic no in coming days left for winter storm in these directions In this subscribe and subscribe that Europe's literal political interests were already applied for this indirect left in coming years will not remember and being applied 40 will understand why will hide from subscribe and subscribe this Hair will do subscribe to again witness right forces right direct forces Welcome to in the Resurrection Remix Aaj Dil To Minuteon is not under the influence of Let's move with the Thursday subscribe And subscribe The Amazing Minute Yes Direct Left Suicide Note This Team Is This Domino Also Present No Right For You Friends Here Director Task Force Subscribe Share Is Next Vihar Directly Force The Move Ahead Neck Switch Off Is Radhe-Radhe Switch Off Is Radhe-Radhe Switch Off Is Radhe-Radhe Video Related To Right Here Is Next Vihar Left For Get A Beat You Don't Have Any Rights In Kashmir Valley Rail Hai Hair Oil It's Aircraft Sorry No Right Course Not Right For No Rights A Place To Also Do The Same Thing For The Left Vansh Sexual The Video Then That Boat At Least Diligence List Of Bacha Karna Hai So Let's Start With This Particular Index Settings 1204 Giving Up Till Last Interview Important Yesterday Morning Sports President Here's Electronic Cigarette No Right On Thursday Reality Of Direct Loop Courses We Do n't Have Any Course In Right And Left subscribe id jo hair bhi hum direct right source to right vital hai jo hair bhi half Buddha forces left and right vich one is right or left for the way subscribe Video subscribe and subscribe the Video then subscribe to subscribe our A strong support this particular case That Damage Stranger Craft And Once Again It's Not Very Clear That Plastic Black I'm Just Talking About This Particular Entry And Vitamin C Budhiya Bodh Bhikshu John Electronic Right For Unity Hello How Far Is Loop Fast Units How To What Will U Get It Will Stand Upright Bigg Boss the force in the left and right it goes that feels great dot has let's move ahead next week have difficulty in text that bihar direct and indirect electronic tripod avoid unwanted defense of its righteous distance of lights S2 subscribe this Video subscribe that Lakshmi Tour That ad placement process will you get direct fluid play list of list talk about this particular and its benefits right in the right and left in the river under the influence of spot-fix right interactive way influence of spot-fix right interactive way influence of spot-fix right interactive way i left interactive two units of which will be stronger Demand Disclosures Do It Will Come Into A More Electronic Pisces Next Swift Color Index Mercury Is Chain Difficult Dominant Leg Wave Raw I Left SisOne Interview Right Forces Two Units Of Which One Has Strong Dimple Yadav Andar Disclosed That Means You Will Get Left A Glutton Subscribe Daughter ki dancer bellcoms mail.ru daughter of lord ki dancer bellcoms mail.ru daughter of lord ki dancer bellcoms mail.ru daughter of lord subscribe to subscribe to subscribe to 24 new light bill gautam bhai all you avoid stop the video luta doo to aaiya hu main 1200 sirf wa typing case not don't worry i am lips dry exam Clear samsung note specified in the best slide 200m writing two enrich list vs subscribe and subscribe this Video subscribe - no subscribe - no subscribe - no torch light country to process will - 142 torch light country to process will - 142 torch light country to process will - 142 is next this amla facts witch directly floor space index 1111 in this will be transport weight slapped so 80 Behave Daughter Will Come From It Will Not Leave That Uninterrupted Process Coming From Absolute Value 11:00 Hai Value 11:00 Hai Value 11:00 Hai Next Very R A Direct Right Course Vihar To Stop The Process Of The Internet Left For Coming Anil - Ban Here Internet Left For Coming Anil - Ban Here Internet Left For Coming Anil - Ban Here Subscribe School X Hai Next This Amla Directed That Will Get Updated Daily Updates Friend Features Loop Subscribe To The Channel Subscribe To Connect With Adi And WhatsApp Benefits To Connect With Hubs Lite Direct Right Course Will Updated To Minus One Requested Not To Left Side Interact Club School Contact Us That Bihar Dot Hai Divya Forces - 1 Bihar Dot Hai Divya Forces - 1 Bihar Dot Hai Divya Forces - 1 Hain Next Week Have Left Attentive And Joe Here Next Bihaav Dot Seervi And Updated One I Will Be Amazed With Lalu Yadav Indexes Button More A+ B+ For The Right In Axis Bank A+ B+ For The Right In Axis Bank A+ B+ For The Right In Axis Bank Main Aaj Let Start The Post One Is not doing them in different sectors will - - - doing them in different sectors will - - - doing them in different sectors will - - - subscribe to I am here director right course at sports complex ki film kaun hai on which still transfer to its right will increase only very daughter loot joining free subscribe to subscribe our that and Law Will Update To Minus One Devnarayan Forces And Radhe Ka Naam Bhi Hafte Building Do Ready Is And Electronic Solution Depending On Which One Electronics A Flat Stomach Ke Behav Left Votes Is Possible In Tax Raids In This Will Help You Will Help That Bihar - ban hair and minus one every vote are That Bihar - ban hair and minus one every vote are That Bihar - ban hair and minus one every vote are not under the influence of fuel left side subscribe to main sunil plane rl notary lar taylor swift free busy index dum in the left and vihar phase subscribe which one's lust for two to three 1730 jab School Arya Hai Latkan Process V0 Three Liye Subscribe Both Parties Will Distance Id A Plus Bell Ko Press Releases Person In Which One Is Following Subscribe Left Appointments Minus One Will Have Next Vihar - Anil Android Vihar - Anil Android Vihar - Anil Android Hai Next Vihar Phase Electronic Subscribe - - - - - Subscribe To New Delhi Option Looks Landing But Its Very Simple Guys Whose Twitter Shot Fuel Understand Only Absolute Same Thing But Spiderman And Posting Agree Find The Length Of Account Number 2 Minute Vihar Arzoo Hai 1.5 With Right Fundamental Rights Available Hai 1.5 With Right Fundamental Rights Available Hai 1.5 With Right Fundamental Rights Available Dull Loot - Encounters With Current Affair Dull Loot - Encounters With Current Affair Dull Loot - Encounters With Current Affair Midcap Index Under Consideration To Find Out The Current Is Updater Laptop Se Play List Continue Protests Echoes Of Doing The Same Thing For The White A Direction Husband Diner The Withdraw It's Starting From Where Winds Going West Is The National Institute Of What Is The Current Minute if you liked The Video then subscribe to the Page if you liked The Video then subscribe to This Is Creative Director All Points Answer Site Rating From Thursday Is The Current Daminiyo Is Equal To Date Ke Din By Check Which One Is Closer To the current domino oil pickup the phone you this mic current domino here left right and center sign dat volume to my answer unless talk about this particular place where in the closest to death in the bab.la the bab.la the bab.la that I pickup account se intact staff nurses if you The defined difference between there voices of mid-day voices of mid-day voices of mid-day e want in case - lt extension e want in case - lt extension e want in case - lt extension 2012 - in the world no internet and 2012 - in the world no internet and 2012 - in the world no internet and direct left side per current index absolute between maximum volume that is similarly for the white department their is the difference between the Between switch of realization force that this particular and that it will distance and absolute cell address to subscribe to that indra and is written during format of the answer and unlock tribes of this is updated that if you want to depression id please don't forget to like share And Subscribe My Channel Thank You Need Every Day And Stay Tuned For More Updates Please Subscribe Like This I Want To Me Chilation Person Then Almost Be Doctor Absolutely Silent Without Any Fear And Please Subscribe Button All The Best Good Bye A
Push Dominoes
design-linked-list
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string `dominoes` representing the initial state where: * `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left, * `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and * `dominoes[i] = '.'`, if the `ith` domino has not been pushed. Return _a string representing the final state_. **Example 1:** **Input:** dominoes = "RR.L " **Output:** "RR.L " **Explanation:** The first domino expends no additional force on the second domino. **Example 2:** **Input:** dominoes = ".L.R...LR..L.. " **Output:** "LL.RR.LLRRLL.. " **Constraints:** * `n == dominoes.length` * `1 <= n <= 105` * `dominoes[i]` is either `'L'`, `'R'`, or `'.'`.
null
Linked List,Design
Medium
1337
767
hey everyone welcome back today we are going to solve problem number 767 reorganized string first we will see the explanation of the problem statement then the logic on the code now let's tab under the solution so in this problem we are given a string and we need to arrange this string such that we don't have repeated characters continuously right so here we have two characters repeated in the string right so we need to arrange this string such that a b and e so now we don't have a repeated characters continuously we can have duplicate characters in The String but it should not be arranged consecutively so while we arrange the string we should not miss any character all the characters should be included in the rearrangement right if we can't rearrange the string we need to written empty string so now we will see how we are going to do this so initially we are going to have a dictionary where we are going to have the character and its count so here we have three A's and we have the count as 3 and for B we have 2 and for C we have 2 right so initially we are going to have a maxi where we are going to store the character and its count where we are going to store the count with a negative value since we cannot perform Maxi directly in the python so we are going to have negative values for the count right so here we will be having the count with a negative value that is negative 3 and a that is the character and negative 2 and B and negative 2 and C right so then we are going to have three variables where we will be having the result list then to track the previous character we are going to have previous character variable and we are going to have previous characters count as well so initially we are going to pop the maximum count from the maxi that is the negative 3 and a right so this will be our current count that is negative 3 and the current character is a so we are going to append the character a to the result initial right we are going to obtain this a to the result so we are going to initialize previous count as count plus 1. so here the count is negative 3 and plus 1 is going to give me negative 2 which means I have appended a to the result and I am reducing the characters that is the as count by 1 right so the previous count becomes negative 2 and the previous character is a now we pop the next character from the Maxi that is negative 2 and B so count will be negative 2 and character will be B so now we need to append B to the result after appending we need to check whether previous count is less than 0 which means we are checking whether we need to still append the previous character right so in this case it is true so we are going to append the previous count and the previous character in The Maxi that is still there are two characters of a yet to be appended to the result right so after doing that now we are going to make the previous count as count plus 1 that is we are going to get negative 1 and the previous character is the current character B so now we need to pop the next maximum element from the max Heap that is the negative 2 and C so now we need to append C to the result so then we need to check whether the previous count is less than 0 which means is there any previous character yet to be appended to the result right so here we are still left with one character of B right so we are going to append negative 1 and B to the Maxi that is the previous count and previous character so after doing that we need to add 1 to the count we are going to get negative 1 and negative 1 will be our previous count and the previous character is now C so if we keep doing this one we are going to have a b c and a b right then finally we need to join all the characters the result to get our final answer right that's all the logic is now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we are going to have character count dictionary where we will be having the character and its count so here I'm using the counter function then I am having the max Heap where I will store the count and its character right I'm storing the count with the negative value so then we are having the result array then we have the previous content previous character in order to track the previous characters count and the character itself right which has been initialized as 0 and empty string respectively so then we are going to have a while loop we are going to run the while loop until the max C plus NT right we are going to pop the maximum count and its character then we are going to append the character to the result then we are going to check whether the previous count is less than zero If the previous count is less than 0 which means we still have previous character to be appended to the result right so we need to append the previous characters count and the previous character itself to the max heat so then we are going to initialize the previous count by adding 1 to the current count then we are going to store the current character as my previous character right so after Max sleep is empty we need to check whether the length of the result is equal to the length of the actual string that is the original string if it is true we just join all the characters in the result we just return that one else we return the empty string right that's all the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos keep supporting happy learning cheers guys
Reorganize String
prime-number-of-set-bits-in-binary-representation
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Math,Bit Manipulation
Easy
191
65
hello and welcome back to the cracking fang youtube channel today we're going to be solving leak code problem 65 valid number before we do i just want to ask that you subscribe to the channel i'm making a lot of these videos for you guys and i want to grow help me grow subscribe to the channel all right a valid number can be split up into these components in this order a decimal number or an integer an optional e or e followed by an integer this represents scientific notation a decimal number can be split up into these components in this order a sine character plus or minus one of the following formats one or more digits followed by a dot followed by one or more digits an integer can be split up into the following components in this order an optional sign character plus or minus one or more digits and for example all of the following are valid numbers two zero eight nine minus zero point one plus three point one four point minus point nine two e ten minus nine zero e e3 on and on while the following are not valid numbers a b c obviously that's a string one a one e three nine e two five minus six minus plus three nine five a five four e five three given a string s return true if it is a valid number so this question isn't necessarily that difficult it's marked as a hard and the only reason it's hard is because as you can see there's so many cases that we need to consider and we need to capture all of these edge cases to make sure that we actually get our final solution so this question is more of can you catch every single edge case and handle all the cases in a logical order uh than it is of coming up with some crazy algorithm to solve it's more of can you cover all of your bases so instead of going over why every single one of these is valid or isn't valid i think what's easier is just if we go into the code editor and we're going to type this out line by line and we're going to explain why things work why things don't work so i'll see you there and we'll walk through this it's quite a long question it's quite a lot of code but everything will be gone over line by line and explain meticulously in a way that every single edge case is gonna be hit and in a way that you can easily understand it so i'll see you in the code editor okay we are in the code editor now it's time to write the code so we know off the bat that you know there's a few things which are not going to make a character sorry which are going to make a number invalid and the first is obviously we can't have more than one decimal in a number right it doesn't make sense we never have like 4.1 or 4.1 4.1 or 4.1 4.1 or 4.1 right that's not a valid number so we know off the bat that we can only use a decimal once so let's keep track of that so we're going to say decimal used and this is going to be false we haven't used our one allowed decimal yet now another thing that needs to happen for us to have a valid number is that we need to see at least one integer right we could have minus e which generally is fine because we're allowed to have ease for scientific notation but if there's no number then this isn't valid right we need to see at least one number so we need to keep track of whether or not we've actually seen a number somewhere here so we're going to say number seen and this is also going to be equal false because we haven't seen anything yet what we're going to do here is we're going to have a while loop and we're going to iterate character by character and check each character as we go along and if ever we get something that's invalid then we're simply going to return false otherwise we're going to keep going and if we're able to get to the end of the string and we haven't returned false and we have seen at least one number then our number is valid otherwise we return false so let's go through this so we're going to go index by index so obviously we're going to initialize our variable to 0 because that's the first index we want to check now remember that in our thing we're allowed to have a plus or a minus which is allowed to happen at the beginning of a number right or after an e so we want to check whether or not the first character is a plus or a minus so we're going to say if s of i equals to plus or minus then that's allowed right we're allowed to have a plus or minus at the front of our number so if this is the case we want to move our i up by one otherwise it's going to stay at zero now what we're going to do is we're going to say while i is length less than the length of s we want to get the current character which is going to be s of i and now we need to start checking all of our edge cases so remember that the only letters that are allowed are these lowercase e or uppercase e and that indicates that we're going to have a scientific notation if we have any other character it's immediately invalid so we're going to say if currentchar dot is alpha so if it's a character we want to check whether that character is an e or an e so we're going to say if kerchar is not in so if it's not in lowercase or uppercase e then we return false we have some character in here that's not valid we get rid of it otherwise what we want to do is we need to make sure that we've actually seen a number before we've gotten to this e if we look at our example of not valid things this is not valid for the reason that we have not seen a number before the e we need to see a number before the e right so we want to check whether uh we've seen a number at this point and remember that when we have scientific notation um when we have e or e it must be followed by an integer so at this point if we've seen an e we need to have seen at least one number before it and whatever values come after the e so for example in this case e minus 1 this needs to be a valid integer so we're going to write a function and we'll do it in a second we're going to say self dot is valid integer and we're going to pass in the string right so s of i uh everything after our e if s of i is our e then everything after it must be a valid integer if both these are true then our number is a valid number if not then it's false so we'll do the is valid integer later because it's actually quite simple and we can reuse some of the logic that we're going to use in this main function so this handles the first case where we have a character right and we made sure that it was an e if it wasn't we return false and if it is we want to make sure that we've seen a number and that the number after it is a valid integer cool now let's handle the next thing we can see which is going to be a decimal right so we're going to say else if the current character is a decimal then what we want to do here is check have we already used our one allowed decimal so we're going to say if decimal used so if we've already used it then we now have a second decimal which is not allowed so we can simply return false otherwise we just want to say we've used our decimal so decimal used is now going to be equal true and we can basically continue to the next thing otherwise what's something else we could see well we could see another plus you know like in this example so at this point we've already handled the case where the plus occurs at the beginning so if we now see and we moved our index up right so if we now see a plus or a minus it's in an invalid location therefore we want to be returning false so else if the current character is in so if it's in either a minus or a plus then we know that this is invalid right this would be this case the minus plus three this isn't right so if this happens we can simply return false otherwise the only thing left right because those are the only things that we're going to see if you look at our kind of constraints here we're only going to see english letters both uppercase and lowercase which we've handled here you might get a plus or a minus which we just handled here you might get a dot which we just handled here or a you know digit so the last case is that we have a digit here which means that we have seen a number so we're going to say number oops this should be numbers seen here uh number so that means that we've seen a number so we can mark it as true otherwise uh the last thing that we need to do is simply just increment our i by one and we are going to go through our while loop now i mentioned that uh the last thing that we need to do once this while loop uh breaks because you know we're done um either we'll have returned false inside of here or we're now at the end of the loop and the last thing that we want to make sure is that we've actually seen a number because if we make it through and we haven't seen a number then that means that this isn't a valid uh thing so you know we can have the string with just a minus right so this is valid because it's a minus at the beginning but since we haven't actually seen a number this isn't a valid number in and of itself so all we need to do is return number seen so if number seen is true that means that we've seen at least one digit and none of these other conditions were broken therefore we have a valid number so at this point the only thing that we have to do now is actually just write our is valid integer which is going to be essentially the same logic we have here except it's going to be a little bit simpler because integers are different from the numbers that we can accept before an e so let me just make sure i don't mess up my indentation here this should be fine so we're going to say def is valid integer and this is going to take a string right we'll say string to test right so what we want to do is we actually want to make sure that we have a string passed into us it could be the case that you know slicing our original string s from the index i plus one to the end actually is an empty string right it could be the case that our uh s of i is actually the last index and it was like an e here therefore there's nothing after it which is not valid right every time we have an e there must be a number after it otherwise it's an invalid right one e is not valid because there's nothing after the e we can't just have e by itself so we want to check whether or not the string is actually a valid string not empty so we're going to say if not string to test so if our string is empty then that's going to be false because obviously an empty string is not a valid integer so we return false here and the same thing for an integer we're going to make sure that we've seen at least one number right so we're going to say number seen and obviously we haven't seen a number yet so this is false and we're going to do the same thing that we did in our you know main function here which is going to be we're going to set i equal to 0 and we're going to say we want to check whether or not the first character in our integer is um you know a plus or minus because look an integer can be split up into a sign character and then one or more digits so let's handle the case where we actually have a sign character so we're going to say if s sorry string to test of i is actually in plus or minus so if it's a plus or minus that's fine because it's the very first character so in this case we just move i up and that's totally allowed now we're going to have the same while loop that we had before so we're going to say while i less than len string to test again we're going to extract the current character we're going to say current character is going to be string to test of i and now as the only thing that's valid in an integer after we've already handled the potential sign character at the front is only digits are allowed so if we see anything that's not a digit immediately disqualified so we're going to say if uh not kerchar.is digit so if the current kerchar.is digit so if the current kerchar.is digit so if the current character is not a digit immediately disqualified false it's not an integer otherwise we simply say number has been seen so we're going to mark it as true and we're going to move our i pointer up and now once this while loop breaks either it will be because we disqualified the number uh and it's not an integer because we saw something that wasn't a digit or we've now hit the end and now we simply again need to return whether we've seen a number so we're going to say return number scene so that is how we write the is valid integer function and remember it's going to be used here when we see an e and just to recap when we see an e we need to have seen a number before it right because if we look at this example e3 is not valid because there was no number before it right and we need to have a valid integer after it so right and then this one it does have a number before it but because the number after the e is a decimal obviously that's not an integer so it's not allowed everything after the e must be followed by an integer so that's why we have the we've seen a number by this point and everything after the e is a valid integer so i'm just going to run this make sure i haven't made any bugs here just because it's quite a long solution and it looks like cool it is running now let me submit this and false oh boy um let me see decimal used if that's true hmm why is that false i found this stupid bug it's actually if s of i in uh this one here i think i had uh equals so that is why it wasn't running uh that recording was like 12 minutes long i'm not gonna re-record it so uh let's i'm not gonna re-record it so uh let's i'm not gonna re-record it so uh let's i think now if we submit it should be fine okay perfect there we go yeah um stupid mistake there i had it right down here but uh up there i just said double equals so okay so what is the time and space complexity for this algorithm well the time complexity here obviously we have to in the worst case go from left to right over our um you know number here all right our string representing a number so in the worst case we're going to have to go from left to right and process every single character so this is going to be big o of n where n is the length of the string right so that's your time complexity and our space complexity is in this case all we do is define two variables uh to basically keep track of whether or not we've seen a decimal and that's essentially it so our space complexity is going to be big o of one so that is how you solve this question like i said this is more handling all of the edge cases reading the question making sure like what's a valid input what's not a valid input this is something that you'd want to kind of discuss with your interviewer uh and figure out all of the cases ask questions obviously on leak code we're given all of these examples of valid integers uh valid numbers and we can kind of derive what is and what isn't one but typically this is something that you'd want to kind of like discuss with your interviewer and figure out uh all of those cases um and you know that's really where this question's meat is it's really you know the details of like all of the edge cases and making sure you cover all of your bases again this question isn't really that hard all you're doing is iterating over a string from left to right but you know there's just so many places where you can go wrong so many things you can fail to check if you don't kind of take the time beforehand to kind of jot those all out or think them through then you can be in trouble but you know videos like this basically just walk you through all the cases and explain it line by line and it should be relatively easy to follow so that is going to be solution for valid number one of my favorite problems it's pretty straightforward there's just so many uh edge cases so it's definitely a really good interview question and uh if you're interviewing at let's see who asked this um looks like facebook and linkedin uh there's a good chance that you might come across this so definitely one to know but it's pretty straightforward once you've seen it once you can basically kind of just remember how you solved it and it's quite easy anyway i'm gonna stop rambling because this video is probably 20 minutes long anyway thank you so much for watching if you could please leave a like and a comment it really helps the youtube algorithm if you want to see more content like this please subscribe to the channel i have a ton of videos and i plan on making a whole lot more anyway thank you so much for watching and have a great rest of your day
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
1,920
Them from American Today they will discuss the problem that is the way are from permission okay so the scene is something that you must be given deep and that is you have to shoot that must be ravish ambulance and which is our answer of I is that bare shot name injury There should be flu due to eye and IQ hero, you will return it simply, ok, look, the example is 113, like the name is given as stick, you should create something, this is 021 something and whatever should be our output, it is given in the explanation. That whatever it is, it has to be melted, how will your name film self, norms of one day, trade on these attacks, even if we stop at the start length is fine, then example second is also given here, in this manner, follow the Metro Chief e. So let's read the comment, query, note that the value of lens can be from one to thousand and the norms for us is the value of beating, it can be from zero to name start length that your other person can have a or one approach. That's our simple, we don't have to do anything, we can make a knotted, simple, we can run a loop and run the form in window 10 right then simple can return murabba a answer ok but you don't have to follow this approach. What is said, you can be solved without using extra space, it is ok without using space, if we fold it, then how can we solve it, without you think, extra space is ok, then the address given to us, the name has to be returned correctly, the class is ok. If you modify the points then I will show them to you. Look, before discussing this question, I want to share some points with you, this is an example of like, it is like you have bought 10th class from the same value case. The key value is for. Okay, now I write this in something expression, this request is to z plus a b models and chicken ok score and multiply. Inside multiply it by n ok where the value of end could probably be something. 6 Take pride Take a part Let's say okay so in order to get the value of me what I can do I can simply to make a request to a small earthen pots see how it went till a first remained a Plus B Key Value Team Key Value Floor End Key Value $600 6 Day Test For Simple * * * * Can Give Thee To $600 6 Day Test For Simple * * * * Can Give Thee To Kitna Yeh 07630 Bhi Apne Kya Kar Can 2017 More Dhan Apne Ab Hume Ek Value Dobara Hume Mil Gayi Kitni And what can we do to find the value of is simple that they can do something like this how the same person 2017 above okay you 2017 models and divide and only this will be off okay so its simple that how many did they become and Okay, so this is the approach, I will follow your approach here. Is it ok in the question? Okay, so what do you have to do, Sonam, that you have come, what is to be done in that, this request is that plus tod name that is that fi aplus a b models and I had to tell my story, name is fennel, my name is Chaupaya, okay, so I will do it, name is this, phone number is shop, okay, what did I have to do in that, 99 models have come, end is okay, models are at end, key value, end key value, open loop, let's take out their balance. The value of some such yogi is to be divided by n and then multiplied by the fans. It is simple that your semicalculations were that Android 4.4 above is treated, it is that Android 4.4 above is treated, it is that Android 4.4 above is treated, it is also run the same way in Adipose 208 Sexual Eye Plus here too. Wrapped open hands, okay, no need to write, what we have depended on above, okay, what to do here, next step, I have found saunf is equal to name, saunf, I am a model, what are the models, and okay, so this. I will postpone the comment, let's comment immediately, first I am raising your show accepted, our vote is expected. Okay friends, now let's submit this one. I am Mukesh, our solitaire has finally been successfully submitted. Okay, see you in the next video. Till bye-bye see you have a good day
Build Array from Permutation
determine-color-of-a-chessboard-square
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** **Input:** nums = \[0,2,1,5,3,4\] **Output:** \[0,1,2,4,5,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\] = \[0,1,2,4,5,3\] **Example 2:** **Input:** nums = \[5,0,1,2,3,4\] **Output:** \[4,5,0,1,2,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\] = \[4,5,0,1,2,3\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < nums.length` * The elements in `nums` are **distinct**. **Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Math,String
Easy
null
763
hey everybody this is larry this is day four of the september league daily challenge uh hit the like button hit the subscribe button join me on discord and let's get started on this farm so i'm solving this lives i don't know what it is so let's see how it goes petition label uh let's see uh a string s of lowercase english letters okay you want to partition them into many parts you should add it at most one product return okay so i think 500 uh i think some sort of hmm i mean i'm thinking of that there's some sort of greedy-ish some sort of greedy-ish some sort of greedy-ish uh it feels like this not greedy but something i mean maybe it's greedy but some sort of greedy um constructive e thing will allow us to do this um but the idea is that okay so first of all there's only 26 characters so we could probably build something based off that and it'll be 500 which maybe doesn't matter that much but basically uh you have 2 you're going to have at most 26 intervals right where you know that um each character will only be in one partition so that means that no matter what um so a for example let's just move the space for a second that means that you have to use all of it right so that means that a will go all the way up to here maybe this is not a good example because this is an actual overlap um okay maybe i'll do another example right like let's say a is here right um so then oops so you know that it has to extend this far right and then let's skip a little bit to i spacebar i has to be here right uh and because there's overlap between these two you know that you have to merge them because well this because there's no other way for them to be uh like by definition if they're in two different uh partitions um well then that doesn't satisfy the constraints so you have to um you have to you have no choice you have to merge them right so basically that's what i think i'm going to do so i think i'm going to just construct these 26 uh intervals and then just do while loops and merge them until we have no um until there are no overlaps and you could probably do this in like n cube or something like that where n is uh n is 26 in this case or alphabet cube uh alpha cubed um something like that's my off my head uh guess we'll actually analyze this later uh and why do i have that guess it's just from prior experience with doing these uh similar things uh and we'll go over it later and i could be wrong so we'll see but that's kind of my intuition so now let's jump right into it so for index in uh for index uh character in typing is terrible that's okay so what do we want to do right so now we want to keep track of for each um character the earliest it appears and the latest it appears so then we could create an interval because if this is just like this a in the middle it doesn't matter all you care about is the piece that shows up in the front and the piece that shows up at the end so yeah let's just call it earliest it's equal to um yeah let's just go let's just do s's you're gonna land as uh so just n maybe it's even just infinity so let's just call it infinity so that's we don't have to worry about anything weird uh and this i guess we could use um something like died or something but i always just choose a big number so that i don't worry about the language because this is in most languages uh so this is time 26 uh latest is equal to negative 1 times 26 or negative infinity actually just to keep it slightly consistent uh and then now we can just simply go um in python is a little bit awkward but we just convert this uh this is how i convert it from and this is lowercase right yeah from the character to a number from 0 to 25. um so there's this uh so index is oops not index uh character index maybe if you go to this so then earliest is equal to c uh oops and i'm missing something early as of c index is equal to the min of earliest c index uh latest is equal to c index is equal to max of latest c index um index right so and you know if you have been clever you can notice that this is uh index only goes from smaller to larger so you don't actually need the min and the max you could do a couple of other checks but that's how i'm doing it just so that i don't have to think about it uh and that for example if later we change not for this form i don't think but if we have to change the order of how we enumerate s for some reason then we don't have to worry about it uh and you know it's just another operation or two so it's not a big cause okay so then now we should have uh and you know i like to print it out just to kind of visualize it for the audience uh kind of see what the intervals are like right um and yeah and okay maybe this is actually a tailwind in the uh this is not a great visualization but so you could do something like sip with this okay well uh but it's okay thanks for bearing with me uh but yeah so you can see that uh the letter a is gonna be from zero to a and of course we can make prettier visualization but one to five is you know the b and so forth right and now we can just what i do there are a couple ways to do this you can probably figure out a better way you could do some sorting and then just um combine adjacent intervals i think that's probably good enough to be honest um yeah and that could probably uh alpha square or something like that um i don't want to do that yeah okay wait oh yeah this is the index right okay yeah let's do it that way i was going to do something like n square uh like i said earlier and cube by doing something like wow changed which is a good pattern that i like to do uh and then just like for x and like from in range from 0 to 26 uh and then for y in range of 0 to 26 and then if you know overlap x and y then we combine x and y and then something like that and then we'll just set changes to go true so this is going to be uh just alpha cube because of how it's structured and change can change at most um you can prove that it you know it will change at most 26 times or something like that so through the alpha cube but let's play around with the other idea which is the which is only slightly faster so i don't know how i feel about that um because uh because alpha is at most 26 right so the difference between alpha square and alpha cube is not a big deal or alpha and log alpha or something like that but uh but yeah but i'm going to try and do it but so you know maybe i'm observing now so bear with me um but yeah for now let's go through uh for index in range of from 0 to 26 so we go for it if earliest of c index is not infinity um then that also means that latest is also not infinity oops this is just index uh so now we just want to put the intervals together um let's do intervals dot append earliest index and make them a tuple latest index uh i think the reason why i if i was in the contest i would definitely have done the alpha cube method because there's less things for me to prove because you know that it's going to converge you know that outfit tube is fast enough you don't have to worry about performance anything but here uh the tricky thing is that now that we put all these things together uh we have to interval um list but now we have to and you know maybe the intuitive thing is to sort um but just from experience i always have to think about how to just how to um how to think about the states more right like there's more worrying there and also just that uh depending on how you do it um because in this case there's actually overlaps right so it doesn't have to be whatever it doesn't have to be like a strict overlap but it's just that i would have to prove the sort order which sometimes i think this problem is pretty straightforward because we're using greedy in already any overlapping we're merging them together kind of way um but i would say if um well yeah i think for this problem it's okay but it's just that for harder problems or some not harder problems but similar problems with little bit of difference uh you'll notice that even in little variations some assumptions that you can make about greedy doesn't apply for other interval problems and these are things that you just learned from experience and i don't really have a good example per se off my head but these are things that i've made that mistake before and that's why this is something that i would protect myself against but uh but you know this isn't fun and not in the contest so i am trying to upsell this and that's why i am going to practice this but now we go with um okay so now we have an end result let's say a results dot array um and we just go for start to end in intervals and then okay if length of results is equal to zero then we just put it in right uh then we still start append start and uh and then continue otherwise we just see if start and end compares to the last results so we can do something like i tend to be very verbose with this just because i think you can reduce this series of if statements but i tend to be very both just because i don't want to think about it that much but basically there's an overlap uh let's actually do something like previous uh start uh previous n is equal to result of negative one uh and then now if uh previous start a previous and like for example i do it this way it's very clear uh that you know why this overlap is um or previous start uh and previous n and i think you can maybe prove the other two just from this um but maybe it's worth writing them out i actually maybe it's a little bit bad about this but uh but this is just how it feels like uh and maybe i could have used the helper function but uh that's okay so now there is an overlap right so uh because there is an overlap we just uh we saw stop we popped the previous result which is you know this stuff um and then we just appen uh min of previous start stored which i mean sorted so it should be previous start to be honest uh but again i wouldn't have to um you know like if i'm writing in a way such that i don't have to prove anything because i don't have to optimize to that extent in general uh this is like an extra operation uh why worry about one operation right so if there is no overlap then we just restart start append start and then it starts a new interval and now at the very end uh notice that we want the size of these parts so now we can just um we can just convert this to the size part right so let's just convert this to uh maybe convert results i don't know uh the size results sizes as you go to there you go to um n minus start maybe i think i'm missing by one uh so this should be this plus one first start and in intervals oh no n results oops uh and then just we could actually just return this so we don't need a name i hope that's right yep uh i'll do another example there's no other example okay fine let's just create the one that we had before where we put an a here i think give or take uh i guess we had it here actually oh i did put in the right place uh so yeah okay let's empty string a lot of a's um yeah i mean i feel like this is a good uh case s must be string within oh uh yeah i guess this is it's good that i mean it's still good to test those cases even if um they tell you sometimes because sometimes it goes a little bad about it but uh okay so let's submit it let's give it a go um fingers crossed yep uh cool so what is the complexity right so is so time right so we look at each character in the input string at least once so it's going to be of n plus uh the sorting is going to be alpha log alpha and this is actually linear uh as you can tell so it's going to be o of n so time is equal it's going to be o of n plus alpha log alpha and you know and i know that in this case it's a fixed alphabet so 26 is fine and then space is you go to just all 26 because of you know the latest and earliest uh and then we just have uh this array but this array will only have at most 26 uh intervals so that is bounded by 26 so which is also alpha uh so it has most alpha variables um and also intervals obviously could only have almost 26 and result is smaller than it right so it could also only want to have only 26. uh so yeah so of alpha space uh or oops i'm not a little inconsistent there so yeah uh that's all i have for this problem i think one question is how do you know is greedy uh the answer is to be honest i'm not very good at proving them i think in my mind uh the first thing i would do is i go with intuition i maybe look at the balance to see if like dynamic programming or sorting or something like that uh can be done and then after that um you know in this case in this particular problem i noticed that like the only one k like there's no way about it right like uh which is why it's trying to go about in the beginning which is that if a appears you know like by how each construct the earliest and the latest um they have to be in the same partition right so then now you end up with all these intervals in which you have to merge them because by contradiction because if you don't merge them then uh the constraints of each letter appearing at most one part cannot be true so you have to merge them and that's how i kind of came up with the rest of it um yeah that's all i have for this problem i am subbing live so maybe it's not as fast as you like but let me know what you think about this format uh hit the like button hit the subscribe and join my discord and i will see you tomorrow bye
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
134
Jhaal Hello Hi Guys Welcome To Ko Dad Today's Question Is Gas Station In This Question Bihar Government Gas Here And Appointed To Find A Starting Point From Which We Can Start So That We Can Cover All The Guests In A Circular Wait For Example In This Case Yagya Gas Station Where Is This represents the amount of gas with which we can feel enlightened and demonstration and also represents the amount of gas British user Pin Mohan from one gas station to the next gas station Hindi sketch for representing cost less women from 200 station to the first Gas Station So What We Do We Need to Find a Starting Point That is one hundredth one hundred tank Enfield with maximum wave that Bollywood gas so normal sequence one but vacancy date back to get at least three amount of guest move from this index studied and the index the birds sing not possible to stand condition one valuables Worth 310 Web Discount Beta Tester A Starting Point Not Look At The End Exposed That You Successfully Scheduled Dates And Subjugated To Tank Initially Zero Better Reduce Gas Stations Should Not Take Web City Will Be Equal To Two Sunao From Moving From Two Three Now Required For Uniform Gas But Now Tank Only Has To Cash Gas Switch Will Not Possible For Women From This ₹2 Will Not Possible For Women From This ₹2 Will Not Possible For Women From This ₹2 Gas Station In This Case That Tum Ka Note Bhi User Starting Point Not Support Given Rates For Android Recent Activities 209 Acid Or Station Swarnabhushan Drishti Vikrampur Offer Tank And will require any one gas from you in 2425 hear so initially but for and where juice one election 2019 period between gas attend this than when they are descendants bishal das capacity feminine that no which you will and up in the tenth development has gone that Station Cross City Will Be Coming Late Now But Will Request You To Modern Education Next Gas Station Choice To You Will Be Used To 18 - 212 60 Reduce Gas Be Used To 18 - 212 60 Reduce Gas Be Used To 18 - 212 60 Reduce Gas Station Per Capacity Of This 690 Guest In Addition You Will Feel The Need To Gas Victims And Three End of station hoon ki 907 unmatched three amount gas election di ki recipe but thanks for some where reduced gas station and amount for soe and hear Tubelight yar album six and for twitter and required to move to next destination on 2301 - all equal to two when They Reduce 2301 - all equal to two when They Reduce 2301 - all equal to two when They Reduce Gas Station and Amount Will Be Equal to Two Hindi Tank So in This Case Button The Best All Its Former Third Index Gas Station at This Point and Where Quiet Brigade Station Ju In Directions Starting Point Where to Find an Index From Which Will Start Ki star tarvar sun and moon today every index handed over are listen let's look at your approach for this question first look at the roots approach road office reached very simple but will sink will consider between index of starting point and 110 cc fruits possible to Cover All The Stations From That Point Or Not Let This Teaching Research Indexes Considered As A Starting Point Someone Told You Will Ko Hospital Look Up On All The Points On Only Nak System Of 120 The Next Day Guest House Plus The Lokpal Bill Will Declare A Starting Point Nomination Quality of Standard That is Royal Stag Kiss Zero No Widely Available Bhul Impossible That is That Was Too Weather This Possible A Possible to Reach and Reach Every Gas Station When Starting from Getting It's Not True Nobility and Proves to Be Are Taste According to Setting On Electroplated Through All The Hai And Haldi Gas Stations Pimple To Is So Vacancy Date Is Video Starting From Your Position At The Starting Point And Its Moving Tel I Plus Guess What Is Why Is Taken I Plus Guest House With Quality Circular Station Hindi And Where To Find A Definity Station At Which Were Standing Currently But Will Do Will Mode This J Will Not Giving Advice Vitamin Station This Is For Circular In The Biggest Region Circular Manner So That Will Doob That Bewafa Hunde Station In Which Were Standing Currently They Will Update A person is the amount of view which they have which were inside and insert in Northern Grid station - the cost - request Grid station - the cost - request Grid station - the cost - request views which were required to statue to medium station short and will be updated at Noida entry point injured in 2008 where not able to move To next destination on which benefit mills at the starting point which were taken initially very strong dad ko notice writing but nobody will do will break from this look pendal starting point will become i plus one that is style dishes will start from one in this They will run in after blue front all loop is run if program which is studied and thin like it means that we can not want and axis bank will return - 1m return - 1m return - 1m I send you very simple but it is very time complex approach in this question. Exam Time Complexity Which We Can Reach A Square With Very High Ability To The Sun Which Will Look At Appropriate Very Efficient Space Addition To Us And Time Of Central Song Suno Let's Look At Approach Selection Width Your Optimal Approach In This Question Biber Given Date Back To Find Your Partners Not Exist In Or Twitter - One Who Will Find Hindi Approach Twitter - One Who Will Find Hindi Approach Twitter - One Who Will Find Hindi Approach Unkindness Path Exist Or Not You Will Find Out What Does Withdrawal And Will Calculate This Difficult Gas - Is Style Of Difficult Gas - Is Style Of Difficult Gas - Is Style Of Gift The Hall For All Game All The Gas Station In Hindi End Of The Loop Tips Found 1001 Twitter - 15 Minutes Near Not Exist And Twitter - 15 Minutes Near Not Exist And Twitter - 15 Minutes Near Not Exist And In It's Not Placid Near Which Will Assist You Know Why Will Be Built In Districts Near Not Exist Which Will Happen In Total Distance To Meet President Total 10 Will Samadhi समधिनिया कोस्ट करेने और एक गास गासुडसी Samadhi समधिनिया कोस्ट करेने और एक गास गासुडसी Samadhi समधिनिया कोस्ट करेने और एक गास गासुडसी विल बे विल बे विल बे ग्रेट कॉंटरी विचे विचे कैं मैक्सिम तक हुम पिक्चु है है सो इस के से ग्रेट कॉंटरी विचे विचे कैं मैक्सिम तक हुम पिक्चु है है सो इस के से ग्रेट कॉंटरी विचे विचे कैं मैक्सिम तक हुम पिक्चु है है सो इस के से दिन बोंड भी एन पूशेष दिन बोंड भी एन पूशेष दिन बोंड भी एन पूशेष Sudhir will return - plate away from this Sudhir will return - plate away from this Sudhir will return - plate away from this one condition only hear well done with loop and were produced In the definitely late just 5 minutes just like in the desert sand of here and will have per from this top 10 minutes tomorrow which will definitely exist no we can do or question 2500 definitely exists but will do it will take two days to visit The city and the starting point to point from video2018 Updated on a brick wall Five minutes of fuel to move to next gas station Subah will move to max player Tank capacity at station will reduce 2762 Now no addition they can filter tank with 174 total chemistry Option 3 And Sunao Bhi No That Full Movie To Net Gaya Station Distance Required Is 300 Tank Fuel Tank Current Twitter 20 Reduce Gas Station Nov 28 2012 Fuel Which We Can Pick Up In This Guest Teachers Us But Be Required At Least Minimum One Unit Of Fuel You Hear Text Message Station Butte 2008 Montreal Two Issues Next Scan Next Gas Station It Means That Starting Point Which Bears Under-20 Starting Point Which Bears Under-20 Starting Point Which Bears Under-20 International Case He Don't Midway Never Give Starting With 2009 Travel To Cover All The A Revolving And 10 Gas Station Elections But Will do in this case sirvi sarpanch velvet font sach ke is letter strips not any tips not possible for B.Ed b.ed bread the tips not possible for B.Ed b.ed bread the tips not possible for B.Ed b.ed bread the number 10 against and help in which lies the starting point with ki vidhi nisha starting point plus one destination starting point 20 For the Distic is not possible to begin select the starting point which one but in this case what will happen also positive that 181 position and consider Vansh starting point which would be able to move to the next station distance at 110 quality Sri 105 against Fuel &amp; Art &amp; Varsities Vitamin E &amp; Art &amp; Varsities Vitamin E &amp; Art &amp; Varsities Vitamin E A &amp; B E Want To Feel Behind Quiet Max A &amp; B E Want To Feel Behind Quiet Max A &amp; B E Want To Feel Behind Quiet Max Gas Stations Three But One Is Licensed Solution This Gas Station Vivo Travel Tours Gas Station One Has But When Invented Starting Point One Is Between Relationship Rashi Views Starting Point In the city of tanks and this gas station what to do 128 dynasty underwear and third able to go to next gas station in the morning they have seen that when will start from distant obscene maximum to maximum wearable you reach gas station on and tell that fifth b Continue and set on route Chat Start with This Gas Station What Will Happen The First to Fall Billon Singh Samoa Amount of Bird Game From Its Previous Trip Dentist Beg Into Being and Two Units from Her Previous Life in Village in Date and Id This I Bed Distance consisting of white bread is pizza bread win7 should also be a starting point will become views in deciding point Apni celebrity of 100 only so in this case will lose singh and distrip sudesh me very bad for r answer is 108 will be step will not impact anybody Answers ahead din also when starting at this point and answers-7 din also will have been Stop this sentence point and answers-7 din also will have been Stop this sentence point and answers-7 din also will have been Stop this sentence only one and vivid distance at a little distance at the starting point between Krishna and the cone is on call with will not give the right answer a Ki Edison Soni Sunao Dhundhun Yaar 10:00 K Ki Edison Soni Sunao Dhundhun Yaar 10:00 K Ki Edison Soni Sunao Dhundhun Yaar 10:00 K Messages 980 Read Share And When Required One Amount Of Fuel To The Ritual Next Step But Will Do Will Still Is A Starting Point With I Plus One Day Taste Arrive Within Us And The Starting Date Of Birth Not able to move from this index to the sentence using the initial velocity of this can search for a starting point vikram bhai plus one message points no hair styling wanted list of vikram ji plus one arrested 1000 but this indicates which have again and Mon amount of fuel swarna stadium 11nov incident using eleventh chapter movie 2012 units of fuel to next a gas station so when will move to next gas station even today mount of tank which will represent hindi tiger points which represents inc tank is not believe in the Snow Will Jain Us Feel Tagged With This Amount Of World Record To 4 Bill 93 5230 Nowhere To Move From This Gas Station To 10 Gas Station Road Located Tomorrow Morning Want To Fuel The Way You Will Be - Tomorrow Morning Want To Fuel The Way You Will Be - Tomorrow Morning Want To Fuel The Way You Will Be - 58 - 58 - 58 - 59 Duration Tanks PNB Reduce Index Will Visit Nau Been Already Seervi 3000 1000 Maximum To 99 And Addition Of This Only And Only For More Candidates A That Sudhir Putra No One Vihar 8 This Index Suno That They Reduce And Nau Are 06 2010 That Seth And Were Already Nodi Khan aka Vipin aka Maximum till which is indicated in zero but in this case and S8 in favor of past which can edit this place amount of fuel so that electricity is easy able to travels through period element again and listen vacancy date when I started from 11th Traveled All The Biggest And Again Read 734 Means Date Fix Current More Adultery Which Is Not Starting Point Date Wise Ad G Hall Index That Can Be Considered A Starting Point Will Again In This Approach But When They Consider Starting Point And 1000 This seat that time 20 able to maximize maximum auto this gas station only and not edifice solve 1000 also started son plus one that is best also pile them stitch starting point with creating part plus 120 but in this case vacancy date wood and have Ever Storm Next Station Positive Ones And Distance Between Sweet That Possible For Best Motion Extraction But In Person Distrip Ka Review Debit Card Or Pen Sahara Answer Were Beaver That I Don't Talk With Relationship To End In 1818 Vikram Three Layer Pendant Was Possible For That To Move to the question on 210 boss settings pe computing which they do not to ajneya ne lage subah-subah hai not to ajneya ne lage subah-subah hai not to ajneya ne lage subah-subah hai kal morning bhi account starting from 0 powder maximum inductive effect in which we can read this will influence of starting point with i plus one that Is Zero Loss Due To His Second Stant With Interesting Point With Me To Saunf Mithun And Sunao New Shooting Point Hai Begum 1039 Will Travel Services Which Contains Starting Point Free Leg Mission Trust And Arvind 034 Bolti Ho Approach 90 Countries In This Approach Let's Look At Record And You Will Get More Clarity of Body's Approach Solid Co Default Morning Sexual Retention Freedom Code This Chapter Such Condition Me Pain This Path Exit And Not Get As Ically Calculated Sum of Gas - Kauthig Dark Calculated Sum of Gas - Kauthig Dark Calculated Sum of Gas - Kauthig Dark Mein Mere Hindi And Officer 1.00 Id Mein Mere Hindi And Officer 1.00 Id Mein Mere Hindi And Officer 1.00 Id Distance Morning Traveled Is Much Better Than Its Total Amount Of Food Wastage Given To Us In That Case Demand Possible To Find Aapt And They Will Return - 110 Twitter - Aapt And They Will Return - 110 Twitter - Aapt And They Will Return - 110 Twitter - 111 Program Has Come Down To Me Ulta - Avatar In These Mins That Day Exist Me Ulta - Avatar In These Mins That Day Exist Me Ulta - Avatar In These Mins That Day Exist Aapt David Exist Aapt Fennel Butt You have taken to validate this tank explosion initiative Citibank start which means to the starting point updates setting stop this a gas station a and listen or a small gas station are now at every point included so value of like - cost hindi tank refill value of like - cost hindi tank refill value of like - cost hindi tank refill Tank Value at Any Point 108 Mid Wicket Boundary Trip in Which Were Not Able to Move from One State to Another Session in Water Tank Values in Districts and Tired End of This Festival Vida Plus One But in This Case Liquid Like This Beaver Distinct Was Not Possible 3000 211 It Is Not Possible To Air India Flight Mode Start With J Plus One On That In These Areas Start With J Plus One Thinks Of His Life Start With J Plus One Shot University Will Be Lower Or Only E 123 Boon Of Tire This Doctor Look Per Person's Day Start Will Be Final Value Sudhir Chaudhary Whole Code Commission District The Code Please Like The Video Was Not Submitted That City Setting Accepted Your Gas Cylinder Video Thank You
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
58
welcome back to Alo GS today's question is leak code 58 length of the last word right so this easy question has given us a string s containing words and spaces return the length of the last word in the string a word is a maximum substring consisting of non-space characters only consisting of non-space characters only consisting of non-space characters only right so we all know what a word is so what we have to do is return the length of the last word so we have the output of five here and that is because world is length of five in example two we have an output of four and that is because Moon has a length of characters of four the only issue here is that we have this trailing space right here which we need to take into account when building this algorithm out so let's discuss two different algorithms the first is going to be using built-in JavaScript methods to be using built-in JavaScript methods to be using built-in JavaScript methods right so in example two we have this Trail in space and we really need to get rid of this in order to start counting the characters within Mo and one way we can do that is by using the trim method and what this is going to do is it's just going to remove trailing spaces so we're going to remove this and then we can start counting the values so let's build on top of this we can also use split here because we currently have a string if we're able to convert this into an array containing each one of these words then it would make it much easier for us to calculate the length of it so if we split based on an empty space this will return us an array of all the words within the string so in example two the result would look like this great so now we have an array containing all the words all we have to do is now select the last word within this array and then use the length property to return the length it's that simple so in terms of time complexity for this algorithm well the two main operations that are going to be taking out time are these two now trim has to iterate through each character within the string so this is going to be o of n where n is the length of the string and split also has to iterate over each character within the string so it's going to be o of n where n is the length of the characters within the string now if we add these up we get o of 2 N now with this asymptotic runtime more specifically biger notation this is more concerned about scalability right so if we have a large data set so the largest data set here is 10 to the^ the largest data set here is 10 to the^ the largest data set here is 10 to the^ of 4 so say we have a string of length 10,000 characters right compared to a 10,000 characters right compared to a 10,000 characters right compared to a string of two characters as we scale up using biger notation this constant right here is going to become more and more negligible so we can drop this so this can be simplified to o n and space in this case is also going to be o because we're allocating extra space here for this array now an interview could ask you a follow-up question to this and the you a follow-up question to this and the you a follow-up question to this and the follow-up question could be something follow-up question could be something follow-up question could be something like try coming up with a solution without using any built-in methods so we without using any built-in methods so we without using any built-in methods so we cannot use trim or split so how can we do that well one approach is to iterate through this backwards or have a count variable which is initially set at zero and the idea of this count is just to count each character that we visit as long as it's not an empty space if we visit an empty space what we're going to do is return the count at this point because we've reached an empty space it indicates that we're at the end of the last word or the start for that matter but we've counted backwards however there is a slight problem with this solution if we take a look at example two we start off with an empty space and if that were the case with our current logic of a while loop that we're itating through backwards and Counting every character we visit and returning when we visit an empty space we're going to be returning zero here because the counter set at zero and we started off by visit an empty space so we need to make a check for this and the check is just going to be if we're at an empty space and count is equal to zero we're just going to ignore this and iterate left and then we can repeat the process and add up the count until we reach an empty space and as soon as we reach an empty space we return the value of count so let's run for an example we're at an empty space now we said if we're at an empty space and count is equal to Z well we're just going to ignore that so we're going to move over to n is a character we can increment count to one we move over to O count can be incremented to two repeat the process we move over to the next o increment to three move over to M increment to four we have now reached an empty space in which case we can return the count now complexity for this algorithm is going to be slightly more optimal we're going to have a Time complexity of o n where n is the length of the characters within the string and space in this case we aren't allocating any extra space to an array in this instance so space is going to be 01 right this's dive into leak code and start coding out these Solutions okay so let's quickly run through the first solution together so firstly we need to trim the string so string is going to be s. trim now that we've trimmed the trailing spaces we can declare a constant called words and we can split the string here and what we're going to split by is an empty space and what this is going to do is it's going to return us an array of all the words and then we can just return words. length so we're getting the last word within the array of words and we're getting the property from this now we can clean this up so let's grab the trim from here let's bring it down let's add it in here don't forget to add the dot notation and let's remove this now let's give this a run okay great so that's the first solution now let's do it without using the buil-in methods so firstly we need the buil-in methods so firstly we need the buil-in methods so firstly we need to declare a variable called I and this is going to be the index of the last character within the string then we need a count variable which is just going to count up the characters within the string and then we need to start our while loop so while I is greater than or equal to Z right so it's not the first character in the string if the current character we're on is equal to an empty string and count is greater than zero well here we can just return count so what this does is it checks if the string is empty and count is greater than zero now this is really important having this count is greater than zero because imagine if you had example two where we have a trading space if count is equal to zero then we want to avoid returning count and we just want to iterate backwards else if the current character we're on doesn't equal an empty space then we can increment count yeah because we visited a character within the word and lastly do not forget to decrement I because we are in a wild Loop right so we've covered all bases here we've covered the base where the current character is an empty string and count is greater than zero this just indicates that we've reached the end of the last word so we can return the count of that word if the current character is equal to an empty string and count is equal to zero we're not going to hit this if block we're not going to hit this else block we're just going to decrement I and then if the current character doesn't equal an empty string well then we're just going to increment count cuz we visited character within the word all that's left to do then is return count let's give this a run and there you go I hope you enjoyed the video don't forget to like comment subscribe and as always I'll catch you in the next one
Length of Last Word
length-of-last-word
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **Explanation:** The last word is "World " with length 5. **Example 2:** **Input:** s = " fly me to the moon " **Output:** 4 **Explanation:** The last word is "moon " with length 4. **Example 3:** **Input:** s = "luffy is still joyboy " **Output:** 6 **Explanation:** The last word is "joyboy " with length 6. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only English letters and spaces `' '`. * There will be at least one word in `s`.
null
String
Easy
null
1,550
Hello hello friends welcome back to my channel today we are going to discuss easy problem from the wiki contest 202 sauda problem title has three positive and isro and is awards were given as were given in this way are and what were to meanwhile have to shabad Dhun lagi re chal vighnaachi quantity number 2,000 hai boond si da rahegi aur values ​​will find number 2,000 hai boond si da rahegi aur values ​​will find number 2,000 hai boond si da rahegi aur values ​​will find true triplets to return them not reflect subscribe The Channel and subscribe the two is vansh 1000 number is the day ki jo achha in second number effective vitamin e contact numbers to Retrieve 130 209 and give one number 100 feet take a mechanic and number battalion this point is secretary and tigris prized day give him strength 1023 this is also a and fame without notice for sleep without proof 100 this a very simple program and doing a year and calculating and Share and storing in the settings for alleged in the traffic from 021 - 2013vinod agri index loop slow 021 - 2013vinod agri index loop slow 021 - 2013vinod agri index loop slow share what doing a initially the story of the con is on who is the location of side andha plus one and assistants inducers peroxide plus 2 and mother name perform Simple Tips For All The Number Say Chief CR Not Divisible By Two It Means The Number Ward Number 16's Returning To Were Returning Subscribe To That Show Is The Solution More A Suite Around And Dutt In This Case Is Swadeshi Products Thanks For Watching And Definition
Three Consecutive Odds
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** true **Explanation:** \[5,7,23\] are three consecutive odds. **Constraints:** * `1 <= arr.length <= 1000` * `1 <= arr[i] <= 1000`
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
Array,Binary Search,Heap (Priority Queue),Matrix
Hard
null
1,979
hey everybody this is larry this is me going with q1 of the weekly contest 255. find greatest common divisor of a way uh hit the like button hit a subscriber and join me on discord hopefully you shouldn't have trouble with this is just doing what they tell you and i would also say that most languages have a library function for gcd um if you didn't know that sorry if it now you do um and from that then it should become straightforward and that you literally just find the smallest number and the largest number and then you return the gcd of them that's basically what i did uh how long did i do 54 seconds i probably could have done it a little bit quicker that's actually slower than i thought um but yeah so this is gonna be linear time because finding the min and the max is linear this is o of one ish depending you know all one for fixed length integers so yeah uh that's all i have for this one i don't know what to say if you don't know if you don't have a library function you can actually implement this and if you have to you could just google it um but i can't imagine gcd is an interview anyway but unless you're doing like quant or something in finance but that's all i have for this one let me know what you think i will see you later oh and you can watch me solve it live during the contest next that's weird okay hey uh yeah thanks for watching hit the like button here to subscribe and join me in discord hope y'all have a good rest of the week stay good stay healthy and to good mental health i'll see you later bye
Find Greatest Common Divisor of Array
maximum-number-of-people-that-can-be-caught-in-tag
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** The smallest number in nums is 2. The largest number in nums is 10. The greatest common divisor of 2 and 10 is 2. **Example 2:** **Input:** nums = \[7,5,6,8,3\] **Output:** 1 **Explanation:** The smallest number in nums is 3. The largest number in nums is 8. The greatest common divisor of 3 and 8 is 1. **Example 3:** **Input:** nums = \[3,3\] **Output:** 3 **Explanation:** The smallest number in nums is 3. The largest number in nums is 3. The greatest common divisor of 3 and 3 is 3. **Constraints:** * `2 <= nums.length <= 1000` * `1 <= nums[i] <= 1000`
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not "it" cannot be caught, and the person who is not "it" is on the left of the person who is "it", find the next leftmost person who is not "it". If the person who is not "it" cannot be caught, and the person who is "it" is on the left of the person who is not "it", find the next leftmost person who is "it".
Array,Greedy
Medium
2191
152
hello welcome to my channel today we have leeco 152 maximum product sub array so given an integer array nums find the continuous sub array within an array then containing at least one number which is the largest uh product so the example one is having input array two three negative two four then you would have two and three that's a sub array that at the maximum product is six here's zero individual one so you can have individual one and the idea of this question is you go through the whole entire array and you see you have the maximum or minimum right here how do we calculate product so we have two here and we multiplied by three so we have six and multiply so 6 right now is currently maximum and if 6 multiplied by negative 2 we will negate 12 so that it's not good so we don't care about that one and negative 12 right now time uh negative four so it wouldn't work so it's like a negative big number but um we also have the minimum number when it turned to oh let's take that look take a look at this already right here now we have six sort right here and we also have 12 negative 12. so the maximum at this place is 6 and the minimum at this place is 12. so in case we can keep looping this one and we see even with times four it will be negative 48. the idea is if this is we have to keep track of the next the minimum number because in case we see a negative right here so we will have to see because this time this will be a positive 48 so we have to time this one with the maximum number and minimum number to see which one is bigger so uh if the bigger one will get updated to the maximum output so that's the idea of this question um see comment this out and let's take a look at this code i mean first we have integer max equal to nums we start min and max in the same number which is the first number of the array so we have in output equal to max current max right now so we have a for loop started with i equal to one because we're skipping we already know the maximum and minimum for the first place and we started with the second number to the end of the array so i is less than nums.lane than nums.lane than nums.lane and is now we look through the entire uh array and what we can do is capture the previous max you to max right now so we have previous max right now and now we have to update the max equal to math.max equal to math.max equal to math.max i will have current number we can have current numbers equal to nums.i so it's current number um could it could be an individual number so we have to check if the current number is the maximum could it could be either bigger than maximum already by itself so we don't need to time anything the max will be either current or the maximum of current number time um previous max or current number time min this is what we do in here for this row we have this one we have to check current number time previous max and current number time pres previous minimum to get to the maximum so the maximum get updated now we update the minimums equal to current.min we have current.min we have current.min we have current and also it's really similar to the upper one so we have current time pre-max so we have current time pre-max so we have current time pre-max current time min and you have the minimum also updated at the end we have the current location max right now we have to check output always keep track on output that have the maximum product and now you have the output that contain the maximum products subarray uh let's see was okay this no synthetic and cool and that's it for this question i believe yeah uh it's kind of straightforward to the logic and we just need to type it out if you have any question please comment below and i will see you in the next video thank you bye
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
128
welcome to my youtube channel today we will see another late code problem longest consecutive sequence and here we have an unsorted array of integers called nums and here we will need to find out the longest uh the c consecutive sequences let's say for this array what will be the longest consecutive sequence that will be one two three and four right so this will be the sequence and another sequence we have uh let's say 400 we do not have any sequence we can say this is a separate sequence and uh 200 also we have right we do not have any other sequence so this three sequence we have so longest will be uh one two three four this we need to return right though what will be the approach to find this solution uh because here if we find the solution we need to find it out our best solution so first approach a simple approach we can find the sorting right so if we sort the array what will be the sorted area here for this uh if we do the salt what we will get one two three four and uh 100 and 200 right so this will be a sorted array so we can see the sequential the consecutive sequence will be uh will be um will be uh you know uh will be the combination right let's say one two three will be uh the neighbor for one neighbor is two never is three four like it will be more easier to find the sequence we can tell this is the first uh consecutive sequence and length is 4 so we can return this from the sorted added so but the problem with this approach uh for the complexity of this approach is n of log n right for sorting so but here in this problem we need to find out a linear algorithms like which uh complexity will be big o of n right so we need to find it out can we do a better approach do we have any better approach to achieve this big off in right surely we have a better approach i will tell you we'll see how we can improve these algorithms and how we can achieve big o of n let's say we have this array so first we need to find it out we need to visualize how many sequence we have first we have a sequence so let's say one we have two we have three and we have four and second sequence we have 100 right and third sequence we have 200 so we need to find it out the starting point of the sequence right so what will be the starting point for the first sequence starting point is one right so here the starting point of the first sequence is one and second sequence uh we have the starting point as a hundred and third sequence we have the starting point 200 right so in this case we need to find it out whether we have a left neighbor of this one if the left neighbor uh exists first we can say that this is not a starting point let's say for 2 we have the left neighbor like 1 then 2 can't be a starting point of a sequence right so like that way we need to find somehow uh we need to calculate the starting point and we need to check whether the element is ah is a starting point or not but how do we calculate that so from this input array we need to create a set and that set will have the all numbers okay and we know that complexity of adding or fetching the value of a set is big o of 1 so in that case what we need to do we need to just check that weather is a element let's say for we if we uh iterate over this array we need to find it out whether 100 is the starting point or not we need to find it out whether 100 minus 1 that means 99 is exist in that num so we do not have 99 right so we can say this is a starting point hundred is a starting point but and then we need to find it out the next neighbor the next element what will be the next element 400 would the next element will be 100 plus 1 that is 101 whether we have the nums uh set we do not have 100 plus 1 right so we will end this sequence in 100 so we got one sequence first sequence we got 100 and then we have four so for four we will check whether the left neighbor what will be the left neighbor for the four left neighbor what will be the left neighbor for four will be 3 right so 3 is exist in the num so for 4 we will skip this because 4 is not a starting uh point right then we will go to that 200 for 200 will find that 1 199 is present in the num that is not present so we'll start the sequence we'll get the second sequence of 200 and again we'll find that whether the right neighbor for the next element of the sequence 201 it is not present in that num set right then uh we'll end this sequence this is the second sequence now we got this one now we'll got this one right for 1 we will see that whether we have 0 right 1 minus 1 is a 0 so 0 in that num whether we have 0 in the nums we do not have so we'll start this one we'll start this sequence one then we will try to find one plus one that is two right one plus one is the two so we will see whether this two is present in the num set yes it exists then we'll start adding into this sequence 2 then same 3 and 4 after 4 we'll uh see whether 5 exists 5 is not exist so we'll end it so then we can calculate the length of for this uh you know uh third sequence is four then we will return this four right so now we will see how we can achieve this in coding right so let's say we have the nums array and let me create one more variable that is longest that will be the longest element that is the uh that we need to return it that longest element equals to 0 initial value will be 0 and let me create a num set from the num equals to new set and this will be created from nums uh here that set will be caps right and what we'll do next we'll just simply take a for loop and we'll iterate over this array i less than nums dot length i plus and here what we are going to do we are going to uh create another variable let's say conjecture we need to find it out whether we have a consecutive number and this number we need to find that is the consecutive next number right so let's say consecutive equals to 0 right and now we will put a if condition and we will say see this num set whatever we have uh num set it's a set we need to use the hash and we will see whether these nums i the current number minus 1 whether we have it or not we'll simply use a not operator if it not present in that set what we'll do if not present means it is a starting uh point of a sequence right it is not present means it's a starting point so we'll try to find the next neighbor with the help of while low let's say we have the num set and we have only to use that has operator and we will uh check we need to check the next enable right so we'll uh see this consecutive is the next consecutive number so we'll keep on adding it and keep on uh you know keep on searching for the next neighbor and for never whatever we have we will just act one each and every time and then what we need to do we need to just fetch that we need to assign that longest whatever we have equals to math dot max and that will be you know this what will be the longest and consecutive rate so let's run this it's accepted let me submit this you can see it's submitted successfully right so thank you very much please stay tuned support me thank you
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. **Example 2:** **Input:** nums = \[0,3,7,2,5,8,4,6,0,1\] **Output:** 9 **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Union Find
Medium
298,2278
3
hey how's it going uh this is casa moani and in this video we will go through a very popular uh coding interview question um called longest substring without repeating characters this is a fairly simple coding question but is often sort of non-trivial to come up often sort of non-trivial to come up often sort of non-trivial to come up with the solution without any prior experience or knowledge and if you're new to this channel i make videos in machine learning most of the time is going through papers and discussing some of that and going through my research and machine learning and i'm and i also make videos on hacker balance projects that i've won and yeah and i'll be doing more videos on coding interview questions specifically hopefully one a week depending upon the schedule that i have so yeah in this video we'll go through this question where you're given a string and the goal is to find the length of the longest substring without any repeating characters so when we define substring it's a set of contiguous characters in the array so you in the case of over here you have your string abc bb this would be considered as a substring this will be considered a substring similarly this would be a substring but the letters a b and a as a set would be a subsequence and not a sub string because they're not contiguous in nature so the longest substring without any repeating characters or abc with length three and we're just supposed to return the length of that substring and um in the case of this it's just one which is b uh but in this case it's actually w k e because p w comes twice uh w k e uh w k w comes twice um k e w well that has that's obviously they're all three unique characters and but the first one that we observe is wke and so something like over here um it's the same example as before but in this case it's w-k-e-p which would be the longest it's w-k-e-p which would be the longest it's w-k-e-p which would be the longest or k-e-p-w and that would be four so we k-e-p-w and that would be four so we k-e-p-w and that would be four so we return four in that case um so how do you actually solve this problem um it may seem a little bit complicated but the actual algorithm is quite trivial uh but it's non-trivial to come up with uh but it's non-trivial to come up with uh but it's non-trivial to come up with the solution a priori and the way that you do it is through this algorithm known as the sliding window algorithm which is a two-pointer technique which is a two-pointer technique which is a two-pointer technique essentially what you do is let's say you have a string abc bb i'm just copying the first example and what you would have is you would have a set of two pointers an ing pointer and what you do is you solve this uh through sub problems essentially so instead of finding the maximum uh the longest set of characters uh in the entire array uh meaning with length um you know length of this array you'd find the maximum number of characters that satisfy the constraint with uh you know length at this index and then at this index so you'd solve it almost like a you know a regular dynamic programming problem but uh that's the approach right you solve it in batches you solve it through sub problems uh but it's not a i wouldn't consider this a dp problem um so the way that you do it is as mentioned you would have two pointers the first pointer or the left pointer and then the second pointer or the right pointer and what you do is you would have an i and j pointer that would determine the interval of these of the array of the sub array and you would basically the constraint is that all the characters between i and j should be unique and if they're unique you keep iterating j to the right if they're not unique then you can no longer iterate j to the right again because now you've found a repetition in your set and if that's true then you iterate the left pointer to the right because now you know for a fact that the maximum window can no longer be expanded to the right because you have already observed a duplicate in your current subset so now you go to the left and you go through the same constrained is are all the characters in that subset unique if so then you iterate the right pointer to plus one and then you continue the pattern otherwise you keep doing it to the left you keep iterating the left pointer and that's basically the algorithm it's actually that's pretty simple um once you know how to how the algorithm works um and there are multiple approaches that you can take you can actually implement an explicit two-pointer mechanism two-pointer mechanism two-pointer mechanism or you could be clever and do it in just using a regular for loop and have a defined starting pointer but have a continuous uh second pointer or you could do it using the more traditional um the second two pointer rule um and so what i what so here's how um i do it um so since i said so the problem the first problem that comes about is how do you actually determine if all the characters in the set are unique right and obviously the first approach you can do is have like a hash map or a dictionary of some sorts but the thing is that in our given in the constraints we know that s consists of english letters digits symbols or spaces and that's basically the entire ascii table right of the or the extended ascii table of 256 characters so we know that the total the table would have at max a value of 200 or 256 filled characters you can no longer you cannot get more than that and that's what i would do we would create a set of 256 characters with the initial value declared as negative one why negative one and not zero uh because the reason for that is because the initial character uh before you start the loop before you start running through the algorithm has zero occurrences so what you could do is instead of having negative one you could have zero but then you would do table zero plus where zero is the index of the first character so it would be s zero right that's the idea um or you could just do negative one and save that um debugging headache and when you do have this uh so this is uh technically an accel an auxiliary space of 256 characters but it's constant so we can ignore this with just a tiny additional buffer of characters and call this as constant space um and our algorithm actually the final algorithm will that i'll show you has a time complexity of o of n so a linear time and a space complexity of one right so it's called constant time and that's the only auxiliary data that we need memory that we need and so what we have is we have a start pointer as mentioned earlier and we have um we have a final or the right pointer uh which let's call it j so let's actually run through um the loop for j in range table so now we're just indexing through all elements and j would be the index value the reason why we're starting with negative one is because every element is negative one and we're trying to have that as a base constraint which i'll explain or what you can observe uh from the um the code that i'll input so now what we have to do is we have to store the character so the character at store the um at s i at table and the way we can store it is by taking its ascii value um and let's call this now we can store this or we now have access to this value and we know for a fact that this value exists in our table and by default it has a value of negative one and what we can do is we would check to see if that value is greater than the initial value which is negative 1 and if so that means that we know that there was at least one instance of repetition so now we know for a fact that this character has been inserted before now we don't know if uh that character that has been inserted before or the new character that has been inserted is part of the same subset or a different subset and if it's part of a different subset then the normal rules that i that we talked about the second pointer iterating would apply if not then would have to iterate the first pointer so what i mean by so now here's the interesting part if start um so if table ask would give me basically the count um sorry would give me the index value and the index value would be a number from zero through uh length s and that's why i wanted my table to start from negative 1 instead of 0 because my first value would obviously be 0. so if it is greater than uh negative one that means that it has already been present in the subarray before so all i have to do is reset the value start to reflect the value of the current table that's present and that's it and uh and after this um all so now we have reseted the value of start um but we also have to reset the value of the table that's present or the in the hash or in the array uh the lookup table would have to reset its value to reflect the value of the current index and that's j not i and once we do reset that value it's almost like a max subproblem a solution being automatically constrained or solved for you so what you have in this case is when you are at a your start character is negative one so right before your a start character is negative one um let me actually do so your start character is at negative one um and your index i is for j the second pointer is at zero uh but when you do hit a uh this becomes zero and this is still zero but now when you're b um i becomes one or j becomes one and a b is still zero but now after you hit b becomes one and you can see this repetition happening again and again two so when i say start yeah so yeah and so this would be two and then right over here when we hit a again um so in this case what happens is we've already seen the value of a so now instead of going to the right again we would increment the value of a to right so we now do i plus in the earlier demonstration so that it could go to b and in that case instead of it being zero through c it would now be one through c o one through two right so now we've shrinked or shrunk uh the window and that's what is so instead of doing that two pointer method it gets taken care of automatically by resetting the value at every single uh point in the iteration and all we do now is just set the um so we can have a max length constant um that's a zero is what we're trying to return and we can just do max length equals max right and uh that should be it um let's run the solution sweet awesome yeah so that's pretty much it's a very simple problem once you understand the two-pointer or the sliding window the two-pointer or the sliding window the two-pointer or the sliding window logic and it's only a few lines of code if you actually understand it the two pointer method is also pretty similar to this except you sort of have to manually control both pointers um depending upon their constraints but i prefer this to be much easier and obviously intuitive since it's an obvious occurring uh continuous problem and that's pretty much it for this video um if you like this video um make sure out uh yeah if you like this video do uh like and subscribe you know the traditional stuff that youtubers say but other than that um i'll probably make another video on leak code uh soon and all right peace out
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
1,752
so hello guys welcome back again today we will do the problem check if it is either a sorted array or not at first I will make our book okay fine so our today's problem is check if the array is sorted or rotated you know the sorted array what is and you need to know what is a rotated array it is a basic question is in gfg and it is a question on lead code easy level question on lead code and the question number is one seven five two the link of the question in the description please check out the description for the question okay that's fine it is in the lead code easy and a gfg basic now what you should need to do now you should do at first I take the area over here it is our array what is given one two three four five six it is our array now what we need to do that is our sorted array like that two one two three four five C it is ordered you all know what is the rotated array if I will take a break over here and I will rotate this like this at first at the first part I will take this like 3 4 5 6 and then I will write one and two you will get this is called rotated array what has a break from this it is also sorry it is a rotated array and it is a sorted array that's fine now you know what is rotated and what is sorted array now I will need to check the given address sorted or rotated or not if the array is sorted or rotated then return true and if this is not sorted or rotated then return false okay now you can understand the problem statement then what is our first Approach at first I take the air over here the edits I take the rotated array 3 4 5 6 1 2 this is the array at first I will tell you uh at first I take the sorted area over here one two three four five six now what we need to do we will take a pointer over here I pointer over here OK that's fine now what we will need to check we need to check if how I understand this is sorted the second element is greater than the first element sorry previous element the next element is greater than the previous element so that's sorted array okay that's fine what is the condition for here I at first I give the indexing is 0 1 2 3 4 5 what is the condition for it the condition is if the previous means the height the I the array of the in the ith position the area of I is lesser than this next element like a of I plus one if this is happen then it is called as sorted array if it not happen then it will call as not sorted array okay that's fine now how we will find that it is a sorted array I do not need to write this I need to write this if array of I is greater than array of I plus 1 if I write that this is the condition for not sorted this is the condition for sorted array this is the condition for not sorted array if the condition for not sorted at a is a if the known condition for not sorted array is satisfied then I will return false over here okay and that is fine and it is not happen we will return ah we will return true at last OK that is fine now what we will need to do now we will need to do sorry now what we will need to do we need to find it is rotated or not sorted is understood it is at our condition for the sorted array and it is the pseudocode for the sorted array what is the pseudocode or the code for on the rotated array now at first I will check the rotated array from this condition OK in this position it is a rotated array you all know I will take the pointer here I will check the condition if array of I is greater than Arrow 5 plus 1 it is not satisfied then we will not return to false no need to return false I will check further it is not satisfied I will check further it will again not satisfied now I will check further now it will satisfy a of I mean 6 is greater than f i plus 1 this 6 is greater than 1 this is satisfied so we need to return false over here but it is a rotated array what we will need to do you see at first ah for the related array at first I will take a not sorted array not sorted not rotated it is like this like 0 four one three eight this is a not sorted array okay not sorted or not rotated array now I will check this condition for this I will check if 0 is greater than 4 no this is not true I will check further this is true and now this is 4 is greater than 1 this is true then I will return false over here ah sorry ah then what is the condition our condition for the rotated array you see that the condition is happen one time if the condition happened one time then if I not return false here when I will get 1 and 6 over here and when we will satisfied our condition one time if we will not return false and we will move further then we will found that it is a rotated array so what we will need to do if the condition is satisfied zeroth time this is a sorted array if the condition happens one time if the condition sorry if the condition happened one times then it is called not sorted array okay that's fine if the condition have break we will take our break here okay this is six this is one we'll take our break here if we will take our break here one time then it is not sorted away here if you here I will move further it is one it is two it is one it is three okay the cap conditions are not satisfied I will move next then the condition is sorry OK if the I have a break over here then what we will need to do then we will need to do that is ah sorry I have if I have one break or zeroth break here then the condition if zeroth back this is sorted array if one break this is no sorry not sorry it is rotated array it is called rotated array if the condition happens R if the condition happens one time this is called rotated array if the condition of zero happens zero time then it is a cover sorted array then I will take a count variable when the condition happens I will increase the count if at first I initialize the count as 0 if the count is 0 if the quantity type is zero position the count is zero then it is sorted I will return true for this if the count is 1 this is related I will return true for this if the count is 2 or greater than one sorry greater than one I will found our condition over here if the count is greater than 1 we will return false if not happen is we will return true okay now let's see the code for it now see the code for it at first we will check this at first I will take a count equal to 0 over here I will take count 0 for over here and I will do F run a for loop from I to ah into I equal to 0 I less than n i plus ok these are for Loop then I will check if area of I is greater than array of I Plus 1. if this condition is happens count plus ok it is our code OK next I will need to check if the value of count is greater than I will found this over here if the count is greater than 1 return false else return true okay this is the code but there is a mistake on the code what is the mistake is basically where is our P my p n it is there is my pain I found this then what is our mistake in the code the mistake in here when our pointer is here how I will check I plus 1 this is not a 0 1 2 3 4 5 this is not have any fifth index then how I will check this I will need to check this from with this index I will compare the line final index with this index how I will get the final index I will find the I will get the first index from the final index how I will find this if I will give here modulus of n if I will give here modulus of N I write it beside I plus 1 modulus of n it is our condition ok how I plus 1 module is s of n give us the first index now at first now I take an array over here suppose one two three four five okay zero one two three four OK this is our index and what is do what is need to do it is our index and I will check if when I will in the final index the I is equal to 4 and the size of array n is equal to 5 the I plus 1 equal to 5 and the five modulus of 5 is equal to 0. and I will get our first index for the last index for this I will take I plus 1 modulus of N and you can definitely say that it is for the last index but what is the for the mid index mid indices always return the next index for this condition how it will happen I will see I will give you ah the example like when I is equal to 1 n is equal to five always five then I plus 1 equal to two modulus of five equal to always two so it is always give us the next index so it is our code it is our whole code sorry it is our whole code it is our code for it and what is the time complexity for it the time complexity is Big of N and the space complexity is bigger of 148 okay so that is for today sorry that is for today it is the time complexity is we go of N and the space complexity is Big of one so that is for today if you enjoyed the video please don't forget to access the playlist for it so we will meet in the next video till then take care bye
Check if Array Is Sorted and Rotated
arithmetic-subarrays
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** true **Explanation:** \[1,2,3,4,5\] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\]. **Example 2:** **Input:** nums = \[2,1,3,4\] **Output:** false **Explanation:** There is no sorted array once rotated that can make nums. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Explanation:** \[1,2,3\] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic.
Array,Sorting
Medium
413,1626
1,834
hey everybody this is Larry this is day 29 of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this Farm uh yeah a few more days of the Year hope everyone had a good year uh Market's been tough uh for me anyway so and of course the tech markets also been a little tough also for me I guess so yeah I don't know but let's finish the year strong let's finish these few problems and let's go uh today's poem is 1834 single divided CPU how many I'll just say that today I think there's a weekly one so yeah so uh make sure you know we'll uh it was due to premium one afterwards so definitely uh you don't have premium just come and hang out and let's do it together I suppose okay so let's do today's uh yeah 1834 single divided CPU so you're given end test label from zero to n minus one with two D integral ways task okay um okay you have a single so you could only do one at a time you cannot choose the one with the shortest processing time if multiple have them it's more index so you have to basically do it one at a time um what's it oh so basically you have to do it one at a time uh getting men I mean I think that's the way that's one thing that I'm not a fan of with respect to the deemed weeks or whatever it is um because from yesterday I guess we did Heap and it's hard for me to like pretend I didn't know yesterday we did Heap but this is going to be but you know there are things to recognize anyway which is that um you know the shortest path then we do it um in this way um let me do a little bit of uh yeah we turn the order in which the CPU process the tasks okay at time one okay I mean we just have to sort this right so basically okay so first we sort um the tasks but on Queue time and I mean the processing time as well we actually don't process off this anyway so yeah and here maybe we can have a cue because you know maybe I'll write it this way instead all right so while we have a task and then maybe we have something like current time is zero um so we start at zero and then we have a heap that let us do the task right so while length of T is greater than zero I may change my mind on how to implement this later as uh this is kind of slightly confusing maybe perhaps on how they're phrasing um but yeah but basically while this is greater than zero um we basically yeah and then we do it yeah maybe I could write this in a little different way I don't know so maybe about true for now maybe we'll add a brick statement I mean we have to otherwise it'll be an infinite Loop but while this is grade 0 and um the first item in queue time is greater than or equal to current the current time then um yeah maybe I'll write it differently though but basically we want to push to the Heap in this case right um because basically now we're saying okay let's put it into the things that we can run you know uh yeah so we put it to the Heap we put and we want to now processed by pretty much okay so do I have to do the index okay so we have to do a little bit um yeah we want to sort by tasks that's what this is so weird to do but we want to enumerate and then we sort it but now the key is just the middle element right maybe something like this actually right real quick just to make sure my syntax is uh okay I think this is okay but you know it's easy to kind of have a typo okay so then now we want to push to the Heap and now element one is the current basically now we have the index as well because we need it for the answer and also maybe we have the answer here just to keep in track and then now we want to what do we want to sort by we want to start by the processing time so we want to do something this is so yucky but um foreign I wonder if I could do this with the walrus I don't know that I can do this with the walrus but let's try it I'm trying to avoid this thing so let me know uh oh I know because I'm doing like weird comparisons okay fine but uh let's you know um but oh yeah pop left right so basically what do we pop the index we pop the time which we don't need anymore because now we know that it is now that is ready and then the processing length so I'm just going to call it um P time maybe um and then here we want to sort by the PT and then we'll just keep the index so that we can return it to the answer and here instead of having this thing I mean we have this as well but we could set current is the code to maybe something like if length of Heap is zero then we set the current because otherwise it would just keep on looping um but we have something on the Heap then we do not necessarily basically we're just forwarding the current time to the first element uh and what is it zero um then is equal to two zero one so then that this will at least pop one item at least okay also we're done when length of T is equated greater than zero I guess I could put this here as well um maybe and all length of Heap is greater than zero maybe we can change that later and then okay so then now after putting all the key things on the Heap we go okay what can we actually run right so yeah so then now we pop off h um yeah and then we get the PT and index is equal to this and then answer we put index and current time we add it to PT and that's pretty much it I think and I think I explained this very awkwardly oh this is um because the way that we did it this is actually um toppo that contains those things um it's PT not edible hmm did this pop really standard dollars two so and current is zero didn't not get over what does that mean is it because I'm shadowing let me just put this real quick just in case okay now it's still there so we're popping these two things and it should be okay I don't get it they don't get it uh yeah you're watching an expert coding silly things uh okay um I mean this is what we expect probably so why what oh I see because this is now wrong because this got converted to a tuple ah okay wow foreign this is so awkward because the reason why all this is algorithm will fix this anyway but the reason why this is awkward is because I was lazy here um and basically in numerate returns an index and then the original thing but the original thing is a list so then now this is just terrible code but well hopefully by now you know how this works but okay so I am putting out the wrong answer for this one why is that dun oh wait this is um so maybe it did something weird yep okay I meant to do that but then I forget but basically we want to fast forward but of course if the beginning of the queue is um you know in the past and we don't need to fast forward but this is just for Fast Forward reasons and you actually added if statement here I suppose maybe that's what I meant and that's what I forgot to do it yeah let's give it a submit hopefully this is good yep uh cool I'm gonna do it last time I guess I did it about the same way anyway maybe I did a snap but yeah so basically this sorting is going to be n log n um no he pop is and push um is you know for each item in the original input we're only going to push and pop once from the Heap so this entire thing is going to be n log n and of course of n for the space for the Heap and the answer so you can really go under that um but yeah basically the idea is just simulation in a smart way you could you um the way that I would actually think about it um you know I think I skipped ahead a little bit in some of my explanations and I apologize for that um wow it's been 10 minutes I'm gonna spend 10 minutes on this um and of course the first thing you should take a look to be honest and I did not do that so this is my mistake as well uh is to look at constraints to make sure that you're doing what is necessary right and it's ten to the fifth so you cannot do N squared but the way that I would think about it um originally if you have time to explore this problem is to write it to n square right what would the code look like in an n-square way and then like in an n-square way and then like in an n-square way and then you'll find that some part of this will you know instead of Heap uh instead of HE push and he uh just pop or sorting um maybe you're doing something where you're just getting Min every time um and then getting Min of a few things and uh and that's what the pop does instead of doing it in login time you do it in of end time and that makes it um and square right um so then once you get there you're like you know you ask yourself how you can optimize and that's basically how I would think about it um like what parts can you optimize what data structures can you use of course this will come with experience as well so you know there's no shame in it that's fun of learning it'll take a while maybe but yeah um that's all I have for this one let me know what you think um stay good stay healthy to go see you later and take care bye
Single-Threaded CPU
minimum-number-of-people-to-teach
You are given `n`​​​​​​ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `i​​​​​​th`​​​​ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing. You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way: * If the CPU is idle and there are no available tasks to process, the CPU remains idle. * If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. * Once a task is started, the CPU will **process the entire task** without stopping. * The CPU can finish a task then start a new one instantly. Return _the order in which the CPU will process the tasks._ **Example 1:** **Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\] **Output:** \[0,2,3,1\] **Explanation:** The events go as follows: - At time = 1, task 0 is available to process. Available tasks = {0}. - Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}. - At time = 2, task 1 is available to process. Available tasks = {1}. - At time = 3, task 2 is available to process. Available tasks = {1, 2}. - Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}. - At time = 4, task 3 is available to process. Available tasks = {1, 3}. - At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}. - At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}. - At time = 10, the CPU finishes task 1 and becomes idle. **Example 2:** **Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\] **Output:** \[4,3,2,0,1\] **Explanation****:** The events go as follows: - At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}. - Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}. - At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}. - At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}. - At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}. - At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}. - At time = 40, the CPU finishes task 1 and becomes idle. **Constraints:** * `tasks.length == n` * `1 <= n <= 105` * `1 <= enqueueTimei, processingTimei <= 109`
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
Array,Greedy
Medium
null
205
hey everybody this is larry this is day 12 of the july deco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem isomorphic string given s and t demanding the isomorphic if the characters and s can replace the t okay no two characters may map to the same character but a character may map to itself okay so this seems like it is just a lookup of the frequency table um or map so then we can do something like this let me see if this will work type values maybe something like this maybe someone like this right uh it's not gonna be the most it is not gonna be the most uh efficient thing but i think this should work and i'll explain in a second i know i'm jumping ahead a little tired today too uh happy sunday everybody or happy monday i guess um but let me just write up these things but the idea behind this one is uh and one liner aside uh did i miss anything um no maybe it's okay let's give it a quick submit oh no why is this oh it has to be in the same order okay so i was wrong on this one i probably have done this before too okay so okay i don't i thought the frequency table thing would be enough because for some reason i doubt that um the order doesn't matter so because the order that matters then this doesn't work so what we want to do then is just to be honest just do what it tells you um we basically have a mapping and a reverse mapping and then just confirm that is accurate uh so let's do that let's have mapping as you go to a um a lookup table and then a reverse mapping or mapping if you will to kind of because this is from s to t and this is from t to s and then now we just go for each character at a time and i guess we have to check that the length is the same now okay so that's good uh it could be any ascii character which is a little bit awkward as well to be honest but yeah so in this case then you just have four uh x y and z of s t and that this z basically uh looks at each character and s and t at a time and then maps it to x and y so then now we go okay if um if x is in mapping um if x isn't mapping and you know we can just be exhaustive and slow it doesn't really matter if x is in mapping then mapping of x has to be equal to y um and not mapping of x or maybe and mapping is not equal to y then we return false because that means that um x is already uh mapped to another character um otherwise we're forced to put x is equal to y and then we do the same thing for the reverse mapping and i think that should be sufficient um yeah and then the way enemy just returned true so let's try it again this time with the ordering thing i think i was thinking of a similar problem where ordering doesn't matter so um yeah okay cool yeah accept it so yeah so what is this um so i was a little bit sloppy i thought that the ordering doesn't matter i didn't really read it i probably watched it too much because i saw one line of potential and you can actually do this pretty easily as well um but yeah but basically what i'm doing here is that like i said i'm trying to force because there's a one-to-one because there's a one-to-one because there's a one-to-one mapping from s to t and t back to s which is one to one um everything is forced right that means that if the two things in one put in one direction then you know you can um yeah then you can return it and you can actually also do it another way where you just um do the count and so forth uh like a keep track of the number of unique things you've seen but either way this should be good enough this is uh for example linear time and space because um though you know i know that's not that many ascii so technically i guess this is actually more close you know this is actually closer to all alpha where alpha is the number of characters for space um but where alpha in the worst case could be linear right because in theory your alphabet can have um i guess in theory you could have like 50 000 um was it 5 000 yeah uh 50 000 different characters and you know and this would be that wrong so yeah so linear time linear space uh let me know what you think um this is pretty much trying to implement it i was trying to upsolve it very quickly but kind of whoops didn't read it correctly so yeah uh okay that's all i have for this one let me know what you think uh join me on discord hit the like button to subscribe one have a great week happy monday i will see you later and to good mental health bye
Isomorphic Strings
isomorphic-strings
Given two strings `s` and `t`, _determine if they are isomorphic_. Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example 1:** **Input:** s = "egg", t = "add" **Output:** true **Example 2:** **Input:** s = "foo", t = "bar" **Output:** false **Example 3:** **Input:** s = "paper", t = "title" **Output:** true **Constraints:** * `1 <= s.length <= 5 * 104` * `t.length == s.length` * `s` and `t` consist of any valid ascii character.
null
Hash Table,String
Easy
290
82
hey everyone welcome back and let's write some more neat code today so today let's solve the problem remove duplicates from sorted list so we did solve a very similar problem to this one where instead of removing the duplicates from a sorted list we were doing it with a sorted array and in this case when they say list they actually mean a linked list and this does slightly change the dynamics of this problem our implementation will be different because in this case we do have a linked list so of course removing values from a linked list is usually done with pointers right so if we wanted to remove this node we would just have to take this link here you know cross it out and instead have it point over here and that effectively removes this node from the list even though it technically does exist here but practically speaking i don't think in this problem they actually want us to delete the nodes but maybe that could be a requirement in a real interview it would probably depend on what language you're using we're not going to really pay attention to that but yeah so each value in this list there may or may not be duplicates for each value in this case 2 does not have any duplicates only one node with the value two shows up but there are two nodes with the value one so of course one of them has to be removed we could remove this one or this one i guess it doesn't really matter but when we do return the list with the duplicates removed we want to make sure that the list is still sorted so it probably makes sense to maintain the existing order of elements as we remove elements right if we remove this one the remaining elements should still stay in the same order and then after we're done we can just return the head of the linked list so suppose we're given this example linked list we want to remove the duplicates from it and then return the new list one thing i want to mention before we start is i usually have a dummy node in linked list problems and if you also use dummy nodes and linked list problems you might be wondering do we need a dummy node in this problem or not and the answer is no and the main reason it's not really necessary is because the head of the linked list in this case is never going to change why exactly is that well because the list is sorted right so the duplicates are going to be right next to each other so in this case we have a 1 at the beginning of the linked list if there's more ones in the linked list they'll come right after it right so the best way that i'm going to handle this is never removing the head if there are duplicates i'm going to remove the duplicates that come after the original right so this one will never be deleted we'll delete the extra ones that come after it so this pretty much guarantees that the head of the linked list is never going to be deleted so a dummy node is not really gonna be super helpful in this case if we were going to delete the head node then a demi node would come in handy because in that case you know let's say we delete this node then we'd have to take this pointer and then point it here and the good thing about the dummy node would be that the dummy node is always going to be pointing at the head if we have a new head or if the head ended up staying the same the demi node is always going to point at the head but in this case the head is always going to stay the same so we don't even need that dummy node but in terms of the actual algorithm of course to iterate over this linked list we're gonna need some pointer right i'm just gonna call it cur it's gonna point at whatever the current node happens to be and of course initially it's gonna be at the head of the linked list and we know that the list is sorted so of course duplicates are gonna be right next to each other so the question now is this is the current node is the next node right after it is it a duplicate right is this the same as the current node and in this case yes it is so what does that mean of course we have to delete this node right we don't want duplicates we have to remove this duplicate how do we do that well since this is our current that means this is current.next right but we don't want current.next right but we don't want current.next right but we don't want current.next to you know exist in the current.next to you know exist in the current.next to you know exist in the linked list so what do we have to take this pointer uh you know change it to be the next node right and that'll effectively delete this node from the list the operation we would do to you know reassign this point is basically say current dot next current.next which initially was current.next which initially was current.next which initially was pointing at this node right is now going to be pointing at current.next.next to be pointing at current.next.next to be pointing at current.next.next so the node that comes after it over here right so basically what we did is we took this node and now have it point at the next dot next node which basically deleted this node from the uh linked list and i'm actually going to change the value of this node from 2 to a 1 just to illustrate this problem a little bit better so now our current pointer is still here but we changed the next node to now be here so our current.next is now at this here so our current.next is now at this here so our current.next is now at this node so again we want to check uh you know our current pointer stays here it stays at the same node because there could still be more duplicates of the node one so now we're going to check is this still the same as our current node again it's still the same so we're gonna do the exact same operation we're gonna you know basically delete this pointer and you know delete this new pointer that we just set pretty much and now have this one node point at the next node uh that comes right after this one which is a three now our current.next would be at this now our current.next would be at this now our current.next would be at this next node which is three and what we would now uh you know determine is that this is not the same as our current node right current is one current.next is right current is one current.next is right current is one current.next is three so it's not a duplicate so we don't have to delete it so what does that mean for us it means basically now that i've cleaned this up a little bit that our current pointer can be shifted from here to current.next which is now from here to current.next which is now from here to current.next which is now pointing here so yeah basically current pointer is here now and we'd you know finish up the algorithm by saying okay is this equal to current.next which is over here uh to current.next which is over here uh to current.next which is over here uh well yes they're the same so now we're going to delete this pointer and set it to whatever comes after node three which of course here is null and we check is null the same as three of course it's not the same so uh you know we can take our current porter and shift it uh to the next pointer which now is at null so current is at null that of course means we're done with the algorithm and we have finished we can return the head of the linked list so the new linked list looks like this pretty much right one three uh not a second three i don't know why did that just one and three right that's the entire linked list so we return it and we're done as you can tell from the algorithm we really only had to look at each node once right so we just had to iterate over the entire linked list so the overall time complexity is big o of n we don't really need any extra memory so the memory complexity is big of one now just to give you a preview the way we're actually going to implement this algorithm is nested loops so we're going to have an outer loop let's call that loop one and then we're gonna have an inner loop let's call that loop 2. now you might think how is the time complexity of n if we have nested loops that's one of the most common questions i get and just because we have nested loops does not mean the time complexity is n squared let me show you why because as you saw from the explanation our loop one is the outer loop that's going to be what determines where our current pointer is so each time we shift the current pointer the outer loop is what's going to determine that you saw that our current pointer was initially at the first node and then next we shifted it to this node right we basically skipped some nodes in between and the reason is because we had our current pointer here and then we shifted it here because in between the nested loop the inner loop is the one that basically deleted this node in between and then it deleted this node again right our inner loop is basically what takes care of the duplicates and our outer loop is what takes care of the actual unique value nodes and our inner loop also you know deleted this one which is why our current pointer just skipped from here all the way to here so that's kind of why uh hopefully the colors make it a little bit uh illustrative of just because we have two loops doesn't mean with the time complexity was n squared you know each node was basically visited once so without further ado let's jump into the code so now let's do the code and the best part is now that we have really spent a lot of time understanding this problem the code is actually really easy so uh like we said the current pointer is initially going to be set to the head and we're going to have an outer loop this loop is going to determine where current happens to be and of course we're going to continue doing this outer loop until current happens to be null so while it's not null we're going to continue and remember our inner loop is what handles actually deleting the nodes so how do we know if we have to delete the next node or not well first we're actually going to determine if a next node even exists so we know that current is not null because of our outer loop but our inner loop needs to make sure that the next node does exist so if the next node does exist and if the next node's value the value of the next node is not or is actually equal to the previous node's value if the next node and the previous node have the same exact value that means we have to do a delete operation here and remember how did we say we were going to do that delete operation by saying current.next delete operation by saying current.next delete operation by saying current.next is equal to current. so that effectively current. so that effectively current. so that effectively deletes the node and that's all we're looking to do right so now we're going to you know this is a loop so it's going to go it's going to ask the same condition again current right the current node stays the exact same but current.next current.next current.next is going to be different now so we're going to check okay is the next node still not null and does the next node have the same value as the current node right so this loop is going to keep deleting nodes if it if they're the same value but once that is done we know we've deleted the nodes that we need to but we potentially have to update our current node for the next iteration of the outer loop so we're going to say current is equal to current.next current is equal to current.next current is equal to current.next whatever current.next happens to be whatever current.next happens to be whatever current.next happens to be maybe we deleted like five nodes and current.next is gonna be five nodes current.next is gonna be five nodes current.next is gonna be five nodes ahead now and yeah it looks pretty short and concise uh because that's the entire code so after we're done with that uh current will have reached the end of the list so we can't just return current as the head of the list right that's going to be null what we have to return is the head because that's you know the same head that we were given in the input so that's the whole code now let's run it to make sure that it works and as you can see yes it does work and it is pretty efficient so i really hope that this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon where you can further support the channel if you would like and hopefully i'll see you pretty soon thanks for watching
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Output:** \[2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List,Two Pointers
Medium
83,1982
918
Hello hello guys welcome back to take 2 sign in this video bhi seedha maximum circular saver problem with established codification of the match so let's no problem the giver simple and will last for limited subscribe to the Page if you liked The Video then subscribe to the maximum subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe Qualities like to right and in some parts of forest land will use this remedy in this is the missions we will be one to three so in this Pages You Can See Is Totally Content And 108 Totally Content Inside This Year And When Ur Parents Rather To Cases Possible Na Latest All The First Solution Solutions To Solve This Problem Solved And Simple What Do We Need To Take Off The Giver The Property Of The Volume To You Need To Know From Starting Point To Pure Maximum Sum In This Is This One Five And You Can See This One Which One Dead To The Maximum Service Will Be 59 The Second Generation Urine Creator Starting Value To 10 - 30 Increase The Volume To The Fast To 10 - 30 Increase The Volume To The Fast To 10 - 30 Increase The Volume To The Fast And The Furious And You Will Take The Return Of The Day For The Day Subscribe Thank You Will Quickly And Come Back To Time Simple Looters Ko Subscribe OK What You Can Give Life As Properties Mentioned You Can Just Write To Service Solution Up and 182 Rates and Discuss the Problem Will Find Maximum Window Size of subscribe to the Page if you liked The Video then subscribe to the Difference between Right and Subscribe Minus Plus One is Equal to How To right in the middle east countries for today's problem solve this problem will take mode of end time and sons were taking or double century so it will also take water for express so let's do possible actions in order to make the solution very simple so let's you R Govind Savere And You Need To Find The Maximum Savere Giving Tarah Property Know What You Can Do It Is Defined Minimum Sub Resham In This Is The Minimum Balance - 3 - 2 - Resham In This Is The Minimum Balance - 3 - 2 - Resham In This Is The Minimum Balance - 3 - 2 - Total subscribe The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Minus Plus Minus Two Shane Warne of Boundary with this method letters is fine and all the values ​​of method letters is fine and all the values ​​of method letters is fine and all the values ​​of native and in case you will have to just return the minimum possible negative value for this is the only boundary case for this simple solution so implement solution while implementing this one such Method By Using Cancel Gautam Solitaire Se This Is Or Original Here What Will Lead To A Rise In Water Every Element Basically Amused With - And You Will Find The Maximum Sub Subscribe Now To Receive New Updates Reviews And News Bollywood Dasham Which Is Equal To - 9 In This Bollywood Dasham Which Is Equal To - 9 In This Bollywood Dasham Which Is Equal To - 9 In This Case Know What To Do In Order To Find The Original Maximum Sir Actually 300 Gurjar Inverted Dare I Will Subscribe This - 1 Inverted Dare I Will Subscribe This - 1 Inverted Dare I Will Subscribe This - 1 - The Observer 4 - Sexual Subscribe Very Simple And Person Do This Is Gold Channel Subscribe Total Time Complexity Of Senses And Subscribe for This is the solution for solving this problem but have not implemented this solution has implemented in alternate solution Soldiers in this example in order to understand this solution sudhijan alternative method and take basically 522 temporarily unavailable subscribe did not give any property subscribe will Calculate the Maximum Without Having Any Property Rates Will Calculate The Minimum Without Having Any Property In This Is The Temperature Of Bluetooth Zero And They Want To Maximize Maths Tricks This Is The Maximum A Day For The Temperature In Maximum Will Be Updated With New Value 10225 Compare With Attempt Maximum Is Greater Than Subscribe Will Update This 2500 Vighn 000 Se Want To Maximize This Is This What Is This Current Value Will Be Id Am Id Subscribe Minimum Of Well That Ninth Project This Will Check Vitamin Committee Formation Zero Because They Want To Minimize This Cigarette 104 Disruptions 2019 After Doing This Process Finally Video Friends Welcome To Years Which Will Be Id Subscribe Now To Receive New Updates Subscribe - - - - - - - 2009 Subscribe - - - - - - - 2009 Subscribe - - - - - - - 2009 Subscribe - To Get Started Adams - 59 Minutes After - To Get Started Adams - 59 Minutes After - To Get Started Adams - 59 Minutes After - Blames for Women - 5 - I Will - Blames for Women - 5 - I Will - Blames for Women - 5 - I Will Observe This Will Be Sent To - 59 Dec Will Also Observe This Will Be Sent To - 59 Dec Will Also Observe This Will Be Sent To - 59 Dec Will Also Be Updated Actually Sued Over Five and When - President Will Welcome to Be and When - President Will Welcome to Be and When - President Will Welcome to Be Minus to Do It Will Welcome Zero Okay I Love You Are Understanding And No Veer Montu Speaker Element Image Process Ten Letters to the Maximum 9 Maths Semi 6 Straight Including 500 Verses chapter-2 69 Stumping Committee - 560 Will Get a chapter-2 69 Stumping Committee - 560 Will Get a chapter-2 69 Stumping Committee - 560 Will Get a Date Will Welcome One No One Has Actually Greater Than - 510 Will Not Get Actually Greater Than - 510 Will Not Get Actually Greater Than - 510 Will Not Get Updated and Temples Committee Secretary Vijay Greater Than 1000 to 1200 Withdrawal 6 to the Next Element Which is - 9 - 121 Next Element Which is - 9 - 121 Next Element Which is - 9 - 121 Quick of Evidence So Nothing Will Be Done Against All This or Minus One Will Be Difficult Minus One and Mint Street Time Sexually - 5 Days For This Is Time Sexually - 5 Days For This Is Time Sexually - 5 Days For This Is the Worst Thing Will Be Done in a Semi 6 - One Will the Worst Thing Will Be Done in a Semi 6 - One Will the Worst Thing Will Be Done in a Semi 6 - One Will Be Id 512 Element 49 and West Macrame Will Not Enter Subscribe 2018 - More Will Not Enter Subscribe 2018 - More Will Not Enter Subscribe 2018 - More Video Subscribe Will Introduce Elements of Obscuritism What is Equal to You Can See All The Limits Of Negative Plan Limit Has Be Negative Dark Time And Administrative System Will Be Equal Otherwise Vote Bank Force So They Can Just Compare So In This - 513 Otherwise Will Return So In This - 513 Otherwise Will Return So In This - 513 Otherwise Will Return Maximum Of The Maximum Which Is The Property Of The Year - Minimum subscribe Property Of The Year - Minimum subscribe Property Of The Year - Minimum subscribe and subscribe the Channel Please subscribe and subscribe the Noida San is equal to the mystery at all elements software basically negative The Video then subscribe to the minimum possible negative element to know all the limits of negative topic maximum subscribe The Amazing Content inside the property and subscribe Must subscribe property subscribe Video then subscribe to the solution Different languages ​​please like to the solution Different languages ​​please like to the solution Different languages ​​please like this video share and subscribe your videos watch this video
Maximum Sum Circular Subarray
reachable-nodes-in-subdivided-graph
Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. **Example 1:** **Input:** nums = \[1,-2,3,-2\] **Output:** 3 **Explanation:** Subarray \[3\] has maximum sum 3. **Example 2:** **Input:** nums = \[5,-3,5\] **Output:** 10 **Explanation:** Subarray \[5,5\] has maximum sum 5 + 5 = 10. **Example 3:** **Input:** nums = \[-3,-2,-3\] **Output:** -2 **Explanation:** Subarray \[-2\] has maximum sum -2. **Constraints:** * `n == nums.length` * `1 <= n <= 3 * 104` * `-3 * 104 <= nums[i] <= 3 * 104`
null
Graph,Heap (Priority Queue),Shortest Path
Hard
2213,2218
380
Hello friends today I'm going to solve record problem number 380 insert delete get random of one so in this uh problem we need to implement a randomized set class in this class we need to initialize our randomized set object in this function which is the very first function here and then we need to Define our insert remove and get random functions as well so the insert function what it does it takes an argument and it inserts that value if it's not present in our object if it is present then we return a false as we return a true similarly for remove it takes an argument well and it checks if the value is not is present in the element in the object then it removes the value and returns a value returns true if not it returns false and in case of get random we return a random element from our current set of elements and the probability of returning each of the elements would be same and all of these functions should be on should be completed on of one time complexity so let's see how we could solve this problem here we have this input and the output is this so basically um uh this first parameter says that we need we are creating our object our set which will um where we will perform our insert to move and get random operations so the for the X parameter is an insert which is uh which takes a value one the argument one so basically we are inserting our one to our um object so far let's not Define Which object which kind of data structure we are using and next we need to remove uh to write so while we insert it uh one we know that there is no one in our um data structure so far so we're in we were able to insert one and we return it true and now when we are asked to remove two well we don't have to in our data structure so we return our false because we are not able to remove anything next we are asked to insert the value 2 here so now since 2 is not in our data structure so we insert the value 2. next we need to randomly get a value right from the data structure so since we have two elements here there should be a 50 chance of getting one of those elements um so basically um that is what equal probability means so if there are three elements then we'll have 1 by 3 probability of getting each of those elements and so on so now um after get random we need to remove again so we need to remove our element our value one now um to perform a remove operation we need to do it in all of one time complexity also to perform the insert we need to perform it in of one time complexity so what comes in your mind when you think of uh of one well in case of array when you push an element at the end it is over from time complexity but if you need to remove an element from the first of the array then it will be o of and time complexity if in case um you remove it from the very first and then you shift all the elements um towards the left so that will be an all of one off and time complexity um and also um we need to check while we insert or remove if the element is present in the area or not right so is array um good example a good data structure for us to use well yes definitely it is if we use it along with a map so let me show you here so what we are gonna do here is we are gonna use a map as well as an array our so we are going to use a map and an array in the map we'll have key which will represent the elements in the array and the value will be the index of the elements index alter elements so how are we gonna do this is that for example I have an array here um so my elements are insert I need to insert a value one in my data structure array so what I do is I insert the value one um I check I need to check right if value one is exist in the area or not so what I do before inserting what I do is in the map right now my map is empty so this is my key and this is my value so right now my map is empty because I have I do not have any elements in my data structure so far so now I need to insert the value 1 and I checked is the value one in my map uh basically no so what I do is that means that the value 1 is also not in my array because uh only those keys are in my map which are in the data structure so I insert my value one I push it to my array and I also add the element one and then the index of that element which will be zero here and then next if I'm asked to insert an element 4 in my array so now I check if the element 4 is in the map um well 4 is not in the map right so um what I do is I insert the element I um with the index itself and I also insert push it on my to my area next if I'm asked to push an element zero then I check it's not in my map so I insert the element 0 with the index which is equals to 2 and then I push it on my to my array so all of these are taking place in all of one time complexity because push operation is off one and in map to look for map that has um has features so we are using map dot has function to check for each of these elements and these this function is also off on time complexity so we are doing it in one time complexity now next we are asked to remove the element suppose 4 from our array from our data structure so what we do is we check in our map does four exist we use this function to check map the task 4 and yes it returns a value of one so which means that we have our value 4 at index 1 so what we do is um we replace the value at index one with the value at the end of our array so this will be replaced by zero so let me just use another color here so we will replace four by zero here and then decrease the like length of the array or we could use to array the pop so pop we could use pop function on our array and then what we do here is we also delete this element here so we delete the value here from our map so we remove this one and the final result we will have one and zero in our array and all of these are like all of one that time complexity and for random as well to get a random value we are going to use math dot random with the index uh with the size of our um of our array so that we get so that each of the elements have equal opportunity to get selected now let's write our code so we need an array um okay and this dot map because we're new map and now to insert if we check in map has the value then return false because this means that the value is already present and we cannot insert it else what we do is we push to our array the value and then to our map dot add we add to our map value and the position so let us do this before we push to our area so that the position the index will be the length of the array here all right and then added to the map and then push to the array which will increment increase the length of the array and then finally return to and now for removing operation we check if it exists in our map or not the value if it does not exist then we return a false because it should exist for us to remove it right so now um if it exists then what we need to do is we need the index equals to this dot map dot get the index of the value so this will give our index and then what we need to do is we need to replace the value at this index pick with the value at the end of the array which is at the length minus one and then pop uh out of the array so we pop from our array the last element and then we also need to delete the element from our map right delete that value and then return our true and then to get random we need to uh the index write a random index rent equals to random index equals to the random um size the size of the array minus one because we need to insert the index right and then this will be the random index and we return the value from the array on that index okay so everything looks good so far let's try to run our code okay it's not that it's set oh something is wrong here got undefined by returning pitch random okay so does this need to uh argument business okay I think I need to see okay so actually in um JavaScript it returns a valued map to random returns a value from zero to one and we actually need to multiply it to read the length of the array to get a value from 0 to the length of the array and this could be in a fraction so we need to parse this we need a floor value for this one crate so our first case pass let's submit our code so what went wrong here okay so get random is not working again foreign okay foreign function actually something is wrong with my remote function see what is it Value method kit foreign okay here while we remove uh we are moving this the value at this Index this index to this Index right so we also need to update that thing here so um map set the value now since we have shipped it the value from this index here to this one X so the value at here is indexed right now let's run our code great
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
1,603
hey guys welcome to my channel thanks for coming back to my channel and choosing my video to solve the problem so today we'll try to solve the lead code problem 1603 easy which is design parking system so here we are given what we have to do is we are given an input which is uh a area of string which says parking system add car at current net car so we have given an array of in this will be our first input like which says one and zero and then this would be the cars so this is a parking system and which describes like one zero and these are all the cars which we want to add one two three so what does the question says so it says that we have to implement this parking system class okay we're gonna implement it here and what we have to do is we are given three integer big medium small so big medium small are the parking space for the car so this is a big car and this would be place for the medium and this would be place for a small so what we have to do we have to uh basically we have to add these cars and then we have to see how many spaces are available so let's see so what just see this thing right so this one would be a big car so you see is there a space for a big car yes there is one space so we can put this space here so if we can put this here then we have to return a boolean called true then second so this would be a medium car do we have space at this space a second which is a medium space yes we have one so it's gonna return to you then you'd see this is a small car so big medium and small do we have a suppose space for a small car if this index you can see zero so no space so we're gonna return false then do we have space for one what is one is again a big car do we have space for one and where does big car goes here so it's one here in the beginning but you remember we used this space to keep this car so now this went to zero so we don't have a space so this is gonna go false i will show you how it's gonna work actually let me remove all of these things actually okay so i'll show you what so see so we have this thing see yeah and what is first time when we go through it right first time when we go through it what happens is we see okay so these are the cars imagine here and here one equals big right two equals medium and three equals small right so what we're trying to achieve here i'll just comment here so what we're trying to achieve here so they are saying that okay first time when we put first car here now what is this 1 0 right i'll write this here so this 1 and zero these are space for big space medium space and small space right so what we are saying okay at first time this is one so if this one can you put this big car in week space yes you can keep so you return to you then can you keep this medium car in medium space so medium space yes you can you have one medium space so this is gonna return a tree boolean so can you keep a small car which is three here no you cannot because it's zero it says zero space so it should return false i'm just saying you what it should return right then it has one more car one which is big car it says can you put a big car again so big car initially had one space but we used this one space to keep this car so it says okay now i don't have a space because you already used it so it should return false as well this is what we want see output this one and now we are just returning it because when we gonna use class so it returns here because they are using a constructor right guess initializing so but you don't worry about that um we'll get our result through this so this was the comments i just wrote it down and if you want you can try it from here but i'll go on from here so what we'll do is i'll try to create a class so we can get idea here so there we have they've already given us param number three number big medium small and they have given us a card type variable which is of type number and it returns a boolean so what we do we create a class so what was the name in the beginning it was parking system right so you create a class called packing system and now in this class what we want is we want a constructor because we want to initialize this data this one this ad car red car how many times you want to add so we initially the constructor and what do we want in it we want big medium and a small car yeah so a big medium and a small car cool now what do we want so we want to now uh like we want to implement this so we want to basically initialize this so to initialize it we're going to use this construction and what we're going to do we're going to say this dot big equals to big the value so we want to equal that big value to the current value of that big so we're just initializing it we're gonna do same for this dot medium equals to medium and this dot small equals to small cool and after this construction we constructed we're gonna make use this method called edgar and in this method what we're gonna do we're gonna keep an argument and what's the argument a card type see they're giving us argument here card type so i'm gonna put this argument here card type is a number so this is this all the card these are the card types one two three one and these are all the spaces this dot big so we want to make changes to this thing right uh you will it will make more sense uh when i'll try it so now what we want to see what you want to now see what we were trying to do here we were checking if this space is available then um we want to see okay it's available then you return to you if it's not then newton falls so basically we want to check so what we can do we can use the if condition so i'll use a if condition and i will say that see if car type what is car type is these things there's one two three one big medium small big so i wanna say if this big car basically if car type i wanna say if car type equals one so we use three equals if you wanna compare the values directly if you wanna see if it's equal to this so if card type equals one then you would say this dot big here you have got the factor like you have got hold of this dot big because you're putting big value inside this so you will say this dot big and you want it to uh make it like this dot big minus one so we will just use the syntax this dot big minus now we'll just after this you want to return as well right true or false so then what you will do you will say return this dot big so you know here it says it returns a boolean so that's how it's gonna so we're gonna say this return this dot big which will be true or false only if it's greater than equal to zero so why only if it's greater than equal to zero it means that it had a available car space and we used it so see here it was one when we used it becomes zero and it's true but this one if it's uh this one so this became zero and next time when we said okay go and use this car space again the one we want to put here it was already zero so then we don't want it to say true so what we can say only put if it's greater than equal to zero so we'll say return this dot big if it's greater than equal to zero otherwise don't return it so we can put one more condition for other cars we'll say else if car type equals to 2 is what it's a medium car if car type equals a medium car then what you do then you put this dot medium minus and same you return after making it one less like after removing that parking space we want to make this medium we want to return this only if it's greater than equal to zero same it's gonna be same for all of those and then you can write again else if condition but i wouldn't write it because it's the last condition so you can just use the else and you will write this dot small like if card type equals to 3 or just else then just do this dot small minus basically you want to remove again that last one space from it and then what you do is we'll just return this dot what is this one is small so this dot small only return if it is greater than equal to zero easy right so now we've got all these things and now see what's gonna happen so what's gonna happen is in the beginning it was one it says okay is it equals to one yeah it's equal to one then it says okay then make it zero so here this thing one zero you know this one zero i'll just write it down for you here you know this one zero that space it became here 0 it became a 0 1 0 right in first time and we already passed this variable now second it says if car time equals 2 then it said if car type equals true then it says okay this is not medium minus and do we have the space at yeah we have a space one so then it says okay then you do this one zero as well and this is already zero then what happened third time it says here three which is a small car so small car space is this one right this one it says okay is there a space here no there is no space then it says okay then you cannot put the card there so in that case we cannot return so when if it's true then we return to you but otherwise we return false and how do we return this card we already written a boolean from here so that's why you don't need to really write it so that's how it's gonna work and same it goes last digit which is one the big car it goes again and it says okay if car type equals one which is then it says okay make it minus so this space here this time becomes minus one right and it says okay return true only if it's greater than equal to zero but minus one is it greater than equal to zero no it's not so then it's gonna return a false that's why you got a false here at the end and you got a false here at the end because there is no space for a third car which was also zero if you see i hope you understood it and if i try to run the solution it should work let's see no it didn't it means we wrote somewhere what did we wrote yeah this thing we're gonna comment it out i just write for explanation so yeah now it should work yeah and we're gonna test it as well for different use cases and test cases say it worked we got a good solution writing solution and i hope you understand uh and if you didn't understand then comment in the videos maybe i can try to explain you again or make a detailed video on it but thanks everyone for coming to my video and uh yeah and subscribe my channel if you like how i make the videos and if i can help if i help you in any way just subscribe my videos like my videos share it comment uh it helps me to make more videos thank you so much
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
925
yeahyeah Hi everyone, I'm a programmer. Today I'm going to introduce to you a math problem with pronouns as follows. The name is typed out long. Let's go into the details of the problem. The details are as follows, your friend is typing his name on the keyboard. Sometimes when typing a letter c, the keyboard can be pressed long and that character will be typed one or more times, then I can understand that the fact that it's so long means that when I type, it's stuck with words, right? You have to check that the characters in this less-changed place check that the characters in this less-changed place when typed on the keyboard will return to Chu if you see. The name of your friend A and with a few characters is typed out long so you can check. Okay, let's go to example one to better understand the problem in example one. We have the name of my friend Iraq and he typed on the keyboard this string instead of cursing is a e le ex then as we have tried to define the thing that when typing it is likely to be clear once It can have one or more times the same character appears. We see that for this name Alex, when people type, there are two times, they have two times. The keyboard is called sticky with that word. Diarrhea, you see that in the story Alex has the word no, there is only 1 cure in the first position of age, then in the resulting string we see that also in the first position we have 2 cures, meaning This remedy we have been changed to is typed with the word all two all one time similarly. In the 3rd position Yes, we have the letter e, so if we don't count these two positions we will calculate is this 29 is a position two from A this is a position then we have in the 3rd position there is also a two slots so let's look at it again and do a sticky typing of the word Call Thanh 2 characters So here is the complete explanation, a&amp;e is the thing called sticky words that a&amp;e is the thing called sticky words that a&amp;e is the thing called sticky words that we need to test, then in the schools that we after testing, we can filter out the two contents can become a good cure. If the letter e becomes an e, it will become an ars, right? So we will return to the bell result which is the name he typed correctly. However, this keyboard is faulty, so at some point I will outputs more than 1 character. Okay, then going to example 2, in a good example, we have a string of the friend's name called SK ID and the string that is clearly filled by the person is s ad. You find it strange, yeah? This letter e is said to have the letter e and is typed twice When typing on the keyboard, it says that the letter e only has one letter. This is not a case of faulty keyboards, but because he typed the name and it was missing an e. Like the school teacher, the keyboard is faulty, so the one here must have more than 2 sisters, then it must be valid. We should infer that we will return to Phone. This is a case of mistyping, not a school. combination and keyboard case For example 3, we have the name of this person is Lily which is l e then the name displayed on the screen is ll then three letters E then lr2 letters e then we see this is a case of an error entering the keyboard, that is, a valid case called correctly because we see that there is an l here in the name with a gratitude as the head, then in the display there are two sisters I'm the first one to deduce that if you're the first one, it has a keyboard error so it displays 2 more characters than in Thien Thi followed by the two letters e, then we see that in the displayed result there are 3 cars. Then it turns out that there is a letter. You can type Hanh as two letters, which is also valid, then the sound is the letter L next, or you can type nothing at all. Type one and then one, then there is a keyboard error, there is no typing error, and The second will be the two letters e, then we will also display 2 for e, then infer that we will return to Chu for the case of Example 3 a for example 4, we will have the word Lai Dinh, the name of the friends is After returning to the temple, people clearly returned to the temple, but there were no typing errors or keyboard display errors, so surely the two topics were the same, so it returned to Chu. Is that so? I have gone through four examples of the problem and think that through 40 real applications, you have grasped the requirements of the problem. Now I will move on to the next part which is to think of an algorithm to solve the problem. For this problem, for and this one I will use one with one strong object I will use one strong object for each of these banana trees I My purpose of using the object piece is to mark again The number of occurrences of those characters At the yth position of the banana tree, the details of my piece tree are as follows. I will have a piece. Well, I must first have the object first, then the age of For me, I call it Mai cha, then in my Mai cha it will have 2 characters. One is the return value in Tiger and the second is the type called Cao, not interior. then this love bar will keep this suitcase, it will keep the character registered at the character position at the yth position of this place and this frown is the number of times the item appears. From there and my piece. For example, if I have an em piece and I have a spring roll chain, then I will have a corresponding piece. I will have one piece. Here, only I have one. Here, Mai Tra. But if there is an umbrella to help die, I will infer that if it is built from this piece, then after I build my piece, it will have something like this. I have to make an example later. ha That means in the economic position, otherwise the thin sky here will also have a position that specializes in seeing nothing. Yes, then it will be in the zero position. I will have 2 values. These two values ​​are equivalent to The 2 values. These two values ​​are equivalent to The 2 values. These two values ​​are equivalent to The two values ​​in this ospy bottle two values ​​in this ospy bottle two values ​​in this ospy bottle are in position, otherwise I see that my suitcase is A, so the character in position, not of the printed place, is A, so I think this is A and number. How many times does ' appear? I How many times does ' appear? I How many times does ' appear? I check here and see that there is one. I check and see that here and there appears once. Then similarly, I go through the first element of the This array Well, the first molecule of this is if I see it is the character l0, I will give this the value is em is a l and this L down to the appointment how many times em will appear once then it is also one then My code continues to go to the 2nd position. The 2nd position is the letter e. So here I am E, then I have a value here that appears once so it is one and the last. Also, the 3rd position is the letter of my search means a fragment consisting of these objects, then I simply say I will have a dog y I browse from the first element of the string to the last element of the string If the element I will take the Index of y which is the interaction of the thing here of mai xa Yes. Then every time I browse through the element at the final position y, I get the value at the final position y of the characters at The final position of the string will be the suitcase of death. Our cavaron will be the offset and then we will have a high variable. We will have the number of occurrences of this character at the beginning of the string. position in the sky, in all of these Iraqi schools there is one. Okay. Now let's go to the second one here. The second one we have to build is the final one here for the chain. Hey, I 'll also have a sieve of 'll also have a sieve of 'll also have a sieve of maitreya in this place. Yes, yes. Now I'll also start from the position. No. Well, we'll see at the position I'm not. If we fix it, then We will assign its value as a. The value of this post is a. Then we need to be a. However, let's give these people a value. The current value of the character tree at the 2nd position of this banana tree, we see that this value is still A, right? Checking in this offset is the letter a, it already exists. It already exists in this table. So I just need to check the Yes, the adjacent elements, the nearest adjacent elements of this piece so I can get the bar to get it out. Let's check who it is, right? Let's stretch this one again to see if it goes up to two. Now if it's not then we'll appear twice and then we'll go to the l sister then when we Checking Ms. L, we see something strange in the ins and outs of this piece here. It's being corrected, but now through the letter L first, there's a new letter, so there's a new million so we'll increase the cold print variable. then it becomes index1 then curses again that my l is saved as the number of occurrences is 1 and then similarly to the variable e This intek is good to increase and my AE at first was also the same Here at first it was also me, but it was lazy. Counting down the number of occurrences was also one, but when it got here, it checked the guy next to it. The suitcase of the guy next to the array of my tra hey it's adjacent so it's the same 2 sisters e so the height increases by one unit to become 2 and finally we have the know Yes the x variable we also have the occurrence and occurrence is Then, after we have finished building the two pieces in the afraid of my father of this spring roll, we will compare first and we will see that if the length of these two pieces is different. That means the led of the lens I called up of this one is this piece is the network that calls back to the di sneha array and this piece is called the y network that has gone to the end of the term, I see that the led of the device is less. It's different from Y's LED because I deduced that this one is definitely a Phone because the two date pieces represent the number of these two pieces represent the number of characters appearing in the scene: em and number. The number of characters appearing in the scene: em and number. The number of characters appearing in the scene: em and number. The number of characters appearing in the percussion tree is displayed on the screen, but if the number of characters on both sides is the same, I can see that this is not an error from this system. On the keyboard, it's my fault that I'm missing the letter a, then if in the case that these two character places say that these two pieces have the same number of characters, then they We also have to consider a school that is our own. Looking at each intact one, each Index alone, we can see that if this suitcase and these two Hoa Luu are different, it's an assumption that they don't exist either. If I go back, I will say that if the bar is too different, I will infer that it is also a phone, or now if the suitcase is the same, I will make fun of it, I think that if the sarcasm of the fetus of the here of mai cha of the word rather which is smaller than the one here meet ai rather here of mai cha of the Ua nem means it looks like this case 2 if In this good school, we see that the word Yeah, here, its height is equal to two, but here the letter E is the height, it is only equal to one, then this school is good and we can see that it's because of us. the name we have but we only have fewer times than the number of times we need to clearly say it says phone then we just need to see that then we say again this place is to set its height to be less I eat cao but it is bigger than dai cao or should I infer that this is a phone Well, if all three of these overcome all, I will get the strange value Chu which means this is a The 3 ways to change the box are: If the display is correct, 3 ways to change the box are: If the display is correct, 3 ways to change the box are: If the display is correct, I typed correctly, but the way it is displayed is wrong because the keyboard has typed some extra characters in some specific cases. increase to two or three words or more, then this is an algorithm that I will use the Cola programming language to install. During the installation process, I will continue to explain so that you can easily understand. better than my old one. Now I'm going to change the newspaper to one like tomorrow, father, I'll change the newspaper like what I told you at the beginning, my father's tomorrow style is a death, then in this death I will define or value, the first is my suitcase, then I can give it the type ah Yes, for this value, I can give it the type of insignis image sent in 8bit only Yes because it will be saved from the English when we will store the characters of the English string then it will have enough then this high will be the interior type word then this sport will be the number of occurrences of the risk of that character Now we There will be a function, then I will have too many goods, but I will Bill the one here to meet these guys, then I will call the yard fan, but the small one is Bill Gray a Porter girl, then I will pass in this a string and name it. Let's go guys. Then my return result will be a slim one again. Yes. Then we will ah, you have to report a resort as a slim one. Yes. Then we will return zezo Now I will start calculating at first I see the squeeze one Intex variable then these internets are the Intex of the one here Ha on this land will be the ntech according to the first one here This is not the Intex of not the internet of running variables. Well, this Tet at first, my name was me. Can I come to you? The password matching game can be Va Index in. Then after that, the J zo here I will pin and an initial value of zezo then create an object tomorrow then now know the object At first my role will be this is burn this is I will give In this Mai cha is the first object in this string of spring rolls, that is, the wedge is in the zeroth position and the second one is a tall one, at this point your height is as tall as a house and then the bride has to have another one. and then we will start the filter one by one, let's say y I'm for y = y = 1 because y I'm for y = y = 1 because y I'm for y = y = 1 because I put the first guy in and then y is smaller than my led and Y + + y is smaller than my led and Y + + y is smaller than my led and Y + + then Then I'll check if I 'm in the y position and it's equal to the J 'm in the y position and it's equal to the J 'm in the y position and it's equal to the J in the Intex, if it's dot cavalier then it's me then it means at this point I've approved a job through a character and then That's it, I just check the reverse and these characters are the same, so now I just need to increase the counter variable at the position then rich shopping hates J zô plus shopping hates J zô plus shopping hates J zô plus Yes Then after that Then we will have a school that can be taught. In the opposite case, this means that this is a new character that does not exist in the piece here , we just need to , we just need to , we just need to put it here and say a word. the new one We put it in tomorrow, we have to tell tomorrow, the value is the same, it's where you are now, it's from the waking position ah so we have to limit part 1 Yes, remember yes a comma Yes. Then we will increase the Index by one unit, then this intek is the value that we keep so that we can consider it in the variable and in the fragment we This is the index of the piece, so the indexes of this machine only change when it encounters a letter and increase when it encounters a new character, but also when it encounters duplicate characters. then it wo n't increase, but it has to increase what is known. Okay, now we have the Bill piece here, now we will call it by our name, let's name it the same as xy. Now I will go back to the main function, I will declare a strong x and an array y, these two pieces are built from the function Bill Gray sport look up and then I will pass into it first the nem nê little A and the second one is me Pieu I Pray love the father of the hot pregnant then after we Mieu we call those two rows we will have two pieces we glue and little so now we will Let's check the other things for this condition. First is whether the length of It's a phone, so if we're going to compare now, we have a filter y which is zero when it's smaller than the length of x. Now the length of x and y are equal, then after we Having just passed this condition, the two lengths are equal, now we will check each element in this strong and small y array, what will we check first? KW's idea is that if it is different from the one in Lieu Vy th2 in the data at the final position and the two suitcases of these two pieces are different then we will return it back to Phone and add one more. There is a fan, a suitcase of an areca tree in position We typed 1 character missing. We typed an order missing. In this case, we typed the correct order of characters but the number of characters typed was wrong. Turns out it's not enough, the quantity typed is not enough. And this is a number, for example, this one is a thread, but when we type again, we call it the letter B. That's it, so what happens when we If there's anything wrong with these programmers, if it doesn't answer the phone, then this is definitely a place to learn again. Let's try running this program with the first example to see if it has any problems. I turned it off like this. So I have successfully sent the example and the result that comes back is Chu, which is the same as the result asked for problem A. So, I have successfully solved all the remaining examples, then I will see the complexity. algorithm of this problem but I see here that if we call these two functions bills function people's function then we will Viettel the length of the brother and the length of Pepe the length is very much the number of molecules in Nem and the number of characters in night and the number of characters in thai Besides, then we have one in Hon Cai Vong Lap, also Viettel, the number of elements in the network X then you This little bit. In the worst case, its length is also the length of a lump of catfish or F2, then we can consider the complexity of our algorithm as if we call n the number of elements of spring rolls. m is the number of elements of the fetus, we see that it is n + m and the complexity we see that it is n + m and the complexity we see that it is n + m and the complexity of the storage space we see that we use an additional look piece here. Ha and this look piece, it is he also has the length depends on nvm, so we see that the complexity is more than the storage space is also n + for me, I will call and I will end the video here. Thank you for watching. If you find it interesting, please let me know. Please leave a like, sub, like and share the scriptures. If you have any questions or comments or have a better solution, please write them down in the comments section below the video. Thank you all. goodbye and see you again yeah
Long Pressed Name
construct-binary-tree-from-preorder-and-postorder-traversal
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
null
73
Hello guys welcome to my video dham coding cricket us problem call me to elements of obscuritism example subscribe to like this 12345 videos do subscribe thank you to all so much that they cry to retire from this inter college students were already Made Column Jimmy Rolls Royce Ne Xerox Suresh Point From Bigg Boss Similarly I Will Make A Is Particular Intro S0 And Will Make The Sentence Column And From 0.2 Is Box Again Will Make Ben 10000 S 0.2 Is Box Again Will Make Ben 10000 S 0.2 Is Box Again Will Make Ben 10000 S Well S Specific Volume 10 Glass Works Include All Readers Will Be Coming Cumin Fennel Before Snow Coloring and Feeling Away All the Boxes s0n Immersion All the Roll The Adventures of Column of State for Beginners Albums Us Okay Na Let's See How to Three Soldiers Problem Solve This Problem When Approached Them Whenever She Would Make All The Adventures Column Values ​​Point To That's Us Column Values ​​Point To That's Us Column Values ​​Point To That's Us Must Subscribe Quit Zero OK nod32 Problem Yes-Yes OK Quit Zero OK nod32 Problem Yes-Yes OK Quit Zero OK nod32 Problem Yes-Yes OK Next Club School 01 2010 And Not Actually OK What You Are Doing Well In No Way To Identify and Mark Intercourse 9000000000 This Particular Elementary And what rule this point this particular in everything I will not refuse nuvvu you doing this you all the flying license subscription okay 9:00 am notes simply like arrest 9:00 am notes simply like arrest 9:00 am notes simply like arrest suvivi's news normal raw metric from back copy of the matrix to health tips Gyan Adhoora So Let's Make Up For The Same Size For All Elements Of Obscuritism Women Will Change The Way Will Not Be Able To Work With This App You Will Always Remain Valid Points 102 Voter ID Answer Per Debit The Time Complexities And The Problem With Nod Time Complexity The Biggest Hurdle The Different Uses Complexity Person Tweet In Place Protest Use App To Another Pre Matric Sorry Number-21 Oven Space Complexity But What Number-21 Oven Space Complexity But What Number-21 Oven Space Complexity But What Is Complexity Of Dissolution Its Form Into And Tried To Address This Problem During Extra Space Ok Na Time Complexity Of All the best quality sacrifice element and corresponding this elementary sorry for writing introduction limit ulte came into one time complexity yesterday point which element which will lead to role- point which element which will lead to role- point which element which will lead to role- plays the volume to you will have time complexity volume it is best selected mother better way to Give It's Mother Better When Will Need This Large Matrix I Just Understand CPI(M) Between Values ​​Using Understanding Are CPI(M) Between Values ​​Using Understanding Are CPI(M) Between Values ​​Using Understanding Are Doing Its Best That Vinod 852 4000 Play Store Is Particular Index For This To Is Particular Inactive And Mineral Acid Various Are Introducing Matrix Reduce The Time Updates Videos Public City From 12321 D University Born 2342 Rains Wave In The Villages To The Independence What Do We Call The Satanic Verses With Say Zinc Pro0 Address And Long Wishes Column To Switch To Grow And Corresponding Olympic Serving Seen Vitamin Row And Column One Needs To Update OK Techie Vivek Singh Bist And Also Withdraw Loot Middle Destroy Chinese Roman Range Rover Acid Column 1 Column 2 Quid Next Depend On It Ring Road-2 OK Quid Next Depend On It Ring Road-2 OK Quid Next Depend On It Ring Road-2 OK Drishti Serving Road To S Well S The Volume Which One To One Column Values Problem No Problem Solved Reduce Volume 09 2010 2011 2012 Subscribe to Think Something Area of Square Restoring The Video then subscribe to the Page if you liked The Video then subscribe To My Market Tested English Lecture Half Dancer Request with Values ​​of Tourists for the Worst Floods Values ​​of Tourists for the Worst Floods Values ​​of Tourists for the Worst Floods In follow back to make all the valley school amazon phone collared shirt or to make diwali certificate school van road into to make departures tu roegi to make a call to the self no not at this is easy to use no dues extra final Problem Oven subscribe The Channel Please subscribe this Tours in words with letters that Euro use the first royale the first poem is based on markets ok what do you mean by rajveer123 system inside and went through use this is yes ok no problem yes-yes use this is yes ok no problem yes-yes use this is yes ok no problem yes-yes Story True and False Values ​​Back How Story True and False Values ​​Back How Story True and False Values ​​Back How Made To Twelve Verses In Adherence To Zero Number Is Liquid Such Fold Problem No Problem You Wish For Office Eyes Are You Need To Mark Which Where Formal Where Four Size Maze Pay Dowry What Will I Don't Think You Have to Store in This Particular Column Relief Historians' Particular Column Relief Historians' Particular Column Relief Historians' Problem Yes-Yes to Here But She Always Stood Problem Yes-Yes to Here But She Always Stood Problem Yes-Yes to Here But She Always Stood in Place and Share You Easier for Watching This Too Are Inside and Difficult You Are Right You Cannot Used This Particular Values ​​IS Pure and science in you will Values ​​IS Pure and science in you will Values ​​IS Pure and science in you will reduce the problem only invatas in this matter what is cricketers who hear what will you to the volume to bank details problem na latest tried to ignore this problem in laddus last latest minerals solution slowly latest ignore this and you have only Three Westminster Abbey Quiet Bay Worked For Weeks But Latest Markundi Dave Lift The Inside It's Okay What Were Made To Avoid 30 Minutes Later Should Consider All Is The First President Of India In 100 BC Ray Does It Means Torus Zero Correspondingly Admit 2003 Points Her Correct Foreign Tourists force him this box these days roli first for looking at trivandrum matrix videos forums ashwagandha powder and 2000 corresponding column and corresponding roli store zero ok navvi 2050 rate listen no what can i do not disturb problem final match final year for simplicity and destroy Values in To-Do List Ishwar Markets in Us Twitter Values Stop This Point in Delhi All the Columns and Values ​​for Example in the and Values ​​for Example in the and Values ​​for Example in the First Kill in the Forest Amazing Experts Will Make All Respect You in This Column 10 Auditions in Camp Zero Simran liquid you including this particular markar this is that do markets issue on two markar 90 markar edison markar english number 90 this point be long that election water this next markar next this 10 markar chain call divine next this 10 markar you will always Be Used To Give What Is The Solution Of The Problem What Do You Celebrate With clt20 Final Solution Apart From This You Should Problem Is That Matrix Also Folder Problem Successful Is Award For Best First Law And Order For Columns Were Not Given Or Solving Problems For True Values Will Just 16 Two Elements With The First Role Ambitious Zero Late May Make Exclusions Vivekanada Available By turn of pollution left over the example again drive not this particular singh anil vaidya complete logic that show bihar day particular matrix plate blindly Jupiter kilometer this letter black color rod markar ok chutney in black color dore sapoch in the forest column first that Particular RS Verma's column values ​​in this particular problem in this particular role Particular RS Verma's column values ​​in this particular problem in this particular role Particular RS Verma's column values ​​in this particular problem in this particular role in the verses maintain column0's similar to this particular column is the marker in this particular ABCD-Any Se Zauq-e-Safar Zauq-e-Safar Zauq-e-Safar Problem Veer z10 Question Is Later All The Romances Uske Center For Cellular Time Singh Indraprastha Slam Singles Distance Natural You Will Make And Witch Destroys Video Must Subscribe 430 More Quote 8 If Possible Sorry For The Three Mistakes Of My Life In This World In This Manner And Senior Correspondent Already Hit The Ground Values ​​Are Eligible Hit The Ground Values ​​Are Eligible Hit The Ground Values ​​Are Eligible For Appointment Order Cancelled By 0.5 Inch By 0.5 Inch By 0.5 Inch This Particular Checking for this is the answer 3000 1000 to problem 13 sunshine toilet straight code message whatsapp latest straight angle so m taking and image and size the metrics and taking a g p dha number of rows and columns and 1000 for the amazing column value subscribe And do n't forget to subscribe Hussain Starting from Iconic Shoulder Particular Example Battery Saver Servi Trick Shades Trading Updates Yaun I Know Dasha Yah To Market Ve Market Aaya To Market Correspondingly First Prayer For Bride In Abhiyan Users Marketable Value Twenty-20 Key Abhiyan Users Marketable Value Twenty-20 Key Abhiyan Users Marketable Value Twenty-20 Key Twitter User Bullion Value But In This Particular Case Record Junior Vacancies Pair Independence Committed Suicide In Place Market Place Marking 000 Not Given 1212 1000 Hindu Festival Column 1 Column 2 Soil OK What Were Chatting Making Friends Let's Him South Or Checking For The Person Wearing Meghvar And Megh Columbus 09 2010 subscribe The Channel subscribe Kare The Question And Addition And Subtraction But Thank You For Watching This And Definition In English
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
289
Hello Everyone and Welcome back to my channel Algorithm HQ Today I am going to write the code and also explain to you all the algorithm to solve this game of life problem what is there in lead code it is a medium level problem and can be solved Intuitive using a very easy approach. So let's start it by taking the name of Shri Krishna. In this question, we will have been given an m * n grid, which means m columns and a row. It m * n grid, which means m columns and a row. It m * n grid, which means m columns and a row. It is okay. In this, we will have the values ​​in is okay. In this, we will have the values ​​in is okay. In this, we will have the values ​​in those columns. In those cells, there will be only zero or one, okay, so basically they are representing the state of life, okay, live means one, okay, dead means zero, okay, so if there is one in any cell, then it represents live cell and if there is zero in any cell. So this represents the dead cell, okay now every cell will interact with its eight neighbors, horizontal, vertical and diagonal, and four rules have been given to interact with it, we are okay, any life cell with fewer than two neighbors dies as if Cause by under population, it is ok so any life cell will be there and if its neighbors are less than two life cells, that means if there is one or zero life cells then that cell will die, it is ok, it will die because of under population. If there are two or three live neighbors then it will remain alive in the next generation and if there are more than three neighbors who are live then it will die due to over population. Again and then any dead cell with at least three live neighbors becomes a Life cell means if there is a dead cell and if it has at least three live neighbors then through reproduction it will become a life cell in the next generation. Okay, the next state means every cell in the current state were born and Deaths if simple new given the current state of the a in a grid board return the next st Okay, so in this example we see like this is the first cell or zero cell, how many live neighbors does it have, just one, so this is in the next generation. Will also remain dead, will remain zero. Now look for this cell, how many live neighbors does it have? Only one will die in the next generation because there will be two or three life neighbors, only then will the S life cell survive in the next generation, and for this cell also. What will remain is how many live neighbors does this cell have and how many are needed for reproduction? So it will remain zero. Now this one which is a zero cell, how many live neighbors does it have? Two and three are okay because we consider the horizontal ones too, sorry the diagonal ones too. We are doing a Live at Neighbors, three of them are live, so it will go live in the next generation, so if we have to make it like this, then basically we will be able to work with only one grade board, otherwise we will have to make a clone grid board. This means that we will have to clone this board and put it in another one and then we will have to make changes in this board otherwise we will get a wrong answer. Okay then its length will be boat dot length and then boat zero dot. Okay then for enta e 0 aa lesson bo dot. Length i plus n for int j e 0 j lesson board zero dot length j ps and then we will put the elevation of the board in the clone, now again we will rate it on this and the board people will keep filling it, we mean All the conditions imposed here are imposed only on live neighbours. Live neighbors is written, two live neighbors then two and three live neighbors, more than three live neighbors, so basically we have to calculate live neighbours. Okay, so to calculate live neighbors, we will look up all the neighbors and take all the one from them. Okay, so first let's write a function for that to calculate live neighbors, private int find life. In this we will pass Will do I and J meaning the cell whose live value is to be extracted and the indexes of the cell and then board. Okay, so first of all take line it g then f i psv is less than d dot length and board of i psv and j ev to. We will increase the life by one, let's copy it for Zpv and its board will be zero dot length after Apv, here Zpv is ok, Apv Jpv is done, let's take it for Zpv and here But zero will come in both, greater than equal to zero and here also greater equal to g. Here will come a my and here will come z mine. Okay, now for horizontal nevers also we have to write some conditions so a pv should be less. Then both dot length and j psv means we copy this one with j pv should also be less given and here we also take j pv along with a pv, okay now here j pv with a pv Let's take the MIVE, once we delete this one, copy the top one with I MIVE, J MIVE greater equal to 0. Okay, after that, take J PVES with I MIVE, copy this only and delete the bottom one. Sorry aa mive with i psv j pv aa mive will come and here j pv then again i mive with j mive ok this is done at last we will return live whatever is made ok now for every neighbor first We will check if board y clone of i is equal to two, if that is one, okay, then we have to see how many neighbors it has, okay how many live neighbors it has, actually, so on find y, this came twice find life of ima jama. It is fine to have two clones, but let's take one separately, int live, so that if this function has to be called only once, then live is equal to tutu or live e3. What to do in this case, we will put IJ1 in the board. Okay, that means in the next generation, V is going to be live, otherwise we will put zero in i in the board. Okay, now here, if this is zero, that means we should have exactly three live neighbors, then find lie, image, come, clone equal. If 2 is 1 then board i is equal to board i is 0, okay, that's all, according to all these conditions, code compile error has come, int live here, double N has come, let's run and see this sample distance. So let's submit and see if the code is successfully submitted but before leaving please don't forget to like the video and subscribe to my channel if you haven't already also point.
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
518
Hai Bhai Kalyan Loot Se Hai Jhaal Shri Ram Products will be very good and will group you in DP, these accused patience tablets will also be learning Prakash today's video back bus naam barabar video bana raha yudhak hum aur Big End This Question Custom Should Be Destino Light Come Tourist Attraction Shyam Different Uses Same Question Don't even test the celebs, if you wink at them after watching the video then please do a few rounds at such a high price today that they are completely happy. For this you need reference, let me tell you, if his dead body should be kept then the requested video of Fall Same coin, Chintu's real point of such videos will be found in this point to job title. * point of such videos will be found in this point to job title. * point of such videos will be found in this point to job title. * Its just video was earlier, there is an installation in this chapter. If the question is target education then this point of tomato will prevent coffee waste. Watch the whole video. Breakfast question will be made by you. Make sure that if you have not seen it then it is okay and it would be very auspicious and it would not be looking like keep it in some place for use and tell me. And after half a minute, you have to click on the subscribe button from this point, Ghrit 1540 E that the assets of date Ankita Monteiro border should be here, a few cm from it, okay, so there is some contribution, you can give in some way for these vegetables. Ko Inches Part-1 can give in some way for these vegetables. Ko Inches Part-1 can give in some way for these vegetables. Ko Inches Part-1 When I did the lipstick, ask her how much minimum can she pay for it now, it's a little different, okay, the sequence was done and America successfully discussed it should be cooked a little, okay because of the World Cup. You tell me which engineer is present and tell me whether you are feeling well or there is some twist in all these relations. Are you okay? And the people of agricultural states have every specialty to do relation. It is like the previous question, only in the previous question we have first Then it is equal till 2030. Hey, it is right, basically and Pakistan's 2015 fixed rate is 70. Here, I had made it myself. If affair question is asked here, then subscribe to the festival of six letters on it. It means that 125 digits of words are 6 of their own. Hum ticket 125 shift verification to his 101 ayurvedic remedies send written message subscribe pawan 2013 please subscribe and share and subscribe this channel if you have this subscribe to that dent that in this regard to come out from where you can you If you can give it then it has a meter height of 100 grams. You don't have any other way to get the money. Can you give it? What is the interest? Who is the gas? These two curtains are the health of the Gurjars. If you know this then definitely subscribe. Who do you have? 11 2012 That if Akshay comes here then he will discuss 10 parts, you have to pay ₹ 1, 10 parts, you have to pay ₹ 1, 10 parts, you have to pay ₹ 1, take his side, you can still deal with the exit in a way Tubelight August 2018 201 34 Relation exactly to the previous song Subscribe again to that IGL is this DP of IT Mins one who worship A plus Deputy Chief like MR Chairman and that if we discuss once then he is saying that you have to cook I am your itna rupee time when you have itna khayal on twitter What will happen to the weakness? A monk will see that if this ₹ 1 is on the face, then one was that I ₹ 1 is on the face, then one was that I ₹ 1 is on the face, then one was that I broke down but now work on the computer, should I ignore it or not but I do not deny then the peel is as much as zero set off organic There is no harm in this, that's why an additional one came, my Satguru A Paiya, he was giving it to me in so many ways, before that, in what way was he giving it to me, if you have given it means if it has come now, then Till this time it was to be given on like share, this is the symbol of this middle, how much thought was given on it in how many ways for ₹ 2, how much thought was given on it in how many ways for ₹ 2, how much thought was given on it in how many ways for ₹ 2, then this is that this is neither good nor good, I will not be if less or right click hair pack Brahma After this, after adding the status, in my anger, I had visited 119 tests that in this way, the pimples that came at this time, when 1975 pimples, take out the time and do the simple test which was said in this way, now we are in this, I can't take it, apart from that, please subscribe because we - I mean, it was like that way, when we reached here, we were in the appointed village, you have to see which is the time of Ravana, now it has been paired, so it is equipped with practical. There is one way, friends, comment on the same pattern, well, if we remove this from the printer, then what is the question of Miss World-2013, World-2013, World-2013, which is the human Ashwattha tree, then it is not possible to do it, when it is Amazon, if you use two of them, then there will be no problem in dreams. If there is one then this must be subscribed and Above Subscribe - 20131 More 123 Subscribe to your mind 5 Achharika 312 And one bound forward One rights are also needed because when we are intact then if you subscribe to this from above Lightly tell you cancer phone deactivate its answer is positive tiger discus portal of every area then you sometimes that you have so much or fear 0.2 is a way to remove you fear 0.2 is a way to remove you fear 0.2 is a way to remove you member of parliament then if according to defective news channel on obscene talk especially But you will fall on the disco track, by taking tips about it, the music system has not yet been acquired by Khan, I don't need much explanation, now there is hope in the test channel, because by doing this murder, you were free. If so, subscribe to point torch plus one channel. Yog leader of Anup Kitab, want a plus one the can be quite a, cash from Abhishek is a source of inspiration to the listeners, he will stop only in the first top countries, then point icon is also definitely IT IS. If the column of inscription IS Nikalkar Mode 50000 must be subscribed, then it is liked and subscribed, it is authorized, verification, objective and addictions, both are on point, exam point is off side, is on point, Jaipur II, 108 Samudra Amrit, clear, what if I came back in 40 days because of one Tapkeshwar's diploma ji. President, I will request that if I want to do some present then I will do some dal or superhit, then I will have to do a good, it should be possible, the difference should be towards the time, this was the gate and one WhatsApp points you. You can see that it can have some shapes so all this on the complaint and here you have to do minus one and that is [ __ ] Ishraq Sameer Madhok so that is [ __ ] Ishraq Sameer Madhok so that is [ __ ] Ishraq Sameer Madhok so that your pimples in this with this mixture some tips for investigation Question 1 You can do this 0 Infection rate is extended 100 If you understand Alka Yagnik Right point What was the fault of subscribing to the channel So don't forget to subscribe this point Keep it on The freedom is shared Complete joint tax is of size Pass Road accidents are this Now don't eat this This is how much dad does vashikaran on twitter. You can read a saiya in Bhojpuri that girl or click on it at 1109 time. Gyaan is set to maximum. This is the to-do set to maximum. This is the to-do set to maximum. This is the to-do section or chapter note with the point. So now in this you can see. Can this disgusting and here, please subscribe to this channel on the subscribe button. I thought you were watching the video. Now item video problem vs depends. Okay, this is just on Samsung switch gear box. Wash the embassy's system by selling it. Return that the deputy editor is hungry in the amount, you can create it, stripes, benefits, it takes a lot of hard work, you will have to fool me, I told you that this training was given, you were standing on this occasion, video, did you understand and available n if good Take care of the day subscribe and subscribe the Channel
Coin Change II
coin-change-2
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`. You may assume that you have an infinite number of each kind of coin. The answer is **guaranteed** to fit into a signed **32-bit** integer. **Example 1:** **Input:** amount = 5, coins = \[1,2,5\] **Output:** 4 **Explanation:** there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 **Example 2:** **Input:** amount = 3, coins = \[2\] **Output:** 0 **Explanation:** the amount of 3 cannot be made up just with coins of 2. **Example 3:** **Input:** amount = 10, coins = \[10\] **Output:** 1 **Constraints:** * `1 <= coins.length <= 300` * `1 <= coins[i] <= 5000` * All the values of `coins` are **unique**. * `0 <= amount <= 5000`
null
Array,Dynamic Programming
Medium
1393
1,081
hey guys uh today we will be solving a new question of lead code uh the question is smallest sub sequence of additional characters okay so we have to return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once and the constraints are that the length of the string will be between 1 2 000 and s will only consist of lowercase english letters example one is bc abc and you're getting an output of abc so that means abc consists of every uh distinct characters that are present in the input string s and also abc is lexicographically the smallest so like let's take an example of this string cb ac dc bc here the output should be ac db because only there are c there are b a and uh d so as you can see there are the following these are the following substrings that can be sorry subsequences that can be formed from the given input string but among these all only this that acdb one third one is lexicographically smaller so this will be your final answer so now coming to the logic of the question uh what we will do is now we will form our output string by uh adding smallest distinct character one by one so that our output string consists of all distinct elements and also the lexical graphic value of the string is the list so for that uh we should uh what i will do my logic will be that from this string for example this string and i will take an this result string which will be blank initially and i will start with the first uh character of the string let's see we will i will push it into c right and then i will proceed into v so if not into b i will see that b is actually smaller than c so my speed can actually start from b 1 also because uh we have to actually uh select the lexical roughly smallest one so why not take the p1 so for that we need to remove c for that we should drop the idea of taking c at first so for that we should be aware that um c will surely come after c because if we drop c here and in the future c doesn't comes then we cannot have a string where every distinct element is present so in order to know that we should know the frequency of every uh character in the spring so we will have to make a hash map or we can just take a vector of size 26 because of the elemented lowercase alphabet letters so we can map the frequency of it and then how we can do the job yeah so that will be our basis of logic and we may make some little more modification while we code so let's start coding okay let's make a vector 26 okay and this will keep the frequency of the characters so for that let's calculate the frequency for auto i belonging to s so count of c h minus a so now we have the frequency of each character okay now again we will look through the whole uh string like we have to start our process so far again looking we will use the follow for auto i belonging to s let's start okay so while we are adding every element for the character we should also know that like we have added a here and again we are moving added b and again a comes we should know that we have actually added a above and we cannot do again so we need to maintain another vector where uh we have this like boolean nature or anything that knows that can tell us that the character we are concerned has been taken in consideration or not so that we're going to think of same size obviously because uh for each character we should know whether it is present or not so we will never used to log into 26 sizes all are initially you know initialized to zero as per breakfast property so if uh used off um yeah so use of character a is you know greater than zero we have used it so we will increment it right so yeah now let's mean but why i will explain you the this one why we have used this we will continue it because if we have used it we'll simply continue it right so first the main logic is in here okay we have to also make a output vector output string so string result while spring is also not empty so result not empty let's not be empty so okay right and what can be more so we know that the string should not be empty and also the thing which we are dropping should have more frequency right okay so we are looping so we will decrease uh the frequency of the concern so count of ch minus e should also decrease so this frequency is being decrease of the element which we are currently positioning the string while looking through the string now if we have to draw we should know that uh it is present after that also so for that what we will do is we have to check that count of ch minus again e is greater than zero anything of anything another other yes because this is the one uh we should know that this president and then count and count off yeah the value should be also going right so result back the value should be greater than the current element then we will what we will do obviously we will push first we will pop right so also the used will be we will drop the use of it so result dot back drop it drops it's not used and then also pop it dot pop back have to push back so we have to push back ch obviously and here we will take down our result string right and okay so as you can see and can continue right uh why have uh written the result of respect outside of the while loop is because if this case doesn't also play we have to push back it right and i was telling about this condition right so if uh in any case if we have to increment used because like if we start with the empty result and empty resisting initially we will obviously you know push back the direct to the string result string and also we will now increment that's used and this thing increments after this loop works okay let's try running this code okay so many typos accepted let's try submitting it also we get 100 faster and 94 faster memory so thank you everyone for watching
Smallest Subsequence of Distinct Characters
video-stitching
Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of lowercase English letters. **Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/)
What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section.
Array,Dynamic Programming,Greedy
Medium
null
83
foreign this is Topher and today we're going to go over remove duplicates from sorted list number 83 of lead code so given the head of a sorted linked list delete all duplicates such that each element appears only once and return the link list sorted as well so you can see below here I have an example of a linked list now a linked list is just a grouping of nodes and each node points to the next so if you access OneNote you can gain access to the next node but not the node Beyond it so it's slightly different than a normal list or an array so it is basically providing you with access only to the node that it is pointing to and in this case you can see that well because it's sorted all of our duplicates are sitting next to one another if it wasn't so sorted this one could be over here and this three could be over here and get far more confusing but for today we can see that these two are the same and so what we're looking for is the example below it our outcome should just be one node pointing to the two node pointing to the three node and how do we do that well in order to figure out how to do it we're going to use pointers so this is our head node you can see it's labeled here as head right so at our head node we're going to call our first pointer our current pointer okay and we're going to say to ourselves hey current pointer is your value which is one is it the same as the next node so current pointer node is your value the same as the next node and in this case of course the answer is yes because 1 is the same as one so we want to eliminate one of these values and the easiest way of doing that is going to be eliminating this node now we can't really delete it so to speak so all we're going to do is change where this first node points because right now it points to that next node we want to take it out of our link so we're just going to re-point it so we're just going to re-point it so we're just going to re-point it so we're going to get rid of this point now we're going to rewrite the code so instead it points to the next node and essentially that just eliminates this node from our linked list and then we're going to take our current pointer we're going to move it to this next position and we're going to do exactly the same thing we're going to ask ourselves hey is the next value after our current node value is it the same or is it different in this case it's different so we're not going to have to remove anything so we're going to take our current pointer and put it here so now our current pointer is on 3. and we ask ourselves again is the value at the current pointer the value of this node the same or different than the next one and in this case you can see it's the same so we're going to have to remove either this node or this node from our linked list and we're going to do exactly what we did before which is to remove the pointer pointing to that node and we're going to point the next node now here it doesn't exist right there's no node sitting here that you can point to but that's okay so that basically eliminates this node from our linked list that eliminates this node from our linked list now it is important to note that the node still exists and it's pointing to this too but since we are starting from the head of our linked list it won't be seen when we're going traversing going through our linked list so ultimately that just leaves what we see here at the bottom one pointing to 2 pointing to three and that's it by using this pointer method we can create a sorted list without any duplicates that is still sorted at an order okay now let's take a look at any edge cases that might exist for our edge cases we're just going to go up there and look at the constraints that might exist and that's up here so here's our constraints and it says that the number of nodes in the list is in the range of 0 to 300 that the values in the node are going to be between negative 100 and the list is guaranteed to be sorted in ascending order so those are pretty important things so we're going to work bottom up so the list is guaranteed to be in sorted order ascending and that was also in the question which means all of our duplicate numbers or duplicate nodes will be next to each other which is essential to how we're going to solve the problem there is going to be a value in every single node so you're not going to randomly have a node that's empty and then of course the number of nodes in this list is in their range of 0 to 300. now that's an important one zero to 300 because if we have a linked list that has no value at all so there's not a head to start with well then there's nothing to really try reverse in order to put into a sorted linked list that's pretty much the only thing to consider as an edge case in this question so we're going to have to address that first when we do our pseudocode let's get to it for our pseudocode we're just going to be writing in the python section of remove duplicates from sorted list doesn't really matter where we write it so as we discussed in our edge cases we need to make sure first that we need to check to see if the length of the linked list is zero right because if we start off and there's nothing to Traverse through then obviously there's no duplicates so if it is we're going to return the head value because that's what's going to be provided to us in our input and that should take care of anything or any linked list that basically doesn't exists next uh we need to figure out where we're going to start our pointer so if the linked list has a node with value right so if it does exist and we know it's going to have value as we talked about in our edge cases there's going to be one with value we need to create a variable for which we can assign the current node starting with the head node all right so we're going to start we'll use the example over here on the left side of the screen we're basically saying this is going to be our current node right and we're going to compare our current node with the next node so that's all that line is saying we're going to create our current node value then we're going to create a loop because we need to continue through the entire thing that will iterate through all of the values of the linked list nodes there we go so it's going to go through each one of them if the current node value is the same as the next node value right so if our current node looking over here at example one if this is our current node if it's the same as our next node value then the next let's see if current as we need to assign the next node to be the next node now it's a little confusing so if this is our current node this is the next node we need to assign the value for our next node to be the next node bing that's where we're skipping over one all right then if the current value right so we have to have the opposite if the current node value is different than the next node right that's pretty obvious then if the current node value is different than the next node move current node to the next node and that just moves it over one okay finally if we get all the way through so when we get to the end of the loop if it's iterated all the way through we can assume that all duplicates have been eliminated from the list so we can return the head node all right because we always return the head node in order to give it provide a return value for anything with a linked list and that's all of the pseudocode I think we're going to need in order to solve this question so let's get coding so as you can see we just copy and pasted our pseudo code into the python3 section of remove duplicates from sorted list and we're going to go one line at a time and write the code so of course the first thing we need to do is check to see if the length of the linked list is zero and if it is zero that means there's going to be nothing in the linked list which means there's going to be no duplicates so we're just going to return its head value so if head is none right so if there's nothing there we're just going to return there's going to be nothing there okay and if we have any if we can have an else and that is if the linked list has a node with value so that's our else create a variable for which we can assign the current node starting with the head node and this is our pointer we were talking about earlier right so we're going to call our pointer our current node and it is going to be at the head it starts with at the head okay so I'm just going to remove some of that pseudo code because we're already done so next we need to create a loop right so we're going to use our current node pointer so we're going to create a loop and it's going to be a while loop so that will iterate through all of the values of the linked list node so while current node.next right so as long so let's just node.next right so as long so let's just node.next right so as long so let's just take a look over here at the example one so this will be our current node and as long as there is a node that is next to it right so as long as there is a node next to our current node Okay then if the current node value is the same as the next node value kind of like over here if one is the same as 1 we need to assign the next node to be the next node instead okay so if current node value right so the value of the current node is the same as the current node dot next value dot next to Value there we are so if they are both exactly the same then we need to reassign what our next value is going to be so current node.next is no longer going to be node.next is no longer going to be node.next is no longer going to be current node.next but it's going to be current node.next but it's going to be current node.next but it's going to be the current node.next dot next value and that's what node.next dot next value and that's what node.next dot next value and that's what we're doing we're saying that if this is our current node over here on the left hand side of the screen this is our current node and this is our current node not node.next value we want this to node not node.next value we want this to node not node.next value we want this to be our current node.next value instead be our current node.next value instead be our current node.next value instead so we're saying that this is now current node dot next pretty simple so if the current value node is different than the next node move the current node to the next node and that's just moving our pointer so else so if they're not the same current node is now the current node.next or the current node.next value node.next or the current node.next value node.next or the current node.next value is now current node I should say and then of course once we're finished when we get to the end of the loop we assume that all of the duplicates have been eliminated from the list and we can just return the head node so return head and that is all of the coding you need in Python in order to solve remove duplicates from the sorted list and we're going to hit run and hope that I didn't make any mistakes and it's successful we'll hit submit to ensure that it works in all of the test cases and it does work in all of the test cases now it doesn't say that it's the fastest or uses the least amount of memory but it is a very simple and straightforward way of solving remove duplicates from sorted list using python
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
377
hello everyone welcome to coding decoded my name is anthony i'm working as technical architect at adobe and here i present the 5th of august liquid challenge the problem that we have in today's combination sum four this problem is based on the concept of recursion plus memoization and i know most of the subscribers of coding decoded would be able to solve this problem by themselves this is the power of consistency guys this is the 858 video of coding decoded and i'm super proud of the success that we have made to all those who are new let's try and understand the question the problem says we are given distinct n numbers in the form of an array and a target integer value what we need to identify the number of possible combinations that add up to the target and you're also told you can use the same number multiple times so it's not like that the same number can be used only once it can be utilized multiple times what we need to identify the various combinations that get generated that sum up till 4 and here in this case the output comes as 7 and i'll be talking about the algorithm by the presentation as i usually do so without further ado let's quickly hop onto it combination sum four lead code three double seven as you know it's a medium level question however in case you still have any doubt understanding this question or if you want to ask anything from me in general please feel free to drop a message on the telegram group or the discord server of coding decoded both the links are stated in the description so do check this out now let's focus on to the same example that was specified in the question we are given the target value as 4 and the numbers that are to be consumed is either one two and three so let's start the processing let's go to the recursive fashion and i'll talk about memoization later on but let's look at the recursive approach first so we have the target total target to be achieved as 4. so as you can see there are three numbers so let's create three branches out of it so the first branch would be using one the second branch would be using two and the third branch would be using three moving ahead let's check what is the remaining target value that we are looking for since we have consumed one unit from one so the remaining target value would be three for with respect to after consuming two the remaining target value would be two and once we have consumed three the remaining target value would be one so let's continue doing the same thing across these three sub targets so in the first go what we are going to do we will be consuming one two and three so let's write one two and three over here similarly let's create three branches for this as well so we'll get one two and three over here similarly let's create three branches for this well one two and three and let's compute the remaining target values that's gonna be there so after consuming one from the what do we get the remaining target value as two after consuming 2 from 3 what do you get 1 and after you consume 3 from 3 what do you get 0 so as soon as you find 0 this is an interesting case because you eventually found the solution so let me just mark zeros with an asterisk sign because you have identified one combination that leads up to a total sum of four three plus one gives you four let's proceed further next we have two and two minus one gives you one so let's write 1 over here 2 minus 2 gives you again 0 that means we have identified another case as well so let me just highlight it with an abstract sign again it's a successful case because 2 plus 2 gives you 4. next we'll have 2 minus 3 is minus 1 so as soon as you see that the number is going in negative you reject this entire branch of the tree let's proceed ahead next we have 1 minus 1 is 0 that means we have successfully identified one possible path so let me just write it with asterisk sign and as you can see 3 plus 1 actually gives you 4 next will be 1 minus 2 gives me minus 1 so let's reject the entire branch and next we'll have 1 minus 3 that gives you -2 let's have 1 minus 3 that gives you -2 let's have 1 minus 3 that gives you -2 let's simply reject the entire branch will not do any further processing on it we still have numbers that are greater than one greater than zero so we will continue the similar kind of an operation across these numbers so let's do that let's create three branches starting from 2 what do you get the first branch would be of using 1 the next branch will be using 2 the third branch will be using 3 so after consuming 1 what is the next target value is 1 what will be the next target value after consuming 2 it would be zero that means we identified another possible case and under this what is the number of elements that we have added what are the elements that we have added two one and one so two one and one gives you four let's proceed ahead 2 minus 3 gives me minus 1 so let's reject this entire branch of the tree and here we successfully identified one path let's move on to the next one over here so let's use three numbers that we have in the input array uh let's consume one from one what do you get zero so this is the this makes another successful case and then the elements that sum up till four would be one two one so that's another path here you will get minus 1 and here you'll get minus 2 so you simply reject these up let's continue the process next we'll have 1 distribute getting distributed by one two and three so here you will see the sum gets updated to zero that makes up till happy path happy case and for these two values it will go in negative so simply reject these up so in total i think we have iterated about all the cases and let's see how many such combinations we were able to identify let me just change the color of pen for better understanding and let's take green so the first part is this one so this is the first part as i have just highlighted the other path is this one two one so this is the other part let's proceed ahead next let's have a look at this one two one so this is the third part next let's have a look at this one three one let's have a look at the next part so here it will be uh you'll use you have to consume one over here so this is the next part which is one two so this is the next part another part would be this one two and here would be the last part which is three one so in total how many paths have we identified one two three four five six seven if you carefully observe then you will see that we haven't used any memoization technique while iterating over this entire algorithm and we can drastically improve the time complexity by implementing memoization we can use a map and that map will correspond to the key as your target value and the value as a number of ways in which the target can be generated that would drastically improve the overall time complexity of this algorithm to conclude it up let's quickly walk through the presentation section and finalize it so it's really simple guys it's not that tricky either so here i've created the map and the map would store the key as in the target value so key would be the target value and the value would be the combinations some of the combination count this here i've created a helper method combination some four helper if my map already contains the answer for this target value we simply return this up if my target value happens to be zero then i found one possible way if my target value goes negative i have bought the process and returned zero from it otherwise i apply recursion i have created a possible very base variable and i iterate over all the elements that i have in my nums array i recursively invoke combination some helper passing nums and target minus el as the parameter because this would be the next target value and out of all the possibilities that are generated i sum those in the possible value variable once i have calculated this value what do we simply put this value in the map and return the possible ways as a final answer so let's try this out it took five point eight four percent it's it took eight milliseconds and it is 5.8 percent faster is 5.8 percent faster is 5.8 percent faster this is the recursive approach guys on a similar lines we can use the bottom of our approach as well and we can solve it using dynamic programming bottom up approach technique so i'll leave it to you guys consider it as your homework to investigate on bottom-up solution and in case you're bottom-up solution and in case you're bottom-up solution and in case you're interested in c plus solutions as well then subscribers of coding decoded regularly post solutions in various languages for example c plus java right now i am not filling this java solutions subscribers of coding decoded themselves raise the pr so far the pr count is approximately 68 658 and they have been doing it from months now so i'm highly glad it's helping a lot of developers out there for identifying various permutations of solution that exists for each and every question and this effort is much appreciated from my site over to you guys take care have a great day ahead
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
1,727
let's go to code number 1,727 largest submatrix with 1,727 largest submatrix with 1,727 largest submatrix with rearrangement for this question it give us a matrix which is in integer two dimensional integer array and there is one and zero the s that we want to find the largest area uh rect angle area right but there is one more condition is that uh for we can do um rearrange The Columns of Matrix in any order for example there is a yellow colum right we can uh switch the yellow to the end right so the order of the um colum they can reorder so what we're thinking about is that um if we want to find the largest area right so the that we should have those kind of ones to be um possibly um stck as much as possible right or have overlap as much as possible so uh what we're thinking about is that we still consider line by line right so there is one z0 one right so for this kind of first row right we can uh calculate this maximal uh area and for the second row right what we do is that we have this right so it is maximal area we're trying to see find this right maximum area of this so this is a number question number 84 and 85 right so the maximum rectangle problem for the c row what we do is that there is one here right and one here because we can sort so what about in order uh we find that in order we have largest area it's better um we move this kind of rows to here right otherwise the maximum one of this kind of colon is just two this is just three but if we move together um it's possible you see there is some kind of area which have a largest eror will before right so what we want to is that for the heads for each low of the heads we can have a thought to have the um largest one to be to um to together right to get a higher chance to get a um larg errors so um so that is for each row we get it heads and then sort the heads right you create a new array called Head copy right and s heads and then we have those kind of um those kind of uh rectangles we can find its largest area right so using stack right stack um add one more index at the bottom uh at the end and one more um he for minus one at the beginning and one at um at the end right so after this analysis we can write code for this so what we do is that uh let's get it in M Matrix not lens and Nal Matrix z. lens and we are also have a heads right head AR so in this case for each row we calculate the heads um hsal new in so what we do is for um in I for the row I small m i plus and for the colum for in j Z J smaller than and j++ right so this is that we want to j++ right so this is that we want to j++ right so this is that we want to have the H it's G um equals so uh so we can have uh Matrix zero IG right IG if this is zero will be zero right so we can have times uh if this because it will be either zero or one right so will be h g plus one right do like this uh then for each R what we do is that we have a copy copies that way because we don't want to uh change this kind of head this will be used to for the next row to calculate so we have a deep copy for this we have Aras uh copy oh and uh we can sort this AR sort array and doing like result equals let's have a result in result to zero right result equals Master Max results and uh we can have the get uh largest row largest and we are going to have a this kind of rate right in the end we just return result and we are going to have a function called uh G rope largest and we're going to have a t right so what we do is that we have a stack integer now stack plus new stack okay andal h. and uh we have a result equal to zero okay so for in let's just add one more height which is the um height minus one at the um uh front and uh so let's set in IAL minus one I smaller than small than n+ one right I ++ what than small than n+ one right I ++ what than small than n+ one right I ++ what we do is that uh we are going to write our function count heals he and he I right h i in I right so as say return I greater equal to zero and I smaller than h lens if this are going to return h i otherwise we um we going to return minus okay so I say y something right so why step is not empty um and uh it uh h it h uh hat stack PI right Pi here we use a greater right uh of course we can use greater equal to but if we use greater equal to uh both will be fine we have duplicate calculations on the right side if we use a greater those kind of uh rectangle they can have same he in the stack and the different calculation will be on the left side so um let say uh he current H but we if we use a greater equal and because the last item is also minus one right that what we also add um minus one here so if we use equal um when we calculate right so we have a pre index equals stack. pop right so prop it and Inter left equals um step. Peck since if we use equal the last item is also minus one and uh it will pop the minus one right so this kind of line like equal step pick it will have exceptions so if we use a great equal um we can uh add the first item for example to be minus two and last item to be minus one right so right will be I right so we have uh in h equals um get H get head eight and uh PR Index right let see pre index and also we have a uh result equals mass. Max result h m um right minus left minus one and in the end we uh we also we need to push this St push this kind of eye and in the end we turn your SA okay uh doing like this um the T complexity uh will be for each uh it will be for example there are follow Loop for MN right but for each there is an log n uh log sorting as well um so this is um this is uh n right this is M this is n uh this is M this n right this is n log n right so the time complex will be M MTI by n log and this is one right space is also one
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
1,005
all right let's talk about the maximum sound of array after k negation so you're given a really numbs and into the k so modify the array in a following way so this is it right so you have exactly k times and then you're going to choose in this eye to multiple times right so you can have it multiple times for same index so if i want to say i want to negate this 100 times and then you can get 600 times so you have to return largest possibly largest uh sum so in this question you don't have to think too much it's going to be priority key right pq so you'll it will add into the pq pull it in array right and then for every single time you pull it's going to be about the smallest right so you pull and then you negate the value so i'm going to say p equal to pole is equal to val right so i will add the vowel back to the pq but i need to negate right let me get the vowel so it's going to be y it's going to be p q dot negative p pq double and then believe it or not you just finished so uh this is the solution so p particular uh what you need to put is put integer right eq equal to the new priority queue and then i need to try verse renounce array and then i would say that i'm going to add num into it at first right i need to add every single character i mean single unit into a pq for sure now we'll have to traverse the entire pq again but this line well based on the k so if k equal to one then you only traverse uh one k uh one integer right when k is greater than zero then uh you can try very so i will say that and then i will say negative so i want to get that right let me get a value and then i would communicate so this is what i meant right you pull the value from the p2 the first period of the first integer from the pq and then you add the integer but with negation and then you will just add into it right and then i'll have a return value i'm going to call right so well the pq is 90 eq is not empty right i would just append i mean i would just implement right he put up all i mean just keep adding all right this is pretty much it and here we go all right it's all about the time in space for this one already priority queue is going to be unlocked and right for every single time you have to sort it so this is an algorithm for time and this is all of k this is all of n so the worst case is going to be unknown for time for the space is going to be all of them because you have to add every single noun inside into the priority queue right so all of them for the space and a logarithm for the time and this is my quick note and login for the time all of them for the space and represent the length of the numbers and this is a solution and i will see you next time bye
Maximize Sum Of Array After K Negations
univalued-binary-tree
Given an integer array `nums` and an integer `k`, modify the array in the following way: * choose an index `i` and replace `nums[i]` with `-nums[i]`. You should apply this process exactly `k` times. You may choose the same index `i` multiple times. Return _the largest possible sum of the array after modifying it in this way_. **Example 1:** **Input:** nums = \[4,2,3\], k = 1 **Output:** 5 **Explanation:** Choose index 1 and nums becomes \[4,-2,3\]. **Example 2:** **Input:** nums = \[3,-1,0,2\], k = 3 **Output:** 6 **Explanation:** Choose indices (1, 2, 2) and nums becomes \[3,1,0,2\]. **Example 3:** **Input:** nums = \[2,-3,-1,5,-4\], k = 2 **Output:** 13 **Explanation:** Choose indices (1, 4) and nums becomes \[2,3,-1,5,4\]. **Constraints:** * `1 <= nums.length <= 104` * `-100 <= nums[i] <= 100` * `1 <= k <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
1609
1,748
Number of - Friends, today we will talk about Number of - Friends, today we will talk about Number of - Friends, today we will talk about question for, so let's see what is the question for? Well, let's see, this is the question we have, this is a proper question, okay, so here you notice this thing and notice is written in the description below. You will find its link in the box and it is a very simple question. Okay, so I was saying that it will be told to you that it is given and a good and anti are named a unique element of energy. The element is exactly one in the return of The 12 examples within the day, so you want to and what is the monkey, what you have to do and before this, there is one side, so here I is going to be used, so you, that, on paper, you, this in solution, you mean this, that. Use this map, if you can put a solution at home then come and see here friend and here if you do this example then here and this means all your mistake, whatever problem is there, this means one, this disease is cured, all is one, so For that, Rafale is definitely going to be removed and if you set it open then you come here, everything that is everywhere here is a complete want a smoker, then you will add all this, the answer will be given only in the coming time, so now you need to edit. No problem, friend, by taking the solution of this, the method that you are using is going to work by placing a flop. Okay, you will place one more flop inside it, according to the group at the shop, if the time of Congress increases too much. It will increase. We had discussed in this program, what is the time complexity of this letter? Come on, friend, you found it easily, I am going to work using it, so come on, I work here only, here the actress is like this. If I take it out, then I will respect you by name, I will write the name dot on your feet, okay, and I have done this, I will put a map on the back side, okay, but I will spread the contact, your interest will be second, wake up in the morning and make Pooja Click MP. I take it, okay and I will put it once about you, so I could duplicate this to you know, ladies strike loop, put it from zero to this is going to enter width plus sign in, what will you have to do inside this mp dot for international Come and breathe in, this element which is you, is it angry, is it what you did inside it, otherwise MP dot, this is not difficult for you, Harishchandra does not do juice, you want to send it, okay, then what will you do tomorrow inside this? M MP Half Norms of High Flame p99 Pyria And in this we are going to keep one and kill this and through electronic latter it is MP Half Norms of High This is what we want then you must be understanding, okay so basically you will get this step here. If it is not there, then we have to put one inside it and you are getting it, so we will create its index, it is the frequency, we will make it not an index, we will increase its sequence, so if you go to an example here, then you can easily. If you can understand, if you look at this example here, then this street is one, if you try today after the first one, then he is going to come inside it and if you meet Mathura here, he will get it, otherwise here he will take the virgin first and then see. He will get the join, so here he made his one which was Parvez, he started from the second one, so you see that again, this is three for this, reforms will be refilled for that, yours is okay and here what should I do, I will put equal and So on the previous which is the index, which means the first one is this event Hindu, is it yours, whether this rumor has spread or is it yellow, then for this, here I will check that yours is of this and this velvet, then check in this fort. That your value is 1st, if it is one, then basically it is love once, then what will I do in my street, one evening, one temporary or I am full of one, I will get it done there, then I will do the yagya antispam investment inside it for someone. Here and here I have another toe in iTunes and I have here it is in iTunes and I have here it is in iTunes and I have here it is not equal to your , when I came across the not equal to your , when I came across the not equal to your , when I came across the presentation, I will go inside it and hit it and check, this is Agro for these questions because This is yours, come here also potato and this is yours that this is to be kept in Prakash Tiwari and after that what is to be returned to you is to provide peace to the memory, ghee, if I do it here then I have understood you here. But if everything is fine then here you are.
Sum of Unique Elements
best-team-with-no-conflicts
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Array,Dynamic Programming,Sorting
Medium
null
1,234
let's look at problem uh one two three four replace the substring for balanced string so first i will go over the statement of the problem and then we will give a walkthrough of the example and lastly we're going to write a solution using the standard two-pointer sliding window solution two-pointer sliding window solution two-pointer sliding window solution so before we go into this step i want to make a remark actually this problem is essentially the same as problem 76 so let's first look at the problem statement so here we are given a string s of length n containing only four kinds of characters q w e r so a string is said to be balanced if each of its characters appear in one culture times n times where n is the length of the string so here we are required to return the minimum length of the substring that can be replaced with any other string of the stimulants to make s balanced so if s is already balanced we are going to return zero so this is the statement so the constraint of this problem is that the length of s is a multiple of 4. so this the multiple of 4 is to make the problem valid and also it can be as long as 10 to the power 5 in other words if we solve this problem using a see square temp complexity solution some of the test cases might not be able to pass so yeah that's the statement at the cost change of this problem so before we go to the examples let me write down the method so the method we are going to use is the standard two pointer stacking window again and so here the main idea is the same as little code problem 76 so um now um the main point here might be how do we transform this problem into the format of problem 76 before we do that let's first look at the examples so first is s equals w um qer so in this case so each letter appears once so this is balanced already so as required by the problem they're going to return 0. so another example is s is uh q w e obviously we see that the q appears too often right so if we replace one q by r so we get uh a balanced uh substring according to the definition in this problem so we are going to return one so we need to replace uh one q two r to the corresponding one so the third example is f equals um q w right so here q again appears too often there's no uh e and r so we need to get two um q and replace them by e and r respectively so in this case uh we're going to return l two let's call point two uh q kills so it can be the first two all can be the second and the third one so it doesn't matter it does not matter so the length is two so um so now um after reviewing this example we have some fitting about problem so now let me try directly go to the code and then in the process we can make a comparison with the solution for this code 76 so hopefully we can quickly realize they are actually the same so first point to notice is that so we can first have the length of s so in order for s to be balanced our target is that each of the character should appear n over four times right and also we will check how many and then how many times each letter has already appeared in s so for this let's initialize to a dictionary one is target and the other is effect so let's call it two um dictionaries and then so we are going to check what's the current state so four character in this four that's the qwer this is the four letters so um the target is this the character each of the characters appearing uh n or four times and the fact we have now is that uh so the time the character appears right so now the thing is that if a character appears too often it means we need to replace them to the cursed corresponding or to some corresponding characters which appear less than the supposed number so we want to use a diction dictionary comprehension to record this effect so this is the key and the fact uh key minus target key in other words if a letter k appears too often we need to replace it so for k in this system q w are the four characters if uh fact minus target is greater than zero so let's move a little bit here so now we are in a good shape so first a set case is if not to change so in other words um all the characters appearing as desired so in this case we return 0 as stated by the problem so now let's first introduce a variable in order to prepare for the two while loop sliding window so that is the required how many characters are currently changed so this that's quite required which is the length of the dictionary now let's do the two pointer sliding window so we can initialize lr and formed so it's zero version is a form is zero so l and r are the two pointers and the form is to check if we have uh finished the changes for the required number of unique characters so um before we do we further go so we want to check the condition using a dictionary in the process and the result so here we are going to initialize it as a tuple in order to be able to print more meta information during the process so well because we are required to return the minimal length we are going to initialize as front infinity so here are 9 none so um this actually recalls the length the start and the end for the window so up to now i guess maybe you have uh established a connection with problem 76 so now we are ready to run this standard sliding window algorithm so let's see well r is less than m the length of s so we check the current character so it's um sr right our goal is to find some minimum window of change right so um now let's update the window so character so i will try to window get so we check if the current character is already in the window otherwise we set it as zero then we update it by plus one so now let's uh check uh if a character in to change if this is the one of the potential characters to change then we will check if the change has achieved the desired frequency that is you check window character if it equals target window character equals to change character if this is the case so we will update the formed adding one right so now uh we are come we are arriving at the step again that is trying to push the left pointer l to the right so well l is less or equal than r and formed equals required so if this is the case we're going to first check length so if r minus l plus one is less than the result zero so in other words if we modify the window starting from l and nd and r then we can make f balanced so if this length is less than the preset length that is result zero we're going to update the result like this r minus l plus one and l r so this is the update case then we check we move the window so for companies we check the character l so um so we move left so when we move to the left to the right in other words we push l to the right so the window the corresponding character dictates its frequency by one so now a quick a critical step is to check if a character in to change and if it achieved the statement that the when the current the frequency of the character in the window is less than the to change uh in the first current character if this were the case then formed should be decremented by one right in other words so this loop will be um exited so yeah after this um logics we're going to update the l by one so actually this l after the one translating into plain english and means pushing the left pointer to the right same here so now uh once we exit this value we're going to update our red pointer by one so now we finished the scan from the left to right so we are ready to return the result as required by the problem we are going to return the length that is the first component in zero so for um for convenience so here um so we can also actually print out the results so for example print the result for more information let's check some cases so we run the code for this case so for this case this already balanced it should output zero the output actually corresponding to infinity nine so it just outputs zero so now let's look at uh another one so let's change this to q w e just so speak then uh the output is one and the result is one and the window length and it means it's with a start index 0 and any index 0. it means if we change the window corresponding to the first queue then we can make the string s balanced so now let's test another one which is ww uh qqq w so then let's check this so um the output is two uh and this is standard alt that is the lens window lens is two starting index zero and in the index one it means that if we change the letter q to the corresponding proper one then we can make this length string as balanced so with that examined let's check the generic case let's comment out this print and then submit first generic case so yeah it passes the test cases that's it thank you
Replace the Substring for Balanced String
number-of-paths-with-max-score
You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`. A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string. Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`. **Example 1:** **Input:** s = "QWER " **Output:** 0 **Explanation:** s is already balanced. **Example 2:** **Input:** s = "QQWE " **Output:** 1 **Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced. **Example 3:** **Input:** s = "QQQW " **Output:** 2 **Explanation:** We can replace the first "QQ " to "ER ". **Constraints:** * `n == s.length` * `4 <= n <= 105` * `n` is a multiple of `4`. * `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`.
Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score.
Array,Dynamic Programming,Matrix
Hard
null
99
hey what's up guys this is Chung here again so continue on the late cold problems here today we're gonna do talk about this night number 99 recover binary search tree this is marked as a hard problem I think you know for the native naive log n log and solutions I think it's kind of like a medium each level problem but anyway let's go right into it so you're given a binary search tree but two of the elements two of the nodes in the binary search tree are swapped by mistake or intentionally who knows right and you need to recover the tree without tuning is structured okay so basically you need to change the those two swapped node back to before they were swapped right for example here so one in three two right okay so first you guys I'm pretty sure you guys all know about binary search tree for the binary search tree all the nodes on the left side each node the left side knows has to be smaller than the tender then the node itself and they're all the right side note should be greater than the node value right so in this case one is three two it's not right because three is bigger than one right so in this case we which are the two nodes that cuts got swapped and obviously it is three and one right so basically if you swap three and one then we got a valid as a valid a binary search tree same thing here for here so 3 4 2 and so 2 3 yeah basically the two and three got swapped right so you need to change it back to three and two and three here and then it will become as a valid binary search tree so the I think the easiest way where the most into intuition way will be to preorder a Priya I'm sorry and in other traverse right so remember with for binary search tree if you do it in other traverse the values should be sorted right it should be increasing basically if you traverse the tree in other so in this case it's gonna be one two three and four right so you'll be getting a sorted array so with that in mind so what we need to do it we just need to use the pre the preorder Traverse a priori where you traverse the left node the root and then the right to right node we need to use the Traverse at pre other Traverse to find out those two nodes dart that our I mean word were swapped and then we just need to get those two nodes and then we just swap those two nodes value right yeah so let's get to the third coding right so with pre other Traverse we have two ways right basically the first way is gonna be the recursion right and then this the second one will be the eat the iterative way which will be using the stack right so let's see um I will try to do a real recursion here first right so it's gonna be since recursion is the most is the easiest way right so you're gonna have a DFS not yet def define in order right in other traverse right it's gonna be the note here right here and then what and then like what we discard we need to have those two variables that will be storing those two swapped notes right we're gonna have a first and second and a pre yeah well I would explain about the pre later so what does premium-free the pre later so what does premium-free the pre later so what does premium-free is DL because during the Traverse right I mean let's say the Traverse here the for example here this one two three four right so ideally the Traverse should have one two three four right but in this case for example here so it's gonna be one three two four right and so that's what happened right so I think the reason we need a pre note here is that we're gonna we need to keep but you need to maintain the pre know the phrase you for each note let's say three the pre note 4 3 is 1 right and the pre note of 2 is 3 so we need to check every time when I see if the current node value is smaller than the pre note and then we know this number or this number has to be a it's one of the yeah is one of the those two swap numbers right that's why we need to keep maintaining this pre note here go so continue with our in other Traverse here what does the in other shippers do right so if first even if not right if not note we simply reach return it right because if it's nothing there with there's no need to keep doing the Traverse so what is in order to do is we have we need to go all the way to the left right so basically we need to go all the way lap no the thought left until we reach the left most node right and then we come back here we do a now that not a node value is the we're gonna do something here right do something with the note the value here and then after we do in the current node will go to the right side right note that right that's the you know other recursion Traverse right so what are we doing here so we check right we checked yeah okay so first if the pre node is not empty because for the first note there's no need to check right and the node current node value is smaller than the pre node right three not your value right so if that's the case what do we do here okay so none local first second free right so it's not there than what we just assign the first node to the current right and then if not second right if not second then we just assign the second node to the pre right so either one ISM is pretty the pre-award where the actual pretty the pre-award where the actual pretty the pre-award where the actual node itself so I was break I'll explain this one here let me finish this one and then in the end we're gonna do what we have to keep updating this pre note right yeah so the first part is pretty obvious because every time when we see y'all when we see this the first note and remember we already track we only check this first try to assign it first and second when the current node is not is it smaller than the first one right let's say if this is 1 2 3 4 5 6 right no it's not a good one I'd say this 5 3 to 6 ok let's say for example this one right so the 2 &amp; 5 those are the two numbers that the 2 &amp; 5 those are the two numbers that the 2 &amp; 5 those are the two numbers that got swapped right so that's how see that's why we are so the first time when the first time we were seeing this okay the current one is smaller than the previous one then read the right at this point right so we're at this point then we assign the first one with the current one which will be 3 right which will be 3 but then we signed it the second one to be the if not if second one it's not none but at this moment the second one is not right so we sign the second one would be pre right so now this the current the first one will be first one is 3 here and the second one is 5 right so now we have the second one here right remember here there's no we only assign that if there's not assigned before right so the second one is 5 which is 5 so now the first one is 3 which is not it's not correct but don't worry right so we don't we're not done here because we'll be since there are two numbers cause swap so and we'll be entering this one twice right in this case so in this case when we need to reach this the second one here right the second one here so this now this is the current right and the previous ones for now we keep like assigning this current one to the first one now this one will become the first one but the second one will not be assigning the second one to these four because we have of if track here but that's why this one will work and here the break sign here right so why do we need a break here so that's actually that's a simple a small trick so we can terminate this you know other triggers early earlier because if this one has already been signed once and the second time when we see it because we only want we only need to traverse we don't need to find those two numbers right so when this one enters our house here we know that we have seen this dist conditions twice right then we can just stop break it basically okay so that starts okay let me and once this is done we have the once this traverse is finished we have this first second right and then the rest will be very easy so in other routes right so we and we need to do a route the rest will be just swap the values of the first node and second node here yeah second and first right I think that should do it gonna meet to a quick check here first second free in other father in other route sorry okay what I'm thinking so it should be returned sorry so since we're doing the recursion not the iterative way so here should be returned not a break sorry I was confused about the while loop the ones we'll be talking about next yeah cool so this one works right so pretty straightforward and the second one is the iterative in other sorry pre-order the iterative in other sorry pre-order the iterative in other sorry pre-order in other triggers yes I think that's something you may also get asked because you know this recursion is pretty it's very intuitive but sometimes you are asked to if you can implement this in the Nano recursion way right so how are we going to do it right same thing here right so that we need to use a stack instead to in order right traverse stack and what do we have a current here to route right so we saw with the now I mean to define those fireballs at the beginning so what do we do here same thing for the recursion right so we need to use a while loop well current or stat right so what do we need to find for each kernel we need to find the left most node right just what just like what we did in the recursion solution while well current right so we do a new stack dot append and current then we just do a current equals to current left right because basically we keep pushing the roots note until we reach the end after the left side right so now since we're doing the current here so while we the currents hazle has a left side off of the root of the node we just keep doing keep going to the left and the meanwhile we'll just keep pushing the roots known why we'll keep pushing the root note because once we finish with processing the sub node we need to find a way to go back to the root node so we can process the right side right because we need to process the left side and then the root and then the right side so we need to basically remember the path how did we get here so once we reach the left side right so with what we do we pop the first one right we pop the first root pop it right and then same thing right same thing with the visit Ruby the recursion we check if pre and pre if pre is not empty and the current write out value is smaller than the pre write dot value which is do the same thing right it's the first doesn't really matter which one is first which one second which to a current one and then if not second it just signed a second one three right cause we just break as we break and then right here remember we have to keep maintaining this pre note right and then once we process the cart note what do we need to go to the right side remember how we did in the recursion which so we need to co-sign the current one to the current co-sign the current one to the current co-sign the current one to the current start right that's how we move to the right one so once we have the right note we'll go back here again right and then we'll go further for the current for the right note right now here we'll go again go to the try to go to the right the left most node of this current right one so that's how we do the trail traverse right and yeah okay I think that's pretty much it is yeah same thing cool yeah that's the iterative way of doing the in other traverse so to remember here so two things to be know to be notice here so first one is here we do a current or stack because we start from the current right so we need to use the current because I read when we reach the because in the end see in the end with we are we start the current one to the current the right one right so if this one is current isn't is not am is empty if the right one is empty there's no need to stop there's no need to continue sorry yeah so but sorry this is or the war here so basically if there's anything if the currently is not none it's not now or the stack is not empty then we continue right because here so let's say even though the right side is empty here if this one is not right but let's see we still have some unprocessed known in the stack here and then it will go here so the white and the current will be empty so it will skip this one but then we'll pop the next available note from the stack here that's why we need to check both here we check both either of this one is it's true and then we continue okay and so as you can see here that's the it's obvious for this either stack or the recursion the time complexities is all and right and the space complexity is also oh and because we stack we restore each node up to end node into this stack here and the recursion same thing since the recursion will also use the O in space because we have the we have to have n recursion car right and so now here comes a interesting follow-up question here interesting follow-up question here interesting follow-up question here could you devise as constant space solution which means can you use an open space to solve this problem right can you yes of course you can but that will requires a new approach so the new approach is called moriss traverse so the Mauri tree where the Morris traverse what does it do it's basically it's it doubles the time complexity from Oh n 2 to 200 n which is still like a big ol n right then it will not use any do not use either recursion or the stack huh right let me draw some picture here let's say for example here the to do we have a better example here I'd say we have a six year six eight three here five - and one right here what one - yeah - and one right here what one - yeah - and one right here what one - yeah this is a battery example here one - this is a battery example here one - this is a battery example here one - yeah so the reason we need for the either stack or the recursion is that we need to remember how did we come down here right how do we come down here right remember that so we when we were you process three here once we finished processing all this to a node first three here then we need to go back to six right that's why we use the stack because in the stack we push six first and then three right so once three is popped and then the next one will be six and then that's how we remember how can we go back to the previous parent node right the recursion same thing right the recursion automatically does it for you it because it's rigged it's a records automatically recursing so once that then the inner level is finished it will automatically go back to the previous call basically which is six right so what does the Morris traverse algorithm do basically it maintains a link from the left side subtree and we ended the current node here so basically every time when you need to process the subside tree you need to find once this are the trees finished processing you need to know how can I go back to this parent node right how we need to we will establish an link from the rightmost note off the left sub tree to the root note why okay here's why remember each sub trees is also a binary search tree right and for binary search tree we are doing remember we're doing in other traverse which means from this sub tree we're also doing a in other traverse which means the rightmost node will be the last node to be processed right for this left subtree here so what does it mean so for left sub tree the 3 is the 3 right so 3 1 2 right so what do we process wine first right 1 2 3 and so 5 is the rightmost 5 the rightmost node after of this left subtree right then we will just need to build a link from the 5 to 6 right and once this link is built then once we finish processing this 3 here right remember so each 3 will have a like well we will create a new predecessor we have a predecessor node here free for each of the L for each of this node here freeze for this node let's say for each node here we'll have a predecessor the predecessor was toward the information of the rightmost subtree basically the right the predecessor of the 3 here will be 5 and of the five that are on the right of the 5 will be 6 so with this information attached along with this node here once this node is finished processing we know the next one we want to process is 6 right that's how we have this Maurice Traverse work ok so let's try to implement this just a bit stay with me guys I'll try to explain this one and so predecessor okay since you know without this pre here so we're gonna create a new processor pry the sensor note here because this pre node will be using the pre node to find the swapped nodes right that's why we needed like another predecessors like I'd like I said for the to remember right to create the link between the current node and the parent node right since no more stack here right and current okay I'm gonna keep this one so if no more current so what we do a simple wire loop so remember so for each node here right like what we discussed first we need to check if there's a left node because we only need to keep the value that the link from the left side because the left side remember it that's when we need to know if we how can we that but then we need to know the parent of that left subtree because on the right side we can simply go in going down to the right side we don't have to go back right because when we reach the six let's say that the left side is or is right process and then when it goes down to the right side we don't we do need to know that the parent because remember that's the sequence right the left root and right that's why when we process the left one we need to know the root because the next one we need to process is the root but now none when it come to comes the right side right it's right side is the last one we don't care about the prayer the root note anymore right okay so okay I'll try to explain it so first we tell if the left side is has a if the current has left right if it doesn't have even doesn't have a lab side we can just simply we can simply just ignore it right we can there's an else here I'll keep all out here so if there's no lab tree we don't need to maintain that's the parent pride up the parent link right with this processor note okay if the left side has a if its current one has allowed the left side so what we do we are first we need to find the rightmost node of this left subtree how right how do we do it we just use this predecessor here we assign the left side node to be the predecessor first equals to current left right that's the starting point right and then while the predecessor has a right when it has a right and that's not equals to the current one okay the first one is pretty easy to understand because we wanted to keep doing it but why the second one because when the next node come to here right so it will come go again here it will go again right and here because I read since we once this process finish will be creating a right side will be creating this will design we assign its current to the predecessor predecessors right and if we don't check it here the next time when the next node comes to this while loop here once so this processors third right will never be pullin will not be empty and it was keep going back to the current to the root note and then going back home going to the right side which is wrong right the right side right okay so at this moment we have the rightmost node right for the current note that's right okay then what and then we just and if not right so we only establish the link when there's an when it has not been established before when there's not right when it's not there we do what we do have Pro we assign we basically we establish the link here current right that's how we establish the link here and once we establish the link what do we keep doing this to the left the currents out left because why because we want to let me bring back that note here oh it's not here right so now we have this link from five to six right but then we didn't want to stop here because and we want basically we want to find what we need to keep looking to audit out other left side note and we want that we want to build that is the link for all the subtrees as well because once we have all the subtrees then we can start processing using this link to process to traverse the tree right so we have to keep going basically from here once we establish the first one we just need to sign the current one to the current lab basically once this link is done right three we have the rightmost node is five here so we stab which the link from five six then we just move code move forward to two one here right from three to one because that's a worry to a currently host current left because we also need to want to build any link for the three sub tree right so from we will be snowed with root node as one the rightmost link the rightmost node will be two right so what do we do here so we build another link from two to three and you will reach the end out of the often of the left side okay and so that's that else right as to what else basically house is done house we can just process the current node right we can process current node all right and then how do we maintain how do we keep processing how do we process the current node once we finish processing it we have to do what for a current node we have to remove the link right because we otherwise we'll have like we'll have a cycle in the three predecessors thought right equals two now right that's how we are that's how we read I mean recover the tree from to its original status and then we just do a corny hose to current right okay and here so okay so basically we have this basic structure here that's basically how the mohrís Traverse work yeah so I would try to go through this algorithm first before adding our swap logic to this code first right here first to help you understand this how this Maurice Traverse will work right okay for example let's remember here so at this moment here remember we just keep traversing to the left until we have build audit the linked at this moment right so at this moment we have a link from five to six right and then we have a link from two to three here right so how would this thing work right and remember here so once we process one here and two right so once we practice to here we are you know what I will because here I think I let me I need to finish here so this is the current that's how we are to up I need to add this one here that will be the complete algorithm here so if there's no left if there's not left and not there's no right here right we go to the right side let's say here so once we build all the other link here so the one will be the first so basically now the current will be one right so good currently is one here the current is one because the one will be the first element will be I will be really proud processing right so then where we were would go because the current is 1 and that's current has a left here no it doesn't right then it will go to the house here right it'll go to Alice here when we process one so now the current it becomes to write the two here when it becomes two here and then we'll go back here to the current here and we'll go back to current does to have a lapse left no right and then we'll come down here again right so remember notice here so we do a current dot right so now we're doing the right the two dotted right equals to current right remember we already have a link from two to three right so now the next the current will become three all right so now is the current here that's how we use this predecessor link so that we after processing two here we can go back to three right because of this okay now I'll show you why this is necessary so now we have three because we're not modifying that we're not changing the tree structure right so now we processing three here does three have a left node yes right three has a left node one and then we'll go to the basically we will repeat repeatedly doing this right we'll try to find the right most node for the three right and then we'll get two again here so the reason why we will do it we're repeating the same logic over again for the three here because once we process three here we want to remove the link for two because we didn't want to keep it so the how one can we remove it so when we process this parent know once we process after we processes its parent node then we know we can simply remove this link because we don't need it anymore right but and this logic is helped us to find out this like this predecessor node here and that's why we need this one because at this moment we do predecessor right we do it we keep doing to the right so yeah so here's the right side right so the lab currently is three here so we start from the left here which is one and then we go to right so now the two here right but the two dot right is its current right because we are at this moment we already have a link here if we don't have this end here what it will do it will continue go back to three right so now the predecessor will become three because the person should write it exists right it will be three and then five right then will be go over the call some other places which we don't want that's why we need this check here too to stop and to is before once we say this three here right and once we find this the rightmost node here okay so here that's why we need to heaven and not sat here because at this moment these ready set so there's no need to do this logic again because that will go back to the left again which we don't need right so in the end what is in this case it will go to the house here all right so then we can press start processing this node here the three node right and once we process three nodes like we said besides doing this regular movement from current to the right side we also need to room move this link from this two to three all right that's how we remove this link and then we go back to three and then we move to the right side we mean which is five right and then the five the current is five that's five have a left node no it will go it will continue to the right which is six right C which is six at this moment six so then it goes back here again same logic here six the six have a left yes it has left so it will go back here to check to find the basically the child node of six here which is five right the women's if an adult goes over and over yeah that's how this Morris in other trailers work hopefully you guys understand it and now we are we have this traverse code here now we can just simply add our swap code here writes remember we still basically we just need to add this logic which we already seen twice previously and two here right okay so we already have that so remember we have two places it would will be doing the regular process right this is the process the leaf node and this is the this house is to process the root node right so we basically we have to duplicate the same code in two places so we will be maintaining this current right as the previous and same thing here if so we have seen current less than all right the previous start value then we just do what first or second whatever current if not first with - a first dot pre-write tree house with - a first dot pre-write tree house with - a first dot pre-write tree house no okay so here remember here so we cannot do a house break here you cannot do a housebreak here why because if we break before traversing the whole tree here because the and let's see we have a let's see the swapped two nodes will be down the road very deep something somewhere here right somewhere here let say there are there two nodes got swap here and will be swapping will be getting those two nodes from this logic once we get this largely let's see you if we just stop here break here right so what does it do right it will stop here basically will have will leave all this kind of parent the predecessor and apparent link here right which will make this tree a cycle right which is not right so with what which means even though we have process we have seen those to swap nodes we cannot stop here so we have to keep finishing processing of the tree to remove all the predecessors link we previously established that's why we did this more each tree more algorithm is kind of like a little bit time-consuming kind of like a little bit time-consuming kind of like a little bit time-consuming but it's a it will save us a lot of space because it doesn't use any extra space here right so basically with we just simply ignore that break here right and we can just copy the same logic here yeah we just simply copied out the logic here and that's pretty much it is right so that should do the job right so once we finish everything you should do it run it predecessor is not defined yeah I'm pretty sure there are some typos down there cool yep works cool guys so just to recap what we have discussed moreish right morris algorithm so what we do every time we see a node right we uh we tell if it is the left side if there is a left side we try to find the rightmost node off the left side and then we establish right we establish the link from this rightmost node to the current one and then we just keep going down right until we has it we had established all the link and then we just do the process right remember here every time we need to finish the process of after a root node which has a left side right we just we need to remove the note the link and then keep going to the right side same here if it doesn't have a lab side we just do a regular process right cool guys I think that's it for this problem thank you for watching the video go see you guys yeah bye
Recover Binary Search Tree
recover-binary-search-tree
You are given the `root` of a binary search tree (BST), where the values of **exactly** two nodes of the tree were swapped by mistake. _Recover the tree without changing its structure_. **Example 1:** **Input:** root = \[1,3,null,null,2\] **Output:** \[3,1,null,null,2\] **Explanation:** 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. **Example 2:** **Input:** root = \[3,1,4,null,null,2\] **Output:** \[2,1,4,null,null,3\] **Explanation:** 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. **Constraints:** * The number of nodes in the tree is in the range `[2, 1000]`. * `-231 <= Node.val <= 231 - 1` **Follow up:** A solution using `O(n)` space is pretty straight-forward. Could you devise a constant `O(1)` space solution?
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
138
hey everybody this is larry this is day 10 of the february let go daily challenge hit the like button hit the subscribe button join me on discord ask questions hang out talk about the market or something uh okay so 10 days in today's problem is copy list with a random pointer so i do solve this live so if it goes a little bit slower just fast forward to whatever you like i like to go over explanations and thought process anyway okay construct a deep copy of the list i know none of the pointers in the new list should point to notes in the original list i'm just still reading the problem each notice i'm i think i'm still just understanding the problem and what they're asking for okay grab a list and notes the value is you go to it but then the next and the random should find a new notes in the copy copula such that the point is already represent the same list state okay none of the point okay i mean okay so this is just deep copying okay to x minus okay so basically we just have to make a copy i don't uh okay and the numbers are not unique okay so we have to i see so the tricky thing is that we don't okay i see what the problem is asking we basically want to make a deep copy next is kind of easy and that you know you just copy the next and that should be okay but then we also want to copy the random that points to the same notes but read but because some notes may not be ready because it may point forward or backwards because of that it may even point at itself for instance because of that it may be tricky to create this deep copy that's a good question actually that is an interesting question i mean so yeah so the quick answer is that you know we have a hash table this is actually very straightforward um actually you know but i don't know if that's in the spirit of things um okay how about this i'm going to do it to the crappy what i think is a crappy way then we'll look at the hint and then we'll go over to solutions i don't have an idea of my head how to do it in um over one extra space because you because obviously you know we have to return a new linked list so the new link this is always going to be linear space no matter what but the question is extra from that do we can we do an over one space or can we you know do we do in our event space right so yeah let's kind of let's see if we can then okay let's get started then uh for so we'll create a list to begin with so i just took current as you go to head let's have a new head as you go to uh let's just do a node of negative one so that you know i always have like a point attack points to the head that's before the head so that it becomes a little bit easier sometimes but yeah so while current is not none so we basically just you know do something like this right and then in the same way we go new head as you could oops new node is equal to node of you know current.value and you know current.value and you know current.value and kern well no not current.x suppose and kern well no not current.x suppose and kern well no not current.x suppose okay so we do a new node g goes to this um new node um all right copy current is equal to new head maybe so we have a new node we do copy current it's equal to so for this problem just draw it out i think that's my recommendation um is to go to new node copy current s02 copy current.next something like s02 copy current.next something like s02 copy current.next something like that yeah so this creates the node one at a time so this would be good i don't think that we have to return the new head i guess or dot next so i think this would be good if we didn't have to care about random so let me just one so what i like to do is i like to test stuff incrementally um because we if we so that if something is wrong here we can fix this and before going on to the next uh portion and let me also take this opportunity to put in more test cases because yeah if this is wrong then we can kind of you know fix this before moving to the next step uh and what i'm looking for is things that are roughly right um we don't i'm guessing this is the random pointer which we don't use so just assuming that the first part is right it's going to be good enough for me to move on to the random part okay so this looks good given that we know our expectation for the first part so my mouse is a little bit weird so it's a little bit jumpy uh my bad but okay so now we'll have to do the random part the random parts are a lot tricky hmm and i'm gonna do it the crappy way and then maybe we'll learn together if there's a constant way of doing it you know because the constant way is probably gonna be uh some clever way of doing it requires some clever thing but i right now i'm not thinking about it right and i'm a little bit tired not gonna lie but that's part of learning is that sometimes you know you just figure out what it is there to learn and keep going um okay and on an interview you just try your best if you don't know the answer right like you know you don't want to spend most of your time just thinking about it uh you know having some code is still better than no code um and you know it allows the other parts of your interviews to maybe balance it out if you do exceptionally well in them then they're able to overlook it maybe uh depending on how lucky you get sometimes but yeah basically let's just have a look up table is equal to hash table so let's actually put this here so that we do it on the first loop so okay so then for every current um look up oops oh no the other way oops my computer is a little bit slow look up of um so we're going to make it so that when we look up the current we get the new uh node which is the new node something like that let's put it here after we set it up let's run it again i don't know if this is hashable so that's why i'm going to hash it out guy seems like it's okay maybe um and then now we start again so current is to go ahead uh while current again and next time we just go okay oh you also do copy current as you go the new head same thing as before so now we go uh we start to copy current to the next um you know both enter so now we both have a pointer at the same notes and for linked list problems and binary tree problems to be honest where if you have issues just make sure you um find piece of paper and pen so and just draw out every state of the world um i think having that practice with visualization will allow you to get a better uh intuition of where the pointers are at i don't show it on stream as much because i have done a lot of these problems so that i am able to visualize it in my head a little bit better um so i would say sometimes i still get it wrong so you know when in doubt definitely just draw it out just to kind of you know go through the state one at a time and go for some examples to kind of see where the pointer is at um but yeah so okay so copy current dot random okay so we want to do if this is not none that means that we have to look it up then if this is not none then um and copy current.random is equal then um and copy current.random is equal then um and copy current.random is equal to lookup of copy uh current.random lookup of copy uh current.random lookup of copy uh current.random and i think that should be good oh no i mean it's mostly good but we have to obviously move to pointers and copy current is going to copy current.next uh okay this looks good on a cursory looks let's give it a quick submit cool um yeah so this is going to be linear time linear space uh and you cannot that's the lower band right because that's both the size of the out that's literally the size of the output is linear um and you cannot really do any better that is the lower bound you could have some time convincing yourself that's right because well that's literally like you cannot make you know smaller than your size of your output right so yeah um let's kind of go back and look at let's look at some hints to see if we could optimize a little bit i'm just curious in general um okay yes uh we can avoid oh huh oh yeah i mean we don't create multiple copies of the same node but that is smart i see what is going on okay i mean i accept that i mean did i so i think one thing that i'm trying to figure out a little bit is also um no this is definitely a very clever way of getting in constant extra space on top of the list uh basically the idea here is that um i'm about to do a little bit of a drawing but the idea is um yeah and i'll do a little drawing but i want to talk a little bit about it first which is that what i'm struggling a little bit is try to figure out like how to extend this for other problems right and when you're a beginner uh when you're starting up you don't know or you might not know like the universe of problems and how to kind of think about you know like if everything is new to you don't know what is relevant and what is not and i think part of my kind of going through this here or ideally or hopefully is trying to figure out how this applies to a lot of the stuff that i do and learn right and by itself this is a very cool track and actually i dig it um but as for trying to figure out whether that like is this is a one-off thing is like is this is a one-off thing is like is this is a one-off thing is this something that comes up a lot is this you know um can i use this to apply for different things um i don't know i don't think i have a great like i don't think i relate this strategy that much with anything else i've done um so i don't i think this is this feels very one-offic so i don't very one-offic so i don't very one-offic so i don't like i would not necessarily worry about figuring out distract this is more like a brain teaser type thing more than um more than how do you say it um i mean this oh sorry let me get the paint thing up um oh yeah um okay but yeah so the idea here behind this solution and i don't think this extends i think it's one off so if you don't know it's okay if you don't if you have time to study other things i recommend studying other things in general but basically uh you know you have the original nodes which i'll color in black right um okay maybe this will be a little bit curved and then you have the new notes that let's say i color in red right so you have it in between right so then the idea is that these original lines uh you have original next things where you know you have oops one color so you know your original notes go like this uh with the necks right and you know and duplicating this is straightforward as we talked about um and the idea is that okay now you interleave it uh into weave it in the leaf so that it goes like this right um and this is as i said very one-off i and this is as i said very one-off i and this is as i said very one-off i feel like so i wouldn't worry about understanding the solution but i'm trying my best to explain it um but yeah but now that you have that um now that you have this you know you have it now we add the random pointers right so this random point of paint in blue like this is the original random pointer on the only the black circles you have something that points from here to here uh here to here and so forth right um and you know and here to here say right um and then the idea is that now you can trace those pointers in a way such that um well yeah now that for each red node you can go okay yeah you now you can trace the red node so that it goes to the random pointer because on the red nodes you know what the um you know what the things are so you could do it at the same time so let's use another i know this is a little bit messy i'm trying to figure out how to visualize in a good way but let's say you know now you have a while loop that point at here and here at the same time um then now to update the red ones uh next pointer you just kind of trace it by so now you have two uh you look at the black node that is corresponding so you move two nodes at a time in an interleaving kind of way and then on the black nodes random you just look at that one's next right on that one's yeah that one's next because basically you're tracing the blue line um you're tracing this blue line right here and then that's that next so then this next it goes to here so then now you know that this node and i'm going to use another color so now you know this node now goes to here that's basically the idea um like i said i don't that's the idea to kind of get it in uh oh or one extra space and it's a cute idea um i wouldn't spend that much time on it though it's kind of like oh that's cute and then you kind of move on because i think i mean if you get this on an interview it's going to be always be a little tricky this is such a weird one-off tricky this is such a weird one-off tricky this is such a weird one-off thing that i don't think really applies to many other problems or ex or in both competitive or in interviews um if you disagree let me know in the comments but that's what i think so that's where i um so yeah so i think that's my comments here uh i'm gonna show the screen about my current code which is of n times of n space and of n extra space which is not optimal i mean it's the best oh big o notation um complexity but it does use extra of and space and stuff extra or one space but i rather i feel like that's like i said that's not really um something that i think that's more trivia and it's or more brain teaser i don't see it coming up that often so definitely um yeah i think if you just do it my way you're probably you know going to be 90 of the way good there and that'll allow you to be good at other linked list problems that's what i would focus on um yeah cool uh that's all i have for this problem let me know what you think and i will see you later take care of yourself take care of others uh stay safe stay good stay healthy and to good mental health and i'll see you tomorrow bye
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
367
because 367 question perfect square um a valid perfect square so basically uh we are given a positive integer norm uh while a function which returns true if num is a perfect square else false so do not use any booting library functions such as square root um so for example 16 uh we know it's like 4 times 4 is 16 so it's perfect square so we will return true um if our input is 14 will return false because it's not a perfect valid perfect square so obviously you can brute force it so you can just go over 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 and check whether the square of those numbers is equal to the number itself if it is then you can return to otherwise you can return false um but um that solutions time complexity is b is going to be o of n um and if you submit your solution you will exceed the required time complexity so we should find a more efficient um solution than the proof force one so a more efficient solution it's easy to think we can use binary search right so instead of searching 1 to 16 we just search the middle number which is probably 8 so 8 times 8 is 64 which is larger than the 16 so we can search the left part of the array so the left part 1 to 8 and we search the middle number which is five is uh larger five times five is 25 which is larger than 16 so we search the middle point of one to five which is three times three is um nine which is two too small for sixteen so we search uh the middle number of three four and five which is four and four times four is uh sixteen and uh we can return to so basically we are using the binary search uh for our uh solution and the time complexity is going to be all of a log and um so for binary search you just have to remember there is a template for binary search let me just code it up so first of all let's handle our corner case if our num is equal to one we are already given a positive integer number so we don't have to handle whatever is uh less than zero so if num is one just return true because uh one is a perfect square number um and also meaning that number our number is going to be two or a number larger than two so for binary search you just have to know that uh you have to have a left and right so i left is going to be one you can put it to put two here because uh obviously um the less the smallest number is two but uh yeah it doesn't matter so our right is going to be no because uh um yeah so we basically search the array because us the square root of a number won't be larger than the number itself so our right is numb so uh so this is the um this is the template for binary search wow left is less or equal than rate um and we have our midpoint which is left plus uh right and uh divided by two i'm using um the integer division here because i don't want to get a decimal point number and so and uh the square is going to be meat times meat basically we just compare if our square is equal to
Valid Perfect Square
valid-perfect-square
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_. 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. You must not use any built-in library function, such as `sqrt`. **Example 1:** **Input:** num = 16 **Output:** true **Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer. **Example 2:** **Input:** num = 14 **Output:** false **Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. **Constraints:** * `1 <= num <= 231 - 1`
null
Math,Binary Search
Easy
69,633
799
hey everyone today we are going to throw the little question Champion tour so there are glasses in a pyramid like this and we put champagne from the top and each glass holds one cup of champagne and when the topmost glass is full any excess liquid food we will fall equal to the grass immediately to the left and the right of it so like this and the same things happen in the second row so if these two are full so something very fall down right like this and they like this and look at the side row so there are three glasses and the middle grass got champagne from our right side and the left side right so that's why this grass is half of glass right and on the other hand look at the um lift the most glass and the rightmost glass so left most grass got the champagne from the left side right so that's why um amount of champagne is like a cool tofu and the light must also got the champagne like a quota amount quota food and now after applauding some non-negative integer cup of champagne non-negative integer cup of champagne non-negative integer cup of champagne returned how full the JS grass in the iso is and the both I and the J are zero indexed okay so let me explain how we think about the solution so we can pour champagne from the top of the tower from here and when the topmost grass is full any excess liquid poured with four equal to the grass immediately to the left and the light of it so question is how we can calculate overflow so since this description set each class holds one cup of champagne so we can say like this so of stands for overflow equal amount of champagne in current class minus 1.0 so y 1.0 because current class minus 1.0 so y 1.0 because current class minus 1.0 so y 1.0 because each glass holds one cup of champagne so actually this is a max amount for each glass so if um among the amount of champagne in the current class is over 1.0 that should be current class is over 1.0 that should be current class is over 1.0 that should be over 4 right and uh so this overflow amount goes to like a left side and the right side right so that's why um so exact overflow amount for the next left and the right glasses is so amount minus 1.0 so amount minus 1.0 so amount minus 1.0 and divide two so easy right so after we calculate overflow we just add the amount of overflow to the next left and the right glasses and we repeated the this process again after that all we have to do is just return amount of Target grass so in this case we need to keep all amount of champagne for each grass so that's why our like we use like a dynamic programming to keep amount of champagne for each class I'll show you how so that is a basic idea to solve discussion so with that being said let's get into the call okay so let's write our code first of allocated pyramid of glasses so Kira it equal and the initial value is 0.0 so that is and the initial value is 0.0 so that is and the initial value is 0.0 so that is empty and this is a number of graphs for each row so multiply K 4K in range so first row has one glass so from one two and second glass has two and the sort of glass has three glasses so that's why until 101 so this 100 times is not included so we stop for 100 and then um so poor initial amount of champagne so pure meat and zero equal four and then um like a Travis each row and the operator champagne in each class so for Row in range and uh query row and the i is a warmer folder for grass in French and glass should be the first row has one glass and the second row has two glasses right but at this row started from zero so that's why flow plus one right and then first of all calculate the Overflow over row equal so as I explained earlier so pyramid and so blue and the grass so get the amount of champagne in current glass minus 1.0 this is a max amount for each grass 1.0 this is a max amount for each grass 1.0 this is a max amount for each grass and then divided 2.0 and then divided 2.0 and then divided 2.0 right so overflow goes left side and the right side so that's why divide two and if over flow is greater than zero in the case um we should add overflow to uh so next grasses like a left side and the right side so PIRA meet and next row should be row plus one right and then so this glass is a left side of glass so that's why um so goes to left side like a over row and then one more thing so right side and a row plus one and this glass is a left side so that's why we need to press one so that is the right side press equal so same over row and then in the end we should read the mean and the max should be 1.0 right so and the max should be 1.0 right so and the max should be 1.0 right so compare 1.0 and or compare 1.0 and or compare 1.0 and or pyramid and uh query row and create class so this is a target grass and if this is over like a 1.0 this is over like a 1.0 this is over like a 1.0 so we take a 1.0 because uh this is a so we take a 1.0 because uh this is a so we take a 1.0 because uh this is a max amount for each class so if Target to Grass has less than like a 1.0 we return the this than like a 1.0 we return the this than like a 1.0 we return the this target grass 90 so time complexity of this solution should be yeah this is a looks like a one square but uh this is a fixed with 100 so actually we can say one time because it doesn't grow over like a 100 and the space Also yeah same reason so looks like a orange square but uh this is a like a fixed size so actually um you can say one space and but in reality so we use a 2d array and actually uh we can optimize the 2dla to like the 1D array so let me write the solution code with 1D array okay so let's write a code with 1dra so first of all glass levels and the initial value should be 0.0 that is empty multiply we need 100 0.0 that is empty multiply we need 100 0.0 that is empty multiply we need 100 and grass levels so we pour from the top right so that's why um zero and uh four and then for current Row in range and uh 20 row and every time um we initialize the next levels and also we need to like 0.0 and levels and also we need to like 0.0 and levels and also we need to like 0.0 and multiply 100 and then we need one more folder for current grass in branch and the current row so current row starts from zero so password is one glass right and the second row has two glasses right so that's why we need two plus one and then calculator over flow equal so taking the max Zero versus so okay same and Plus levels current grass and minus 1.0 and the Divide 2.0 and minus 1.0 and the Divide 2.0 and minus 1.0 and the Divide 2.0 right and then up to date next level so if we have overflow so um left side of next levels in the right side of an X variable will be added right so that's why next levels and the current grass so this is a left side plus equal over flow and the next levels and the current grass plus one so this is the right side first equal over row and then after that so grass levels should be next to letters right so next levels and then we repeat the same process again and then after that just return um ring 1.0 so let's say this is the um ring 1.0 so let's say this is the um ring 1.0 so let's say this is the same as a 2d array so glass levels and just uh create address so this is a target grass and if this is over 1.0 we it should return 1.0 over 1.0 we it should return 1.0 over 1.0 we it should return 1.0 yeah that's it so let me submit it yeah it looks good and a very efficient space complexity and the time complexity is same so looks like a one square but uh this is a fixed with 100 so we can say one time and the space also um or one so this is a fixed with 100 so fixed size and but the previous call in the previous call we use a 2d array but at this time so we use a 1D array so that's why space is very good yeah so that's all I have for you today if you like it please subscribe the channel hit select button or leave a comment I'll see you in the next question
Champagne Tower
minimum-distance-between-bst-nodes
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.) **Example 1:** **Input:** poured = 1, query\_row = 1, query\_glass = 1 **Output:** 0.00000 **Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. **Example 2:** **Input:** poured = 2, query\_row = 1, query\_glass = 1 **Output:** 0.50000 **Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. **Example 3:** **Input:** poured = 100000009, query\_row = 33, query\_glass = 17 **Output:** 1.00000 **Constraints:** * `0 <= poured <= 109` * `0 <= query_glass <= query_row < 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
94
509
hello everyone welcome to learn book club in this video we will discuss about today's list code problem that is the fibonacci number obviously this is an easy level question and uh but we'll try to understand how we can impose this question in like top down dp and bottom updp like we'll go ahead with dp we can i will discuss about the normal way like the recursive way to find the ddp and also uh i'll discuss the other way that is a simple iterative way to find that okay uh like one dp but find the fibonacci numbers so let's see what exactly the question is uh telling us and how we can how we should proceed to find a solution to this kind of question let's understand that so first it says the fibonacci numbers are commonly denoted by f of n form a sequence called the fibonacci sequence this is the fibonacci sequence i will show you in a moment says that each number is the sum of two preceding ones a sum of two preceding ones okay uh starting from zero and one that is uh f of zero is zero f of one is one and then following numbers will be uh following this pattern so it's more like you have this first two first number is zero and the second number is one okay and following we'll go ahead with sum of this to zero plus one is one okay one plus one is two uh so two plus one is three okay three plus two is five then five plus three is eight okay and then uh eight plus five is thirty so this is the pattern it keeps on going and like we need to sum up the last two like two previous values to find out the next value of it okay now how can we go ahead to finding a solution like this okay let's try to see the examples once so it says when n is 2 the answer is 1 how n is 2 that means this is 0 1 and 2 so we are returning this particular hello okay that's the number 2 like 0 1 2 and then when n is 3 we are returning 2 that means 0 1 2 and then that's the third position we have and third positions value is two right and thus we are returning over two that's the output we have okay f of three is for two plus four point four two plus the f of one is uh this particular three so we found our answer okay and the following when n is four we have a return three that is you can see zero one two three and four the fourth position value in our uh all the halogen is like three so that's what we are returning over here so this is the idea behind such equation like that's what the question is talking about okay so if we have given four so that means uh basically means when you are trying to find the fourth value is basically uh sum of the third value like f of three not like the position value okay f of 3 plus f of 2 fine uh that's the value so now each case f of 3 is what we need to again see f of 3 is again f of 2 plus f of 1 right f of 3 is basically f of 2 plus f of 1 fine that's what we have and also this f of 2 and then f of 2 is what f of 2 is f of 1 plus f of 0 so uh basically f of 1 plus f of zero so that's the question we have over here okay so that will keep on breaking the numbers into the lowest problem and this f of zero is zero f of one is one and then f of two is f of one plus f of zero again so one plus zero okay so see how what the value is one and thus we are returning uh three so this is the uh the exact question that they are asking us okay well what do we will get a value but we need to break it till its lowest from and then we will find out a solution to the particular value so what are the ways we can find a value to that the first way can be you just uh get a number okay like the way the num n is given to us okay given is n like we can say that given we'll look at the answer but uh let's discuss like what can be the solution ways for that so uh first thing is if n is uh less than one there's no point right if n is less than equal to one if it's over here then we should like if the value lies this side then we should more or less later in the value itself right there's no point uh calculating anything further if uh n is like greater than one now how we can go and we can uh keep on changing values like we took off a level a equal to say zero and we took a b equal to one and then we can uh run up like while loop like while okay uh and within the while loop we can go ahead like n minus greater than like greater than one so that's the idea we have uh bigger than one thing we're the one and within that we will find the sum of like uh a plus b being the sum okay uh like say a value s is a plus b and then we'll um do like a equal to b and then b equal to s that's the while loop we will have and after the all the till n becomes zero or n becomes one we'll ultimately find out what's the value we have okay that's the idea we have over here and that's like the and ultimately we will return uh return b okay i just wrote rdt so just particular so this is an identity kind of solution we have okay we are running through a while loop and taking the number of steps and continuing with the sum like sum of a plus b and ultimately returning uh the value of v since b is showing the sum over here so that's an identity kind of solution you can think of this solution is like uh i think this is the best solution if we take the both the cases you know like both time complexity and uh space complexity in town so in this the space complexity is order of one and time complexity you can see it's uh running a while only a while loop of n elements so that's a like order of n right so this is the value we have so that's the order of m being the time complexity and the other being the space coupling order of one so that's an normal iterative process and it's pretty fast it's not a slow one okay the other kind of solution you can think of is uh let me see this off uh the other kind of solution you can think of as like a recursive solution so you are getting a fif of n that's the number you're getting so you just have a first check that if n is less than equal to one you return it that's the initial check and then you will keep on doing like uh like in the else case you will do like a fifa and minus 1 okay that's one so p of n minus 1 plus 3 of n minus 2 okay i'm sorry for this writing so if there's a thing you have n minus 1 and n minus 2 you will keep on adding them and like you will go into the recursion loop okay so you will return this okay so this idea if like within this loop just like within the function just give a check that if n is less than equal to one i'll return the value else uh return f of n minus 1 plus f of n minus 2 so that's the check you will have and you will keep on checking that again and you will keep on finding a value but think of something like that say before finding a save of four okay n being four then you've got five of three plus five of two then you break five of three in favor of two plus three of one okay if you've got two plus your one you broke them into that and once you break them into a figure one see you again found uh like breakfast or two into favor of one and three of zero okay you found the sum of five of three and going back you actually have a sum of five of three and then you move into favor of two again and again found like five of one and four people of zero and then found us only turn back but don't you think this a fave of two that is this particular part we have over here is just a repeat of this particular part right so if that is a repetition is happening then we can think of some kind of uh that dp or dynamic programming solution because uh that's how we stop this repetition and remember our values from previous calculations okay that's what tp is all about say the number is much because you are going for to find something like fifa flower 10 okay so if you want to receive nine uh like not zero ten so it will be nine uh plus eight right so nine plus eight nine will contain eight plus seven right and eight will contain you are going to calculate an eight over here a large uh 2d graph like um a binary trend of uh waveform over here like if you just see all the iterations then a kind of a binary form and again that uh particular three word calculation we need to do over this eight right but again if we break eight that would be seven uh plus six right this seven and this seven will be repeated so that so when you're seeing the repetition is there then we can think of a better solution that's a dynamic programming approach to find out how we can remember them okay but uh before i move into the dp approach let's uh let's discuss the time complexity of this so you can see like on each level we have breaking down into two different operations so that would be more like p of n equal to t of n minus one plus n minus two right so that becomes an exponential type complexity that is uh order of two to the power n and this that's a pretty huge complexity if you have a larger value like n being a bit larger uh so that's 2 to the power n and space complex is obvious order of n how order of m we have just like the recursive call stack function is being called and that's the like or n times the function will be called so that's a more or less the recursive approach we have over here okay uh now let's move into the dp approach over here the dp approach will be uh we will have an kind of and we will remember the values and then we will keep like keep uh track of all the values we have y okay so this is the dp approach but i wrote already for you so this approach is more or less like a bottom-up approach like or less like a bottom-up approach like or less like a bottom-up approach like ndp there can be two approaches okay uh let me explain them in uh details as well so what can the two approach of a dp so the uh one is as we say the bottom-up approach and the other is what bottom-up approach and the other is what bottom-up approach and the other is what we say the top down approach okay so whatever approach is more like uh say you need to find a value of n right you are given an n you need to find the value of it so how will you go ahead you start from zero and one okay the same way we were doing in our normal iterative way or the normal uh normal activity what we are doing so that's the one we started with zero and one and then keep calculating like keep calculating the series because we didn't see this till we reach an answer like that particular value and return that final value so you started from the bottom and went up to the final answer that's a bottom-up approach okay answer that's a bottom-up approach okay answer that's a bottom-up approach okay the other approach we have is like the top-down approach top-down approach top-down approach that's more like you started from this position value okay and uh keep on breaking down till you get a lower basis you've got a best case uh there's like you started from the top you went into the deep and deep uh and then you found our base case over here and once you found the best case you will simply uh reverse back to our final answer and then we'll just return our answer like the one way we were doing in our recursive approach we started with the main value we started breaking it into two recursive function calls and we started to calculate the value right so that was the idea behind that top down approach so both top down and bottom up is like uh we can do like what we are doing in a recursive approach we are just calling the functions but what if we keep a check that if the value at that position in the additional array or the uh or a particular array we have okay if the well is the fifth cache you can say so once we have a value for that particular element it can be like we've got our value okay now uh what can be done we can store the value in our position and once we value repeated we'll simply turn the file else we will go ahead with uh finding a spell so that's the idea behind the top down drop-down approach behind the top down drop-down approach behind the top down drop-down approach and the one i have over here is the bottom of the workplace that is the one i love the most and what we are doing over here we are simply taking if n is less than 2 and this less than 2 is like the zero and one those two values are there so we'll say return it fine and then we took a pivoting array and then we stored our initial two values like zero and one those are the initial two values and then we started from two till n that is we started from our lower values like the loop is going up okay we started from two till n and then we went ahead with um we found that like five of i is p of i minus one plus i minus two so it's not a function called see if we are not calling the fifth function over here rather we are just calling the array over here right fifth array that we stored that we created so we're just following the fifa array and we keep on calling the last two values like initial case zero plus one wave of our two will be the first one equal to one so that's where we keep on calculating the hello within the loop and ultimately on fif of n so we just written our value okay remember something like when it says in our initial stuff is like we create an error size of m but by using dp usually we'll find more or less on every case uh we need to create a value of n plus one why because the array starts from zero and we need n values not the zero infinite okay uh so like the nth follow in the sense like we need to go for the next value that is n plus one so that's the idea behind like you should we should keep in mind but it depends on case okay so you should remember how when and why we need so we just need to look into that whether it need or not and we'll find out based on that so that's the question we have over here okay so i hope this is understandable i will uh let's discuss the time complexity of this particular approach we have over here okay the particular approach uh this particular equation capacity will be more or less like uh if we just think we are using an only single loop and that single loop is running from uh like all the n values right that the single loop is going through uh the loop i'm calling is like this and this is order of n like and other than order of n all other operations we have in our particular program is like all our order of one so the sp time complexity will be order of n fine and the other one we can have is the space complexity the space completely complicit you can see you just created an array of size n plus one right and any other spaces you took no so that's a only an array being created order of n so that's an order of and bring the space complexity and this is the time compensation so that's the complexity we have so thank you all for watching this video uh i hope i can make you understand how you can solve the question like this and yeah just for your clarity i will just run the code once and you will understand how this particular is working so uh that's all for this video guys i hope you are able to understand this program and if you have any doubts make sure to comment on your questions in the comments below i will be happy to help you out as well thank you all for watching this video hope to see you soon in my next video as well
Fibonacci Number
inorder-successor-in-bst-ii
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given `n`, calculate `F(n)`. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. **Example 2:** **Input:** n = 3 **Output:** 2 **Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. **Example 3:** **Input:** n = 4 **Output:** 3 **Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. **Constraints:** * `0 <= n <= 30`
null
Tree,Binary Search Tree,Binary Tree
Medium
285
235
foreign code called the lowest common ancestor of a binary search tree it is a medium we're going to jump right into it given a binary search tree or a BSC find the lowest common ancestor node of two given nodes in the BST according to the definition of LCA on Wiki the lowest common ancestor is defined between two nodes p and Q as the lowest node in treat T that has both p and Q as descendants where we allow a node to be a descendant of itself so example one we have this BST right here and we want to find p and Q of 2 and 8. so the lowest common ancestor node would be six both are descendants of it example two we have the same tree and this time our p and Q are two and four so the LCA here is to itself since a node can be a descendant of itself so it is the ancestor of both two and four because remember we want to find the lowest common ancestor example Theory we have two in one so we would have just root node two and left child one of course it's similar to this example right here the root node 2 would be the LCA and we have some constraints here the number of nodes would be within this range all the node values are unique he is not equivalent to q and P and Q will exist in the BST so we're guaranteed to get a valid output when we're searching for our LCA in our binary search tree okay so this is actually pretty straightforward but before going into it let's think about some edge cases first given a binary search tree what is our worst possible LCA what is a common ancestor that is as far from p and Q as possible well that would be the root node right because any node p and Q no matter where they are on the tree are a descendant of the root node it is a common node between both p and Q so worst case a p and Q are on different halves of the subtrees if they split up right away then the LCA would be the root node itself because again it is the direct ancestor of every other node so it is always a common ancestor of any node now what is the best case scenario how do we ask close to either P or Q as possible well that is if the LCA is either P or q and that would happen if either p and or Q is a direct or indirect parent of the other say one was two the other was five in that case the LCA would be two since one of its descendants is five so what we want to do is find a common ancestor of both p and Q that is as low as possible and remember this is a binary search tree which means the values are ordered in a very specific manner in a binary search tree what happens is the left child is always less than the Root's value and the roots value is always less than the right child and we've done a video where we explore exactly what a valid BST is I've linked it down below if you want to look at that but we're going to make use of the fact that we have a binary search tree and we can look at these examples right they're very specifically ordered left is always less than the root is always less than the right no matter where we are even here left is us and root is less than right so if we have the following examples say this is our BST and these are our p and Q what is the LTA for each one so we have node 5 and 10. the LCA for this would be eight because that is what's holding them to together what about 5 and 14 that would again still be eight because 5 and 14 they're both less than 15 right but once we get to eight we see that they're not in the same half and so we split which is why this is our least common ancestor because 15 obviously is a common ancestor but to get more specific to get as low as possible we would go with eight now what about two and six well we can use five for that would be our LCA and how we would go about doing this right we would start from the top we have 15 and we see our values two and six are less than 15 which means they both lie on the left half of this tree then we compare both values against eight and we see again we are both less than eight so we go to the left child of eight compare against it we see one is less than it one is greater than it so we know we split and that split would be our LCA so our LC in this case would be five what we're looking for is a split when both values are either less than or greater than we just keep going but once that is no longer true that is how we know we found our LCA now this also works if one is a parent of another because both values in that case would not be greater than or less than the root it would actually be equal to it so if we look at p and Q being 20 2018 We compare against our root node it's greater than our root node 15 so we move to the right half of that tree so we check against the right child and now 22 and 18 only one is less than the root the other is not less than it so we know we've sort of split and 22 would be our LCA so that is all we need to do so what we're going to do is we are going to recursively call lowest common ancestor and check p and Q against the root if both are either less than it then we're going to call this again with the left child if both are greater than it we're going to call it the right child if neither is true we found our LCA and we would return the root and that's it that is the logic so let's go ahead and code this up and then Super quickly run through an example so we're going to go ahead and code this up and remember this is a recursive solution which means we need a base case and a recursive case so what is our recursive case we want to keep going while p and Q are on the same side so either both are less than the root or both are greater than the root so if P dot val is less than root dot vowel and Q dot val is less than root dot vowel that means we want to check the left subtree so we are going to return self dot lowest common ancestor with root dot left p and Q if that is not the case then we want to check the other side right so if root dot vowel is less than P dot vowel and root dot val is less than Q dot val we want to return self.lowest common ancestor of root dot self.lowest common ancestor of root dot self.lowest common ancestor of root dot write p and Q and if neither are true then we just want to return the root and that is it that is how simple this is and if you actually notice something here right usually with binary trees and recursive Solutions a check we often make is to see whether the root being passed in is none because we don't want to operate if the root is none except in this case we would never run into that situation but why is that so we're never going to make it that far down the tree to where we're going to be running into routes that don't exist that would happen if we go down as far as a leaf and then try to call either child of a leaf node but we would never even make it to a leaf node because what we're looking for is a least common ancestor that means it has to have a descendant even if the node is the descendant of itself it still has another descendant so we'll never run into that situation which is why we don't need to make those checks and why this is very simple few lines of code so let's go ahead and run this runtime error oh that is because our example is still over here so let me go ahead and comment this whole thing out and now we can go ahead and run code accepted and submit and it is accepted as well so before we run through a super quick example space and time complexity we only want to go down as far as the tree is deep so if this is a balanced binary tree which means there are nodes on both left and right sides at all times then that would be log n because that's sort of the depth of the tree right we just double each time so that is log base 2 of n however we are not told that this is a balanced binary search tree which means we could potentially have nodes just only on the right side which means all our nodes are on one side and we would have to go through all of them if worst case our LC is the second to last note so that would be o of N and same with space our call stack would go as far down recursively we're just building and building up until we hit all the nodes so that would also be o of n now let's go ahead and run through a super quick example so for our example let's say we have this BSC over here and our pnq are 17 and 18. our very first call would be with the root node which is 15 ps17 and Q is 18. now let's go line by line just to see how this is running we go in the first if statement to see if p is less than the Root's value and if Q is less than the Root's value neither are true so we go into this next if condition if the Root's value is less than p and The Roots value is less than Q which is true well now we call this again with root dot right so we're going to call this same function we can't return yet except with root being 22. so we go back into lowest common ancestor and this time the root node is 22. is P's value less than 22 that is true 17 is less than 22 and 18 is also less than 22 which means we call this again with root dot left so we are now going to be calling this in with root being 18. that is the left note B is still 17 and Q is still 18. now when we call this at this point we make this check right is p is a value less than the roots value that is true and is Q's value less than the root value that is not true it is equal to that value so we go out of this if condition now we go into this if condition is the roots value less than P that is not true 18 is not less than 17. so what we do finally is return the root which is 18. that is our LCA if we're given 17 and 18 as our p and Q so that is how to find the lowest common ancestor of a binary search tree if you have any questions whatsoever let me know down below otherwise I will see you next time
Lowest Common Ancestor of a Binary Search Tree
lowest-common-ancestor-of-a-binary-search-tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8 **Output:** 6 **Explanation:** The LCA of nodes 2 and 8 is 6. **Example 2:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4 **Output:** 2 **Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[2,1\], p = 2, q = 1 **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the BST.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
236,1190,1780,1790,1816
1,832
um hello so today we are going to do this problem which is part of lead code October challenge check if sentence is pangram um so the problem says a plan gram is a sentence where every letter of the alphabet appears at least once right so given a sentence we're going to check if it contains only lowercase English letter and if it contains if each one of them appears at least once if that's the case we'll return true otherwise we return false um this one has all of the alphabet smaller case letters so we're going to ensure this one doesn't so it's not false so this one should be pretty easy we can just go through all the alphabet lowercase letters um and then check if we find any of them that is not in the sentence we can return false if we finish and we did and we were able to find all of them were essential right so very straightforward here um okay so how do we do this so first we need an easy way to check that a letter and this is in the sequence and if a sequence is a set that would be easier right that would be quicker of one instead of oven if it's not and now we need to go through every character in the alphabet to check if it's in the um if it's in this sentence so this in Python will give us all the um so we just check if it's not in it then that means we find the letter that is not in the sentence so we need to return false because it's not playing Ground otherwise if we're able to find all of them we can return true right and then we can run this and we submit okay so that passes test cases in terms of time complexity this is a loop on the number of letters so this is um whatever the number of letters is so if we check the length here um it's 26 right so this is of 26 time um and for space we are only using this set so it's all one spaces it's um of um n and n being the length of this sentence um but also like a set would be at most the number of letters right so it's um of 26 space as well right which is constant almost yeah so yeah that's pretty much it for this problem uh pretty easy problem please like And subscribe and see you on the next one bye
Check if the Sentence Is Pangram
minimum-operations-to-make-a-subsequence
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Array,Hash Table,Binary Search,Greedy
Hard
null
373
hello everyone welcome back here is vanamsen and today we are going to solve uh and optimize lead code problem 373 find Keepers with smallest sum so let's dive in to briefly explain the problem we are given two sorted integer RI and an integer key and we need to return the key smallest per form by taking one elements from each array now let's look at the previous solution so this is our previous solution and we use a built-in Heap data structure and we a built-in Heap data structure and we a built-in Heap data structure and we push per into the hip based on their thumb but we Face an issue with a duplicated per because we are doing push I plus 1 J and push i j plus uh one separately so to solve this we use visited and it was asset to keep track of person already pushed into the hip to not have a duplicates however we are optimizing this solution so let me walk through the new one that might be optimized so in the new approach instead of tracking the visited purse we can push purse into the hip with a different approach so we can push the purse from Nam with the first element from num to until we reach key or a run out of elements in num1 and while doing this is we also keep track of index of num2 elements we have paired with the current num one element so next in each iteration we pop the pro with the smallest sum from the hip append it to the result and push the next part onto the hip only if it exists this new is formed by keeping the same num one element and taking the next element from num2 and this eliminates the needs to use visited set and the possibility of pushing a duplicated purse into our hip so why is the new solution faster this is because we are avoiding the overhead of managing the visited set it's always faster to compute the next element to consider than to check if an element has been considered before plus we are making fewer pushes into the hip as we don't have to push all the pair initially so let's implement it and see if it will be faster so Q and result and if not num1 or not num2 or e is zero then we return results or empty lists and for I in range minimum of chi and Len of num uh hip push q and num plus num of 2 i 0 and while he greater than 0 and Q i j hip pop Q and result append the purse so num1 I and num2 J and if I plus J less than Len of num2 keep hip push Q num one num two J i j and key minus one and we return the result so yeah here you have it so this is our updated algorithm of solving the uh yeah key pair with smallest sum so let's run it and see if it's working so we don't use a set of visited elements up yeah so wrong intention so I have fixed it so hopefully now it will work so yeah it's working so you need to always check in the engine sometimes you can make double tapulation or something so yeah everything work so now let's run for and test cases to verify the speed and less time is was 40 and now we have 82 and 46 so yeah we have Improvement in speed and this is because this additional uh approach of not checking visited set and there you have it a more efficient solution to find Keepers with smallest sum remember optimization is key in problem solving and every bit of efficiency can go a long way and stay tuned for more such optimization and remember uh keep coding stay motivated keep practicing see you next time
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
1,466
Hello everyone welcome, you are going to channel me, okay and I will repeat again that if you have not seen my players with graph construction questions, then watch it, the fundamentals of the graph will be clear to you very well. The questions and the graph are okay, so if that If you have n't seen the play list then definitely visit it and it is a medium level question. Today's question is lead code number 146. Okay and it is going to be a very easy question but I liked this question very much. It is a very interesting question. Okay, the name of the question is Re order rots tu make jo parts lead tu city zero ok question has been asked metal has asked the question of this question very much I liked it ok let's see its input output and understand what is the question ok so keep giving me HTS in the question Whose numbering is Rakhi, from zero to minus one, okay, so there are 6 cities, okay, what does it mean, it is connected, like mother, we take zero and one, okay, which is from zero to one. But only one can go from zero, one cannot go from one to zero, okay, that is, it is given directly, okay, so look at the graph, I have made it like this, I have drawn zero to one here, okay, one to three, you to three, okay. This should be kept in mind like take mother, I will tell you why you will not be able to reach now, take mother, you are standing here at city number 2, you do not take mother from here, right, if you will not be able to attend from 3 to 1 square, then this is what we are asking. This is to tell us what is the minimum which we will have to change. Look, this guy is going from zero to one. First of all, he is going from zero to one. This guy is fine, let's reduce it. I turned it to the saw. I made this cut. If we have done that, we have turned one saw. Now if we look ahead, we will have to turn this one too No, because you will turn three from one, we have turned the one from three, so the one from three will turn into one, we have also turned the one from three to one. If it goes slowly then we don't need to change the 2nd to 3rd HA. Okay, now let's look at the 4th one. Can you go with the 4th one? The character is already made. Five will not be able to go by changing the 5th one. You will have to cut it, now look, five to four to zero, now pay attention to whoever is standing here, who can go from here to here, okay here is the answer, your output will be three, okay, the question is quite interesting. Now let's see how we will solve it. Okay, so let's see how we will approach it. Think that it must be clear while reading the question that it is a graph question because we have given the cities and we have numbered them from zero to -1, cities and we have numbered them from zero to -1, cities and we have numbered them from zero to -1, so these are the notes. We are talking about all the other graphs, now it is clear how to solve it, think about it, see, you know this brother, everyone has to be brought to zero, it is okay, everyone has to be brought to zero, okay, now think like this. When I move the tower from zero to one, like mother takes it, this is the graph itself, so to know which one is creating further problem, I will have to travel the graph, so okay, so if I Even if I travel, I am traveling from zero. I went from zero to one. Okay, when I went from zero to one, I came to know that okay this guy is zero seven whereas it should be from three to you, so I can't go this. So it got messed up because I am messed up, it has to be like this, so how will I come here, I am starting from zero, okay, so how will I go from zero to 4, okay, even though I started from zero, then start with the story too, not the story. Story: You will go a little fancy, Story: You will go a little fancy, Story: You will go a little fancy, how will you be able to go to all the notes, you will not be able to go, okay, so what does this mean that we will have to do something in such a way that we reduce the lives of both sides, we should have seen first. What was given in the example? In the example, we can go from zero to one. It is okay and we have to go from zero to zero, the rest is about what you will do, you will need the front of both the sides, then it is not from zero to one, nor from one to zero. I will make one next, when we will make a DJ, neither did we make this DJ nor in it, zero to one is given in the question, but I will also make one to zero, okay why will I make it, he will tell now, wait, a little bit is ok and then 13 From 3 to 1 we will also make 3 from you, if from 3 to you we will make 3 then from 3 to you we will also make it ok, look at what I have made, first see what is the benefit, after that we will move ahead, how to solve it. Hey, I have made the red one, now look here. But even from zero I can go to four because I have made Red Ara and from four I had given that I can go to five, so one of my tensions got resolved that now I can visit every place, this tension got resolved, okay So, after we reach our place, I also need this information whether to do brother's flip or not, that too will have to be decided. Okay, so let's start like mom takes, right now I am at zero, okay, where from zero to where? Can go from zero to one. Can go from zero to four. This time because I have made it 'A'. because I have made it 'A'. because I have made it 'A'. Okay, from zero I have become 'I'. Going from zero to one. If we are going from zero to one, then it will not remain 'A'. Zero going from zero to one, then it will not remain 'A'. Zero going from zero to one, then it will not remain 'A'. Zero means what does it mean that I have to flip it, I did it last time also, now let's move ahead, from one I went to 3, so this guy is also going from one to three, ara, he is moving away from zero is n't he? I will have to do one more flip. Okay, I will have to do one more flip but tell me one thing, when I went from zero to one, I have two, right, zero, seven, one to zero, so how will I know which was the original next? To know which was the original next, was it the white one or the red one, we have to find out that too, so know what I do, I mark the original next as one and the one I made, I mark it as zero, this one, this, zero. They will also be stored in your DJ. When you make a DJ, I will write one. One means original but one cannot go from one to zero, but I have inserted it is fake, whatever can be added from one to zero is fake, but that is why zero is colored. If we mark it, then it's okay, then let's reduce it by one. One more thing, I am late in noting that if it is genuine then I will mark it with one mark and if it is a fake Englishman, I will mark it with zero. It is okay, till now it is clear that let's store it here like this. Okay, now it's okay that I have to replace, okay, I am going from 3 to 2, but look at this, it is zero, it is fake, what does it mean, it must be being made and it is moving towards zero only. So I don't need to replace it is clear till now, mark zero, I am repeating again, if I was able to go from zero to four, then how was I able to go, with the help of this further, I have made a note in this further. If I thought that this is fake, then my mother will think that I am going from zero to four, then it is definitely real, what will happen next, it will be just the opposite, which will be going from four to zero, okay, then this is a good thing, four. The one from zero to zero is the real next one, so I do n't need to flip it. Okay, now from four I went to five, so from four I went to five. Look, that means I have to flip it, otherwise I did plus one for this too, so answer. My three A is gone, I will also make a DJ and show it to you, now it is best to make a simple diagram of it, see, I am going to make a DJ, look pay attention because with this you will also get into the code, okay, so see what you have given me originally. First it goes to the next one, it means one can go from zero, it can be said from zero, it can go to one, so this is my real, so what did I say for the real, we will keep it by writing one, either write true, take bids. Okay, so I got this from zero to one and what I said was that if I make it from 0, then make it zero from one because I have to visit all the notes, only then I will know. I will be able to do it. Okay, if there is zero intake, then it is okay. If we make zero from one, then we can go from one to zero. What will I put in it? If I put zero in it, then add water. If you say two falls, then if you say zero, then it will be fake. Okay, then it will be for every one yard. For this, I am doing it in two entries, okay, so this is the first one, I have made its entry, now coming to one comma three, what are you saying, from one, you can go to three only and this is the real one, I have given it in the question. That's why I am saying it is just the opposite. If I am calling it zero, then it has also been processed. Okay, now look at one thing. Yes, here I have written one to three com one here separately whereas here one is already one in the map. Well, here I write the mobile number of 3 and remove it from here, okay, what else is matching, 3 to 1 0, it is already here, so I make the second entry here too, 2 0, I remove this one from here, okay. Everything else is fine, all the new entries are 30 123 ok, now which one of ours has gone back, now our back has gone, this is 40. Okay, so where can we go from four, he is saying, zero can go, this is the real one, he is ahead, isn't he? After that, can we go from zero to 4, so let me write here that we can go from zero to 4, which I have made, okay, so we have done all this, our DJ is ready, okay, I will also make the graph in the same way, isn't this zero? It means it is okay and it was made just so that I can travel and relax and I can flip and relax where it is necessary to flip, okay and this is the real one, like it is one, okay, this is one, all the white ones are okay, now do one less. Now let's start our DFS travels. I start from zero. So first let's see where zero can be said. Simple then it will be okay. Nothing fancy, I have started from zero here. Okay, one comma one. What does this mean? It happened, I can become from zero, okay, I can become from zero, so okay, I went from zero to one, okay, I went, okay, so I got my answer, which one has to be flipped, one can go from zero to coma, zero. Okay, but why would one go from zero to zero again, I have just come from the same place, so remember what we used to do, to save from this, you can keep the name as widget 0123450, why would I go back to my parents, okay because I have come from the parents, like the period of zero was zero, if there was no one, then I made the minus one, the parents of one, if I went from zero to one, then who is the parent of one, if it is zero, then I have marked it in P = 1. If who is the parent of one, if it is zero, then I have marked it in P = 1. If who is the parent of one, if it is zero, then I have marked it in P = 1. If its parents are one, then one. Now let's see where we can go from one to zero comma zero, if we can go brother, we can go to 0, then zero is my parent, right, the parent will be zero, sorry, so zero is okay, I will not go back, three, I can go okay but Pay attention to one thing, this one, in the three P's, which one is ahead, this one is not the white one, its value is one, it is real and it is taking me away from its zero. What does it mean that this front will also have to be flipped, so I made it OnePlus One, I said that this one will have to be flipped, why do you have to flip it because this is the real one, the one that has been given is wrong, it will have to be flipped, only then 3 If we go from 1 to 1, we will be able to go from 1 to 50, then it is clear, now I am on three, okay where can I go from 3 to 1, one can go from 1, one comma has given zero, okay but the parent of three is one, so why go back? You will go and see this print of Rahatri has been made, it is a show, it is okay, so you cannot go here, leave it with three, where else can you go, 2 0 can go, but how dear, remember, this fake part of me is going away from him. What does this mean? Real is the reverse of justice. How did you manage to go fake with the help of Aadhaar? Okay, it was not there anyway, it was not I who added it, so the real one must definitely be going towards zero. Here is the flip of this one. If it is not necessary to do so, therefore we will not flip it, we are okay, from three to three, this is done, this is also done, this is done for one, then this was done from 0, this was done now from zero. Is the child in the last 4 0? Okay, from zero I am going to four comma zero. From zero I am going to four. Now see, I am going from zero to four with the help of what further I am going. This is fake brother, it is written. I have written here that zero means it is moving away from zero, so the real one must be moving towards zero, this is correct, here is the white one, look, is it okay to flip it, then it is okay, that is the only one, I need all of them. I had to deliver the notes, the red one is helping me in the front to reach all the notes, okay, so I went to four, who is the parent of four, the parent is zero, okay, what is after that Okay, the parent of four is sorry one, its real is ahead and it is going away from this zero, that means do I have to flip it, right, five is going from four, that means it is going away from zero, correct, I have to flip it, so plus. One more has been done, it is okay here, that is, four to five is here, who is its parent, four is four, can go, why will you go again, it is discarded just like that, okay, here I have missed you. Why will you go back to three? You went from 3 to 2, so why will you go back to three? Then it will become clear. Look, pay attention, how will you make the connection, speed it up and do it like this, four, you and back in connection. You have kept me in question. Okay, so what will be Can also be given so that I am adding from B to A and why did I do this zero because it is fake, it is clear till now, this is my fake, I added it here, this one is fine, so it means that I have made a DJ. I made DJ very easily, after that what did I say, I will do DFS tomorrow, to make direct cycle detector, we just have parent variables, I am doing the same thing, so it will be made, there is no problem, Mr. Direct, send it, make it with that, it is even more difficult than that. No, then I will send a simple variable, parent is neither zero minus one, okay, what else will we send, we will have to send this DJ and just do simple DFS tomorrow, now okay, we will take simple DFS exactly what was written earlier, will we take mother? Okay and what is this eat this is parent Okay and simple what to do remember what was the point of going to us where can we go from this hai jo u se they we are going na Okay, so if you look at it is moving away from zero, so if it is real ahead, that means it will have to be replaced, I will have to do it like this, okay, so in the bigger part of the count, I will give the count plus it is equal to one, that's what the fake was doing. If it was ahead then it is an obvious thing. Look, even from you, if that fake was ahead, then it must have been real, it must have been like this for sure, it would have to be flipped, that's why I made 1 here plus one, okay here, it is clear, after this. DFS samples were done again yesterday, but remember, first of all, check that you are not going back to your parents, why would you go back to your parents, who is this parent, is it okay where you are going now? You are going to pay only then you will go, okay how simple was the support, keep increasing your account variable right here, keep the account variable as global, the answer will be stored in this, I know, that's why I liked the question because this is the one which we have flipped. I used my brain and then we made it a little different, this time we made another graph question in which we were storing the legs, right? Generally, they were stored only as V1, V2, whatever, but this time fair is being stored. Let's write again, let's see if it gets submitted. It will be exactly the same as told. I had written almost the code first, which will be our answer, how was it said, okay, let's name it DJ, now let's start filing it in DJ, okay What is there in the connections, one is up, zero is okay, now what did I say, I have to make a connection from A to B, dot push, underscore back, okay, this is B connected and this is original, isn't it real, so I have made it one, okay Zero to Zero is sending its map, it is not simple Only then I can go right, okay, you will be cleared till here You are going far, with the help of reality, okay, so the you will be cleared till here You are going far, with the help of reality, okay, so the you will be cleared till here You are going far, with the help of reality, okay, so the count was increased so that this real Next to replace the post will go DFS are we going to what is going to V are going to V has to be U was because we come from U ok but what else are we sending DJ are sending simple let's run it and see The detailed cases and simple BF which are available with you can definitely make it will be good for you for practice, isn't it a good question, it was very good and I have shown you that I will get it, okay look here. So this is just normal copy paste which I just did
Reorder Routes to Make All Paths Lead to the City Zero
jump-game-v
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`. This year, there will be a big event in the capital (city `0`), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed. It's **guaranteed** that each city can reach city `0` after reorder. **Example 1:** **Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\] **Output:** 3 **Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital). **Example 2:** **Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\] **Output:** 2 **Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital). **Example 3:** **Input:** n = 3, connections = \[\[1,0\],\[2,0\]\] **Output:** 0 **Constraints:** * `2 <= n <= 5 * 104` * `connections.length == n - 1` * `connections[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
Array,Dynamic Programming,Sorting
Hard
2001
237
hey everyone welcome back and today we will be doing another lead code problem 237 delete node in a linked list this is a medium one there is a singly linked list head and we want to delete a node in it so we are just given the node and we have to delete the node we do not have the access to the Head of the node and we are guaranteed to have a node after the node that we are going to delete so if we have an example like this for by one nine then when we have to then we have to just remove five and here if they say remove node one then we have to remove node one we do not have an access to node a head no we do not have a head so what we will be doing is just copying the value of the next node in this certain node so what we'll be doing is saying node dot well should be equal to node dot next dot well so if we see this example then 9 will be at the place of 1 or let's take the example four five one nine so what you'll be doing is just copying the next so next will be one copying that value in this five position and then what we have to do is just break this link between 5 and 1 this 5 is no longer five because we just copied this one to the location here and what we'll be doing is just saying node dot next which will be the node pointer of five fifth note the value here is not 5 it is 1 because we copied it and this node pointer will point to 9 and we just break this link between this node and this node so no dot next and then we have to return nothing so that's it
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
64
hi guys hope you're doing great today's question is minimum path some given M by n great filled with non-negative numbers find a path from non-negative numbers find a path from non-negative numbers find a path from top left to bottom right which is for example in this case 0 comma 0 to 3 comma 3 right sorry 2 comma 2 right because this is a 3 by 3 matrix so which minimizes the sum of all numbers along its path so if we have to traverse from 1 to this one we have to find the path the sum of the elements on the path which is the minimum right so you can remove either dump or right at any point in time okay so from for example from 1 you can either move to 1 or you can move to 3 from 3 you can either move to 1 or 2 5 from 5 you can either move to 1 or 2 and so on so in this example the path would be 1 3 1 because that minimizes the Sun right if you take any of the other parts for example 1 4 2 1 that is more than 7 you cannot go diagonally so from 1 you cannot go to 5 so that option is not available and then you can have other paths as well but this is the minimum so this is a classic example often programming any question which involves finding the minimum number of ways or finding the unique paths or finding the minimum some path all these questions are short dynamic programming questions and you need not to think about any other approach to solve this question it is a classic example of running a program so in my other videos asked about similar questions but there we have like traverse from the first element to the last element and we have built up the DP array which is the concept of dynamic programming to solve subproblems and use those results to derive the final result right but in this case we'll be taking the approach other way round so we will start from the last element and built up the result to the first element so it's the same concept just that it's another approach and I wanted to cover that in this video so let's get started select any other dynamic programming problem we always have to create a DP array at least in most cases we just first get the number of rows and columns okay and then we will create a DP array of the size rows and columns so now we as I said we will just Traverse from the back or end of the array so we will take this equals two rows minus 1 is greater than equal to 0 and I am - - right and then will to 0 and I am - - right and then will to 0 and I am - - right and then will again say J equal columns minus 1 J is more than equal to 0 and J minus - right more than equal to 0 and J minus - right more than equal to 0 and J minus - right ok so now for every element there are a few conditions for example if the element is in the last room ok so from this element right if you want to calculate the DP of this element let's say for example 4 right so there is only one way you can come to 4 that is from 2 correct so we'll just add the value 4 to the DP value of 2 and that will give us the DP value of 4 if it is in the last column then there's only one way for example for the first one there is only one way you can come to it that is from this one right so we just add the DP or value of this one to one and that will give us a DP value for this particular one but in cases of elements like five you can come to five from one and from two because the question says that you can either move down or to the right so if you are doing it backwards right so two five you can either come from one or two or basically from five you can go to one or two so we will use the minimum of the DP of these two and five to it and that will be our value for DB and the last case is the element one itself like the last element of the matrix so there is no element to the down with it or to the right of it and that's why we will just have to take that value as the DP value as well so let's just get started with implementation so if mine let's say if I is the last row okay so rows minus one but pollen is not the last one sorry about that so J right yeah so this is not the last column so in that case as I said we'll just calculate the DP of IJ as we first add the value itself in every case and then so we'll just since it's already the last row we cannot do anything about it that is there is no other row beneath it so the same row but the next column right because you can move from that to this right okay and the opposite of this so which means that if my J is equal to columns minus one but I is not equal to Rose minus 1 correct so in that case just the same but so we still use grid of I and J but we will just we can just go to the next row because Rho is not the last one and the same column because that's the last column otherwise if right if I is not equal to rows minus 1 and J is not equal to it's not equal columns minus 1 as well so in that case for example here it's the 5 element it is neither on the last row nor the last column so what we'll have to do is we'll have to again write equals to grid of I J plus the minimum right because you want to make my son so the minimum of DP of I plus 1 J great comma DP of I J plus 1 that's it and then otherwise the only case left is that the element is itself the last one so we'll just assign it the value of itself okay and then we have to return the DP of 0 okay let's see if that works hmm so the time complexity for this is off M into n and the space complexity is also off M into n because we are using DP array which is of the same size instead of the matrix and we are traversing the matrix also once so yeah that is the time and space complexity I hope you find this video helpful and in understanding a different approach of traversing the matrix and using dynamic programming to solve the question if you do please like share and subscribe and keep coding and thank you guys
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
225
so this question asks you to implement that using cues so we'll start off by describing what the difference is between a stack and the queue so with the queue you'll commonly hear the term FIFO this means first-in first-out FIFO this means first-in first-out FIFO this means first-in first-out and what that means is the first element that was added will be the first one removed so you can picture this as like waiting on a line let's pretend this is the entrance this is the first person to arrive this is the second person to arrive this person's the third and this person's the fourth which one's going to be let in first the one who arrived first and then the next person who arrived right after that and so on and so forth let's move over to a stack is just the opposite it's LIFO so last in first out so with this one you can picture a stack of dishes so these are just let's say four plates stacked on top of one another which we're not you gonna take first you're gonna take the one at the top then you're gonna take the next one that's at the top the next one and the next one all right so just to demonstrate that to you in another way this is the queue over here first elements added second elements added third elements added which one's going to be removed first the number one which one's next the number two which one's the next the number three move over to a stack number one's added first then number two the number three which one will be removed first number oops sorry about that the number three followed by the number two and then the number one all right so back to the question at hand how do we implement a stack using queues they're actually a couple different methods about three different methods but this video is just going to be going over what's called the costly push method there are a couple other methods that I won't be talking about in this video but they're linked down below so how do we actually implement the costly push method with this one we're going to need two different cubes Q 1 and Q 2 what happens is when you add an element you're actually going to add it to the second q then if there is anything in the first Q you empty those out into the second q and then you reverse the Q's so it'll look like this right now we've added the element 1 to Q 2 nothing is in Q 1 so we won't have to empty that out now we just need to switch these two Q's so now Q 1 will have element 1 and Q 2 will be empty this is probably not obvious yet exactly how this works but let me add one more element and it should start to get more clear so we're at this stage q1 has element 1 q1 has no elements let's add another element so okay so the number two number to remember when you add an element you add it to the second queue then you empty out Q 1 into Q 2 so now Q 1 will be empty and Q 2 will have the numbers 1 &amp; 2 now you 2 will have the numbers 1 &amp; 2 now you 2 will have the numbers 1 &amp; 2 now you switch the two Q's so this will look like this will be Q 1 Q 2 is empty so now when you want to remove an element guess which one's going to be removed it's no longer going to be the first element that was added it's actually the last element that was added so before we begin coding I just want to quickly go over what leet code has provided us so as you can see there is a my stack class and it has all the methods that it wants us to implement so here's the push method pushing to a stack just adds an element to the top of the stack popping from a stat just removes the top element of the stack top just shows the element at the top of the stack and empty returns whether or not the stack is empty what I've gone ahead and done is added a queue class and I won't go over all the implementation details of this because that's not what this video is about just know that all code in this video is linked in the description below but we have a peek method and that shows us what's at the bottom of the queue a size method returns how many elements are in it is empty returns whether or not the queue is empty DQ removes the bottom element of the queue and NQ adds an element to the top of it all right so let's start coding the solution remember the first step is to create two new queues so this top primary queue is a new queue and we'll call the second one the secondary queue thank you alright now we get to the push method since we're using the costly push way of solving this problem this is going to be the most involved method but you'll see that the methods after this are very straightforward first thing you do when you want to add something is you add it to the secondary queue so there's that secondary Q dot in queue and where did we in queueing they call it X so that's what we're gonna call it also next step is to empty everything that's in the primary queue into the secondary queue so we'll say while the primary queue isn't empty meaning there's still things in it so while it's not empty there's that secondary Q dot in queue and swelling QE this primary q dot d table I'll go over that one more time so we're checking to see if the primary queue is empty and if it's not we're going to DQ meaning remove the next element in the primary queue and in queue so add it to the secondary cube final step in this push method is to swap the two queues so let's create a temporary queue called temp Q equals stop secondary queue just a secondary Q equals to stop primary queue and then this primary Q equals temp queue so all these three lines do is swap Q 1 and Q 2 or primary queue and secondary queue now as I mentioned before the other methods are going to be very straightforward so now that we've effectively flipped the primary queue all we're gonna have to do is when we want to remove something we'll say they stopped primary queue dot DQ when you want to see what's at the top of it there's stop primary queue stop peak OOP sorry you have to return these things return nets and return these and then want to see if it's empty you would do this primary Q dot is empty and I forgot to return that again so there's just returns whether or not the primary queue is empty and that should be it let's see how we did looks good now let's submit it and all right better than 69% of submissions so right better than 69% of submissions so right better than 69% of submissions so once again if you want to see this code it's in the description below see you next time
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
234
given a singly linked list determine whether this is a palindrome best today's video let's get into it everyone my name is Steve today we are going through a legal problem in 234 palindrome linked lists the problem is very simple and straight for let's take a look given a singly linked list determining whether this is a palindrome for example give my necklace the one and two upper is first because this is not a pendulum in order to be a pendulum this needs to be 1/2 - 1 which is the second example 1 be 1/2 - 1 which is the second example 1 be 1/2 - 1 which is the second example 1 2 1 matches 2 1 in the end 2 matches to you to follow up is can you do this in open time and a 1 space the reason is asking this follower is because a simple a brute force way is then you can take out on extract all of the note values put them into an ArrayList and then compare of course we want to avoid that how can we do that the idea is very simple straightforward as well let's take a look at the slide suppose we are given this singly linked list 1 2 3 1 multiple steps first step we are going to use two pointer technique remember this is a very common and practical and very useful technique slow and fast pointers slow well move half of the speed that's fast pointer moves so why slow moves one step faster or move two steps and the BRIC condition is going to be when the fast dot next or fast dot next is now then we're just going to break out in this case this is a short linked list fast dot max done next is now so we're just a gray new break out and then we'll use a slowdown next use this note to reverse the second half well why don't you reverse the second half so that it becomes 1 2 now what can we reverse the second half then what only have two handles this one is hat one this one is had two one two and one two this way we can compare we can't run the comparison side-by-side comparison to see whether side-by-side comparison to see whether side-by-side comparison to see whether the two link to let whether the two nodes values and exactly the same so that we can determine whether the original linked list is a palindrome or not because the reason we do this there is the whole reason we need to reverse the second half is because for a singly linked to list again it only has every node only has one next point is which is pointing towards its immediate successor so in order do you know it's immediately predecessor we have no idea how do you know that's the whole reason we need to reverse the second half so that we can do the side-by-side comparison we can do the side-by-side comparison we can do the side-by-side comparison that's the idea then what is the run-through had one towards the right run-through had one towards the right run-through had one towards the right had two towards the left which is two side-by-side comparison to see whether side-by-side comparison to see whether side-by-side comparison to see whether this is a palindrome linked list that's the idea now let's put the idea into the actual code let's take a look let's note copy this first step or check if this head node is now this is a corner case if now what is considered it is a panel and then we'll have to note one is fast we'll start from hat and the other is slow and then if fast dot next not equal to now and fast dot next not equal to now this is the break condition we want to move two pointers fast and slow towards the right faster is moving at that twice of the speed up the slope owner so fast how can we do that what do well so fast one just move twice and then slow will move only once so that faster is always moving twice the speed of the slow pointer so at this point where we are now so back to the slides what at this position right so we need to reverse the second half so we'll use slow dot next that's the one that we're going to reverse see we'll call it second half and then we'll write a function to reverse it's no dot next we'll reverse this one and then we'll have another node first this case we can just assign capture it and while none of them is now not equal to now and this first half not people not equals to now this is exclamation mark if neither one of them is now then you can just do comparison see carries well not equals no not equals to you second half something now we're just to return false because this is the point where we detected the two node values are not equal so it's not a pendulum otherwise were just to keep moving both pointers next and the first is here in the end or just to retention because we finished ringing through both halves then we know this is a palindrome all right now we need to implement it this private function let me copy in this list node helper function to reverse asynchronous the list a node as we have gone through the linked list of basics we know just a template a routine code how do you regret use a simple dummy code or just call it new hat that's fine to initialize it with now while hat not equal to you now remember the four steps so first what we're gonna do to do is that we'll initialize and temp variable which is called next to hold the current hands next level and then it's safe to you reassign hat dot next to what to the new hat right we want to point that point the current had next point it was the new hat that's the way to reverse it and then we'll assign new hat to be a hat and that means we'll keep moving towards the right and then hat will become the next or just assign next towards the Hat in the end we'll just return the new hat that's it that's the entire algorithm now let's hit submit and see oh I need a return type listen Oh all right accepted that's the idea to determine to write a program to determine whether the singly linked list is a palindrome the time complexity of this algorithm is o n because we have to traverse through this linked list and space complexity of this algorithm is o 1 we're only using a temporary boat to simply reverse it to reverse it first to reverse it and then we'll do the comparison that's it so this way is meeting the problem requirements which is asking us to do this in open time and O one space if this video helps you to understand it just do me a favor and destroy the like button that's going to help a lot with the YouTube algorithm as we're going through link to list series of problems to help everybody better prepare for the upcoming coding interviews and don't forget to subscribe to my channel after this we'll go through three serious problems and then a combination of different data structures and algorithms so tap the little bound on vacation so that when next time I publish a new video you're not going to miss out on anything that's it for today's video I'll see you guys in the next one
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
11
hey everyone welcome back and let's write some more neat code so today we're going to be solving leak code 11 container with most water so we're given an array of heights so this is a height 1 this is i 8 6 so on and using these heights we want to see what's the biggest area we can form with a container that has a left height and a right height so in this example you can see that if we take this one with a height of eight and this one with a height of seven we can create an area let's see how wide this is at one two three seven wide and seven tall so that's seven by seven and the area is going to be 49 and they tell us that much in the explanation so since we're given a list of heights and we want to maximize the area we can potentially just take every single combination right so check every left pointer and every right pointer so my first thought with this is what's the brute force way what's the easiest way to solve this problem well let's just try every single combination of left and right let's just try every single possible container we could make and see if it works so let's say this is our left and this is our right what's the most what's the max area we can make with this well let's fill it up to 1 and if we keep filling it up with water notice how it's going to spill to the left right so this left pointer is our bottleneck right we have a height of 1 and we have a height of seven the minimum one is one so you know we can't fill it up any higher the width of this is also one so we get a we get an area of one by one with water and of course if this one remains our left pointer we can try this one as our right pointer and in this case the width is going to be two but the height is still going to be one our remember our left height is only one so our bottleneck is one so we get an area of two by one so i'm starting to notice a bit of a pattern but let's just keep continuing with the brute force so next we can try this area that's going to be three next we can try this area that's going to be 4. next we try this one that's going to be 5 and we can just keep going the height is going to stay 1 because our left pointer has a height of 1. next we move our left pointer here and again we're just going to continue with the brute force solution eventually we're going to have our right pointer set here and then we're going to find our result right it's going to be 7 by 7 that's the biggest area we can do and since we're checking every single combination we know we're eventually going to find the correct solution the only downside is that this algorithm is big o of n squared now is that good enough i guess it depends on your interviewer and let me just quickly code up the solution for that so this is the brute force of n solution let's first initialize our result which is our area i'm going to initialize it to 0 because you can't really have a negative area at least not in this context and we want to go through every single combination so i'm going to have our left pointer go through every single indices of height so i'm going to get the length of height which is our array so left is going to be at every single position at least once now right pointer we can just have this one be always at least one position ahead of left so left plus one because it all our right pointer of course always needs to be to the right of our left pointer right and for each of these combinations we want to compute the area so let's do that area is going to be equal let me just remember how to i don't know about you guys but sometimes even i forget how to compute the area of a rectangle so we're going to do width times height so the width is going to be right minus left multiplied by the height now how do we find the height so how do we find the height remember we're focusing on what the bottleneck is and by bottleneck in this case we mean the minimum height because no matter how tall our right no matter how tall one of the heights is right we could extend this to a million but look how small this one is it's just too small the water is going to spill out so we care about the minimum height of the left and right pointers so let's get that minimum so minimum of height of left and minimum of height of right so now that we've computed the area remember we want the max area so we can set our result equal to the max of itself and of the area that we just computed so every time we compute an area if it's the max we're going to update our result and now all we need to do is return that result that we computed let's see if it works unfortunately it doesn't work we got time limit exceeded so now we need to figure out how we can make this a little bit better can we get a linear time solution so now let's take a look at the linear time solution the one that will actually work in late code so remember how we said that the minimum height is our limiting factor we really don't want small heights so let's see if we can try a two pointer technique now i'm gonna initialize the left pointer all the way at the left and i'm going to initialize the right pointer all the way at the right why because we want to maximize the area so why would i initialize them like because we want the width to be as big as possible because if this left height is super tall and this right height is super tall then we've instantly found our result but of course in this case that doesn't work we get an area of 1 by 8 i think so that's obviously not the result so what do we do how do we update our left and right pointers so the first area that we computed was an 8 which is our max because our initial max because this is basically the maximum so far so now how are we going to update our pointer well we're going to look at what's the minimum height this one has a height of one this one has a height of seven so why would i shift my right pointer when it has a height of seven when i could instead shift my left pointer which has a height of one and potentially increase it so now left is over here and we have a height of 8 and lucky for us we've basically found our solution but i'm just going to keep going with the algorithm just to kind of show you how it works so now we have an area of seven by seven which we know is 49 so our max area gets updated our max is no longer eight it's 49 which we know is the correct solution next i'm gonna take the minimum of eight and seven is smaller so we're going to shift our right pointer to the left now our right height is looks like three so the area that we're going to compute is going to be 3 by 6 which is 18 but that's too small that's not bigger than our maximum so we don't need to update our max area now our minimum is 3 so we're going to shift now we have an 8 by 5 rectangle which is 40 but that's still not greater than 49 and now we get to a nice little edge case where both of the values are equal in this case it doesn't actually matter which pointer that we shift but if you wanted to you could shift the one that has a larger height coming like for example like this height is at six whereas this height is at four we could choose to shift this one just because we know that a larger height exists over here but it actually doesn't matter you could shift either one so now our left is six so we get six by four which is 24 too small we don't care about it let's just keep going so now our minimum height is six let's shift our left pointer now we get a two by three rectangle which is too small let's shift our left pointer one more time hey this time we got a five by two that's a little better than before but still not better than our max and so this is basically the last rectangle or water container that we can form it's going to be four by one and now if we try to shift our left pointer we get to the terminating condition we get to the condition that's going to end our code so now that we shift our left pointer here we're going to get our left here left and right are at the same position so let's get rid of this let's get a solution that can actually work on leak code and maybe you might need this solution in your interview if the brute force is not good enough so once again i'm going to set our result equal to zero i'm going to do what i did in the explanation our left pointer is going to be initialized all the way to the left which is zero and our right pointer is going to be initialized all the way to the right so these values are zero and length of heights minus one and remember our condition for the loop is while left is less than right because if they're equal that's no good and if they if left passes right that's no good either so let's compute the area again i'm just going to copy and paste it from my above solution because that's what the brute force solution is for right you can learn the basic problem the basic parts of the problem before doing the clever stuff i can also just copy and paste the part where we update our result as well now the part that we have to change though is when we're updating our left and right pointers we're doing it based on a certain condition if the height at position left is less than the height at position right we're going to shift our left pointer to the right we're going to increment our left pointer because we want to maximize both of these heights now the other condition is the opposite case so if height of left was greater than height of right then we would want to shift our right pointer and we want to decrement it and the last case is if they're equal right that's our else condition and remember how i said we could do either one if uh if they're both equal right we could increment our left pointer or we could decrement our right pointer uh notice how both of these are doing the same thing so i'm just going to condense this i'm just going to get rid of these two lines of code now all we need to do is return the maximum that we computed let's see if it actually works this time okay of course i had a typo so i had a s at the end of heights let's run it one more time and this time it'll work so this is the actual linear time solution the big o of n solution as always thank you so much for watching like and subscribe if this was helpful and i'll see you pretty soon you
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
138
hey everyone welcome to Latvia coding today we are going to soft than 38 communists with random pointer and we can see this is a really commonly asked interval question let's see the question together so a linked list is given such that each node contains an additional random pointer that can point to any node in the list or nothing copy this linked list with random pointer so yeah this is the question this diagram is a little bit a messy but we can still see that um the additional pointer point to another note and we have to restore the structure in our ask in our output so how do we solve this problem let's walk through our algorithm okay so let's simplify our problem if we don't have a random pointer then things becomes even right we just need to UM create a dummy node and then traverse the linked list and copy every node and connect them to four three it's easy but what if we have a random pointer in the original or list um for example if don't while also have another pointer that points to note 4 then when we are creating note while we don't know where is the note 4 right it is not created so this is the problem how do we solve it what if note 1 has an additional pointer that point to note 4 when we are creating note 1 the note 4 is not created right so we don't know where is the note 4 this is the problem how do we solve it might be not quite intuitive but let's do another data structure hashmap we map each node from the original list to the copied list the key is just the original note and the value is the copied note and then after we are creating this data structure then things becomes I either so from note one we can find the new note 1 and then from Northwest random pointer or we can find note 4 and since we know the address of the new node we can connect not one with note 4 and we can do the same and when we are going to node 2 we find a new node 2 and we see that the random pointer of note 2.2 see that the random pointer of note 2.2 see that the random pointer of note 2.2 nothing so we point so a point new node to strengthen pointer to nothing and by doing this we restore the original data structure the kissing's is said we need to use a hash map to store the address of the copied node so yeah this is the algorithm let's code it coded you we need to create a dummy pointer and less just set the value to zero and then current no this had y au courant is not what we do we create a new node you and then in the hashmap we met the curves node to the new node so we are building this bridge you and then we also need to build this bridge right because it's a linked list you and then we increment the current pointer yes this is our first step now we have no random pointer created this is just a linked list map to the copied list then let's traverse the linked list again to set the random pointer so you we get the random pointer of the chorus node and if the random pointer is not null we find a cockade random node and then we just set the random pointer otherwise we set it to none you then we just need to return the result of next because the result still points to the dummy note you now we create this structure so let's run our code so we make a few modification here this is hashmap and we also need to increment the current pointer so let's run our code yes it's correct and before submit our solution let's run it again mentally to make sure we really understand it so first we need to create a dummy head we call it dummy and then in the first iteration what we do first we create a new node and we also map the earth note to the new note and then we pointer then we move the dummy pointer to the current node and then we move to next node and we do the same thing we create the note and we attached the note we connect a copy node and then is for then we do three we map three and we connect four to three and then we connected to nothing so this is our first intuition and then in the second iteration we go to the current head again and we find the copied node here and we get the random pointer of the head node is for if it is not none then we followed the map and find the Kabat node 4 is here and we connect the copied note to his random pointer and then we do this thing again we go to 2 we find a copy node of 2 and we know that it is null so we just set it to null and then we just need to return the dummy node of the next so yeah let's now submit our code yes is correct and less analyzed time-space complexity so let's analyze time-space complexity so let's analyze time-space complexity so let's analyze our time-space complexity the time our time-space complexity the time our time-space complexity the time complexity is indeed linear because we traverse the linked list twice and face complexity is also linear because we use a hash map okay that's it thanks for watching a code is in the comment below if my solution helped you please feel free to subscribe and leave a comment thank you
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
1,962
Hello everyone and welcome question, nowadays we will get minimize d total as if it is mixed and we have to do some operations by doing exactly number of time operation. What is the operation to be done, you have to choose any one number, any one file is there, it basically contains stone. This is the file, now you have to select it and halve it and then add it to it. How many number of times can you do? The number of times is fine. I will explain the example once and hold it. Divide it by you. After doing this, add the floor which is there in the sim again and you can do this twice, right, like I hold the punch, divide it by two, now whatever I divide, it will be 2.5, right or the integer will be divide, it will be 2.5, right or the integer will be divide, it will be 2.5, right or the integer will be 2, then its floor will be three A. Isn't it true, if I set this 3 again then instead of five, three A will come out, that will be 329, its total will be the minimum, which one is the operation to be done, divide five by five, find out the floor by dividing nine. Take out the floor, right, as we are told in this, then I will pakadunga and halve the maximum three in the starting point, like grab the 7, grab the sex and grab the four, then we will have to find the largest elements by grabbing them. That's it, now 6 is 7, so now what we have to do is to catch the biggest element, then you have to do it, then after a second, you have to do it, then you have to halve it, then the next one which is bigger among them, you will halve it and put it. Brother, these four will come here, now these four are not necessary, it is not necessary to hold them, now what will we do out of these, what will we do, we will make a maxi in it and what will be less than the maxi, let's have, I will take out all of them, then the biggest element will be outside. Now whatever operation we want to do on it, we will do it, after that we will send it here, then you must have read in the sheet that we will go out to catch the next big element, after halving it, we will send it back here again. So basically this is a very basic question of hip, you will have to do it one by one. Take out the elements of K and keep adding them by halving them. For how long do you have to do this. Do this number of times as many times as you want to do. Then we give K - - = greater. We will reduce the we give K - - = greater. We will reduce the we give K - - = greater. We will reduce the elements to zero and then halve them again and add them. Okay, so first of all, what we have to do is we have to add all the elements found in the arrangement. Let's create a priority on this, so let's go create priority why of interior and keep them in piles, okay. Now what does everyone have to do who will do the operation? First what do we have to do? The number of times operation A Minus take out the one that is on the top. Now we have to do floor so math dot floor we can do and divide by tu like here. If you do this, then it will be equal to the pole, like if you take out 14, then divide by, what will you get, 7 will directly get its floor, but now if you do 13/2, then anyway you will get 6, whereas do 13/2, then anyway you will get 6, whereas do 13/2, then anyway you will get 6, whereas what is the floor, it is seven. So if I add one to it, I will already make it 14, so you will get 7, so the method is this, you can do it by direct method, floor dam, what will it do, you will divide it and give you floor, I have made more, what should I do? Have and every time Elements have been done I I I reduce it, I make it Perfect again what did we have to do, that is lying there and take it out After adding 1/2 crore So thank you See you for watching in the next video
Remove Stones to Minimize the Total
single-threaded-cpu
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. **Notice** that you can apply the operation on the **same** pile more than once. Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_. `floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down). **Example 1:** **Input:** piles = \[5,4,9\], k = 2 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[5,4,5\]. - Apply the operation on pile 0. The resulting piles are \[3,4,5\]. The total number of stones in \[3,4,5\] is 12. **Example 2:** **Input:** piles = \[4,3,6,7\], k = 3 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[4,3,3,7\]. - Apply the operation on pile 3. The resulting piles are \[4,3,3,4\]. - Apply the operation on pile 0. The resulting piles are \[2,3,3,4\]. The total number of stones in \[2,3,3,4\] is 12. **Constraints:** * `1 <= piles.length <= 105` * `1 <= piles[i] <= 104` * `1 <= k <= 105`
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
Array,Sorting,Heap (Priority Queue)
Medium
2176
39
so you want to solve combination sum what does it even ask you given an array of distinct integers candidates and a target integer target return a list of all unique combinations of candidates where the chosen numbers sum to target you may return the combinations in any order the same order may be chosen from candidates on a limited number of times two combinations are unique if the frequency of at least one of the chosen numbers is different it is guaranteed that the number of unique combinations that sum up the target is less than 150 combinations for the given output input so actually this line is completely irrelevant so let's just take an example seven can be done with two plus three or seven or eight can be done with two plus two or two plus three or three plus five here you're given a target of one and your only candidate is two so you can't make one and candidate one so you return one two can be done with one plus one okay so how do we even find that the first thing we do is we come up with our return vector which we call my return and that's what we're gonna return my return now we just need to fill up this um this uh my return vector of vectors in some magical way so my return and then we're going to send in the current vector we might want to throw in our candidates we might want to throw in our target and uh the position would be zero and i think that's probably all we need now let's come up with that fill combinations function so we're going to be passing my return by reference so let's just copy all of this so this is going to get filled up as we recurse in my return so this is a classic back tracking problem and we're going to figure out why in two seconds also we have our current vector um we have the candidates which we're going to pass by reference just the same way it was given to us we also have the target as well as um the position and actually i think we could pass some of those by reference as well or const reference specifically um constant yeah const reference so okay so let's see how we go about this the first check that we have to do okay so we're going to be calculating these numbers we're going to be decrementing um eight from the value so for example let's say we echo we decrement two from eight we're going to get six and then we pass in two again we get four and then two we get two and then two again we get zero so what we want to do is check whether our target actually equals zero that means we got somewhere so if target equals zero then well what we do is we push back our current numbers and we return so we only get that when we reached our target now if target less than zero then we return and what does this even mean that means that as we're decrementing if eventually you hit uh you know a nine or something and you used up that number you know that you're going to get something less than 0 because 8 minus 9 equals minus 1. so let's just air that out a little bit and then it comes the meat of the problem so we're going to iterate over candidates but in such a way so i starts at our position and i smaller than candidates dot size and then i plus now we want to add to the current dot push back candidates i and in between we're going to pop back whatever we inserted there but in between this kind of sandwich of pushing and popping we're going to recurse and how are we going to do that so we're going to throw in my return again we're going to throw in current we're going to throw in candidates now the target is target minus so candidates keep on writing canada that's because you guessed it i'm canadian um next comes position and that would be i yeah so the only way that it kind of moves up with position is uh through the iteration here and it stops going deep inside the candidates as soon as it hits a wall meaning it added something it's not supposed to so then it comes back and you're back to your original position and you could continue iterating down this uh down this loop so let's see if this works and our survey says yes and we submit and we got it going thanks again everyone
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
1,784
hey everybody this is larry this is me going with q1 of the weekly contest 231 checking the binary string has at most one segment of ones so i think this is a i don't know if you know hit the like button hit the subscribe and join me on discord but let me know what you think about my solution even though i actually like my solution though i probably could even clean this up but during the contest i just didn't want to um yeah because yeah i think you could buy off the grid buy and that would be yeah or maybe you could do a frequency table or something like that but basically the idea i mean you there's a lot of ways to do it i'm not uh explain i'm not going to explain this problem because it i think the understanding is pretty straightforward for this problem you're just trying to count the number of segments at once so what i did wise is i did a good buy uh this is the number that is grouping value from and if it's one we just increment the count and then at the end we return right at the counter to go to one um this is gonna be linear time mostly dominated by the grid by and constant space um i guess technically there's a linear spacecraft group by also returns a list of the things that is goodbye but you could do it better it's just that uh you know i wanted to do it really quickly again even though i did this a little bit slowly as well in any case but yeah let me know your solution this is you know pretty straightforward but you know let me know uh and you can watch me sub it live during the contest next okay hmm that's not true okay fine okay hey uh yeah thanks for watching let me know what you think about this prom explanation or whatever uh hit the like button hit the subscribe button join me on discord and i will see you next time bye
Check if Binary String Has at Most One Segment of Ones
minimum-initial-energy-to-finish-tasks
Given a binary string `s` **​​​​​without leading zeros**, return `true`​​​ _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`. **Example 1:** **Input:** s = "1001 " **Output:** false **Explanation:** The ones do not form a contiguous segment. **Example 2:** **Input:** s = "110 " **Output:** true **Constraints:** * `1 <= s.length <= 100` * `s[i]`​​​​ is either `'0'` or `'1'`. * `s[0]` is `'1'`.
We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern
Array,Greedy,Sorting
Hard
null
1,176
hi hello today we'll talk another sliding window question this question is diet plan performance let's see what this question is all about all right so this question says there is a dieter that person consumes calories every day so suppose on day zero he consumes two calories three on the first day and so we have to tell the score point so on k consecutive days if the consumed calories are less than our lower limit we will give him -1 if the lower limit we will give him -1 if the lower limit we will give him -1 if the consumed calories are greater than the upper limit will give him plus one if the consumed calories are within the range in that case we give him zero point considering these are the provided rules considering these rules we have to tell at the end what how much point he has scored so we have to tell the score points now considering all these provided things let's see if we can apply some coding pattern they have given us an array there is they're expecting a score point so score point will be something like an end and how we will calculate we have to calculate like in k consecutive days we have to apply some rules on those case k consecutive days whatever consumed calories we have applied these rules and then we get some points that accumulated we have to return at the end now considering all these given things we can see that ray there's a point which is being calculated within k consecutive days looks like a window of size k and there are some rules that will apply on the case size window so we can definitely apply a fixed size sliding window now how we will implement so let's take some example uh let's keep it here so let's suppose we have some calories now in these calories let's suppose the case size is equal to three so we were talking about a window of size 3. so once we have that window we can calculate whatever the consumed calories in these days so we will apply the rules what was given and on applying these rules we will calculate points we have to give him either we have to provide a minus one we have to give him plus one or he score zero and at the end we will just return the answer by summing them all so each move of this window let's suppose it moves next so we get three points again that's a possible candidate we'll apply the rule we'll consider either we have to give him some points and no then again we will slide them in the further on the these three consecutive days with whatever the consumed calories will apply the rule and we'll see that does he score the point and though now talking about the coding template what we'll use we will again use the same coding template which will be our calories and we will zip with index we will fold left and here we will consider zero index that will be our left pointer how much uh calories he has consumed in k consecutive days we will consider zero and how much points it has scored we consider zero and in after the pattern match we can say this is left that is consumed and these are the score point and here we will give that these are the calories for today and that will be the right pointer and then finally what we will do we will implement our rules here and by calculating all the applying all this rules we will just return the answer at the end that's it that will be the pretty simple solution this is the same what we did in the previous question let's go to the code and see how we can solve this welcome back so we already know that we can solve this problem using fixed size sliding window coding pattern how we will implement we already know the coding template we'll say calories dot zip with index dot four left and here we'll say the left pointer will be on index zero and consumed calories all you consume calories within k days will be zero initially and points chord will be zero now we will move forward here we'll patch and match we'll say this is left that will be consumed calories and these will be the points which he has scored so it is just pattern match zero for left zero for consume zero for point and we will say calories of the current day and that will be the right pointer that's it now what we will do first we will get the window size which will be right minus left plus one and now we will calculate new consumed calories which will be consumed plus cal calif today now once we have got the new consume and window size we can compare the window right now we have is it equal to k consecutive days or no if it is not reach the k consecutive days what we will do we will keep the left pointer there and we will say these are new consumed and the point will remain same because we never apply the rule yet and here we are going to apply the rule is very simple we will calculate the new point in the new point it is simply that calculation when we say that if new consumed is less than because we have reached the window size now we are going to apply the rule we say if new consumed is less than lower than point -1 and if we say point -1 and if we say point -1 and if we say else if new consumed is greater than upper so the dieter has consumed calories which was upper greater than the upper limit we give him 0.1 0.1 0.1 and in the else part if the calories consumed or within the range we will just keep returning the same point here we are going to shift the window we are going to slide the window right so we will move the left pointer one step ahead and we will say new consumed we will minus the calorie of the left index day because we are shifting the window so it will we have to minus the calorie of the left pointer so we'll say calories add left index and here we will just provide the new point and finally once we have done everything we will return underscore three which will point the point so this is one this is two and that's three so we return at the end number of point which he has scored let's run the code that's it works really thanks
Diet Plan Performance
design-a-leaderboard
A dieter consumes `calories[i]` calories on the `i`\-th day. Given an integer `k`, for **every** consecutive sequence of `k` days (`calories[i], calories[i+1], ..., calories[i+k-1]` for all `0 <= i <= n-k`), they look at _T_, the total calories consumed during that sequence of `k` days (`calories[i] + calories[i+1] + ... + calories[i+k-1]`): * If `T < lower`, they performed poorly on their diet and lose 1 point; * If `T > upper`, they performed well on their diet and gain 1 point; * Otherwise, they performed normally and there is no change in points. Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for `calories.length` days. Note that the total points can be negative. **Example 1:** **Input:** calories = \[1,2,3,4,5\], k = 1, lower = 3, upper = 3 **Output:** 0 **Explanation**: Since k = 1, we consider each element of the array separately and compare it to lower and upper. calories\[0\] and calories\[1\] are less than lower so 2 points are lost. calories\[3\] and calories\[4\] are greater than upper so 2 points are gained. **Example 2:** **Input:** calories = \[3,2\], k = 2, lower = 0, upper = 1 **Output:** 1 **Explanation**: Since k = 2, we consider subarrays of length 2. calories\[0\] + calories\[1\] > upper so 1 point is gained. **Example 3:** **Input:** calories = \[6,5,0,0\], k = 2, lower = 1, upper = 5 **Output:** 0 **Explanation**: calories\[0\] + calories\[1\] > upper so 1 point is gained. lower <= calories\[1\] + calories\[2\] <= upper so no change in points. calories\[2\] + calories\[3\] < lower so 1 point is lost. **Constraints:** * `1 <= k <= calories.length <= 10^5` * `0 <= calories[i] <= 20000` * `0 <= lower <= upper`
What data structure can we use to keep the players' data? Keep a map (dictionary) of player scores. For each top(K) function call, find the maximum K scores and add them.
Hash Table,Design,Sorting
Medium
null
1,605
Hello Hi Everyone Welcome To My Channel It's All Related Problem For Invalid Matrix Giving Row And Column Sums So You Are You Rate Tours Roshan And Columns Of Negative Interior Roshan Fi System Of This Element India Through And Column Of J Is This Period Element Of Baje Jogging Column of Today Matrix in Words You Don't Know the Elements of Matrix But You to 9 and Tricks of Native in Tears in His Eyes rosban.su rosban.su rosban.su rosban.su rosban.su rosban.su rosban.su rosban.su rosban.su Requirements and Requirement Guarantee Requirements for Example for Kids This Is After Prof Me To end the number of history and finally Bigg Boss to be happy generator tourist places early morning puja letter to draw matrix subscribe and 04 and one this is the giver input subscribe and subscribe the Channel minimum element in elementary subscribe Chameli Apni Circulation B0 Selection Top Three and Four Will Decide Soft and Cheesy Minimum Three Minimum Show Will Feel Three Edison Birthday Flight and Minimum Like Zinc Row and Column Midfield Thriller Film The Three Is Now School Ko Subscribe Listen Subscribe Set List Will Give a Row and Column Which Already Subscribe Ro End Column Will They Will Fight With You To Tigro Android User ID Ro Lyxeji All Will Not Give The Minimum 900 To 1000 Before Election And Half Of The Entry Of The Thing Will Keep Distance And Share Subscribe 317 So Let's Understand With Example To Fans Subscribe Matrix In This Rosary 200 Dengue And My Drawings Not A Good Srishti Matrix And Have Roshan 5 To 10 And Equal Committee 6069 Subscribe Maintain Set For The Next Five Years Will Be Road Similarly You Will Be Amazed And The Huntsman Is Hair Ki And Skimming Ko Lambi Shyamali Swimming Rose Essence 2009 2013 Ukti Ko Lamba Is The Meaning Of This Is Vivek Oberoi And Subscribe To 210 Ghosh Bill v11 Here One More Thing Has Been Already Used Jeevan And Saunf Just This Is The Like Subscribe And Share And Subscribe From First Appointed Roll number to everyday intercourse similarly in the world and also need to know which will result in subscribe now to set that in teaser aa laharon set record to new haircut a nerve cell copy paste also been maintained its effects which will maintain and share no Will run over's last ball side line mid size is not equal to and that NDC set alarm on Saturday New York column and not rise not equal to a I soft and will get too fake minimum index of very row and Rome indices of chief force call 100 More Similarly After Getting Water From Roshan Fiber Glue Quantum Of Dividend Will Be Rs Chief Sequence To Roshan Is That And Also Been Set Up Track That Rosafe Arises From Also Call 100 CID Call 100 CR - Sequence Roshan Of This Subject And Also CR - Sequence Roshan Of This Subject And Also CR - Sequence Roshan Of This Subject And Also Will Updates Subscribe Must Subscribe Like and Subscribe To What Happened By The Full Form Of I So - What Happened By The Full Form Of I So - What Happened By The Full Form Of I So - Equal 100 CR Nobs Induced Into The Middle Of Nowhere To Return To Be Placid On What Will You Get Into The Middle Of A Lake Pisser That and this set top interior the indexes data lady use they want freedom in intermediate sohan sirvi dot max that balu absolute will return from 0 and Thursday nine middle aged plus from this like and subscribe I will update amused and subscribe and turn on the subscribe hour Do Hitesh Akshar Tissues Solution India Contest Late Evening and Optimism and Decisions Like and Subscribe My Channel Thank You
Find Valid Matrix Given Row and Column Sums
minimum-number-of-days-to-make-m-bouquets
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of **non-negative** integers of size `rowSum.length x colSum.length` that satisfies the `rowSum` and `colSum` requirements. Return _a 2D array representing **any** matrix that fulfills the requirements_. It's guaranteed that **at least one** matrix that fulfills the requirements exists. **Example 1:** **Input:** rowSum = \[3,8\], colSum = \[4,7\] **Output:** \[\[3,0\], \[1,7\]\] **Explanation:** 0th row: 3 + 0 = 3 == rowSum\[0\] 1st row: 1 + 7 = 8 == rowSum\[1\] 0th column: 3 + 1 = 4 == colSum\[0\] 1st column: 0 + 7 = 7 == colSum\[1\] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: \[\[1,2\], \[3,5\]\] **Example 2:** **Input:** rowSum = \[5,7,10\], colSum = \[8,6,8\] **Output:** \[\[0,5,0\], \[6,1,0\], \[2,0,8\]\] **Constraints:** * `1 <= rowSum.length, colSum.length <= 500` * `0 <= rowSum[i], colSum[i] <= 108` * `sum(rowSum) == sum(colSum)`
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
Array,Binary Search
Medium
2134,2257
270
welcome back everyone we're going to be solving leeco 270 closest binary search tree value so we're given the root of a binary search tree and a Target value we need to return the value in the tree that is closest to the Target so we're given a tree of four two five and one three and a target of 3.71 right and one three and a target of 3.71 right and one three and a target of 3.71 right we should return the node value of 4 because that is the closest um value to our Target right so we're working with a tree so we're gonna have to use some sort of traversal algorithm I am going to use a breadth first search all right so I'm going to implement or I'm going to import our queue from our collections Library so from collections import DQ okay now let us get that cue set up DQ and we will add the root on we're also going to have some sort of way to check how close a node's value is to the Target right so let's set up a variable called difference and we will initially set it equal to the float value of positive infinity and let's do the same for the node value that we want to return right because not only do we have to keep track of the difference they want us to return the node value so we're going to remember the node value when whenever we update this difference we'll also update this node value so we'll also set this one to float of positive Infinity and we will run this Loop right we want to Traverse all the nodes and find the closest difference so we'll say while the length of our Q is not equal to zero meaning we still have nodes to Traverse we are going to say our current node is going to be Q dot pop left now we're going to check and make sure that node is not null we do that by saying if node is not none what do we want to calculate the difference value and we're going to say it is going to be the absolute value of our Target minus our node value now what do we want to potentially update our difference and we can do that by saying if the difference is greater than well what are we looking for we are looking for the minimum so it should be less than if the difference is less than the current difference and let's just say what do we want to do here we could just say this let's make it easier so if the absolute value of the target minus the node.value is minus the node.value is minus the node.value is less than the difference then we want to potentially update our difference fix some spacing here okay now what do we want to do whenever we update this difference we also want to keep track of the node value that we just calculated the difference from so we can set node equal to node.val and let's change this to node.val and let's change this to node.val and let's change this to uh result node so we're not reusing variables okay now once we've done this or potentially have done this we still need to Traverse the rest of our nodes right so now we just need to check if no dot left is no we need to add it to our queue and we need to do the same thing for the write node right and the right okay now we should be able to return the resulting nodes value and let's get rid of some spaces here we'll run this and it does pass both test cases so let's submit perfect it passes the submission tests awesome so what is the time and space complexity for this problem the space complexity is going to be bound to the length of our Q right it can grow to the length of however many nodes we have so that is going to be o of n and the space or the time complexity is going to be um let's see here it is going to be o of n where n is the number of nodes we have to Traverse all right that'll do it for leeco 270.
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
967
welcome to another video in the graph series today's question might make you go like how will I realize that this is a graphs question and I completely get it but it is better to learn while practicing than make mistakes in the interview correct and once you do two three of these questions you will get the intuition and you will start thinking in this direction I know right now you know that this is a graphs question because it is in the graph series but I will explain you how you can think of these questions and it's a very good question to be asked in an interview because it is based on a very simple basic graphs concept but it will make the interviewer see that whether you can see and you can think in a particular direction or not or will you freak out and leave the question so this is a very good question to not leave it and I will be writing the code in both C++ and Java let's get started before we C++ and Java let's get started before we C++ and Java let's get started before we move ahead I would just like to take a moment to remind you to be consistent and make sure you do not miss any videos in the graph Series so make sure you subscribe hit the notification Bell icon you will also stay motivated and you have no idea how much your support will mean to me there's so much of free content available on the channel there's hld lld DSA Advanced C++ tutorials mock hld lld DSA Advanced C++ tutorials mock hld lld DSA Advanced C++ tutorials mock interviews and so much more so if you think I deserve your support Please Subscribe hit the notification Bell icon and there's obviously a bunch of stuff that I cannot do on YouTube like mock interviews live interactive classes so we have educ we have live we have educ we have live we have educ we have live courses self-based courses with live courses self-based courses with live courses self-based courses with live doubt solving support which both of them we have mock interviews and we have a lot planned in lld hld advanc C++ DSA lot planned in lld hld advanc C++ DSA lot planned in lld hld advanc C++ DSA and so much more you have no idea so if you want me to be part of your further Learning Journey process please check it out the link is in the description and now let's continue so this is the question that is given to us note that nowhere we are given that it is a graph what is given to us we are given two integers n and K what does n and K mean here it is given we have to return an array of all integers of length n so here you can see the length of every number in this array is n here it is 3 here it is 22 222 okay so we are given n we understand the meaning of n difference between every two consecutive digits is K so you can see the difference between 1 and 8 is 7 2 and 9 is 7 8 and 1 is 7 similarly here 1 and 0er is 1 and two is one so difference between every two digits in a particular number so this is one number difference between any two digits is basically equal to K we may return it in any order now I know like once you look at the question you might get stuck that how do I even approach this question so one thing that you really have to absolutely ingrain in your head it is that DSA has very limited number of topics they cannot come up with a completely new topic all of a sudden like that okay so what are the limited number of topics there's recursion there's DP there's B sour there's Windows sliding technique there's trees graphs and things like that right so we start thinking can I form a s search space can I do binary search or uh you know can I do windows sliding over here or can I form any relationship to maybe go ahead with tree and graph let's think about it so if you see the first numbers over here okay so the first number can be 1 2 3 4 5 6 7 8 9 it can be anything the first digit in any number the first digit here you can see it is one then it is two then it is three then it is four so suppose we fix any digit right because we have to return all the array of all the inte es where these two conditions are met okay so to consider all the possible answers where these two conditions are met the length should be n and the difference between the digits should be K okay so we know that the first digit can be anything now we also know the relationship between the first digit and the second digit whenever we have a relationship okay some sort of relationship so basically it is like what it is like these two digits could be nodes of a tree or a graph and this relationship that the difference is this K will be the edge will be the connecting Factor now the question comes is it a tree question or is it a graph question so how would we understand that let me repeat so first thing that we understand is that the first digit in the numbers can be any digit it can be 1 2 3 4 5 6 7 8 9 and then we have a relationship between the first digit second digit and so on so maybe we can do trees scraps we will analyze this more but also you have to start thinking of edge cases also so when we form integer when the starting digit is zero it is a special case right because what does 02 mean is it two only is it possible to add zero in the starting know that in questions in lead code it might be given to us like over here it is given that you should not have leading zeros so the first digit should never be zero it can be 1 to 9 anything it can never be zero correct now in interviews you have to ask these questions these might not be mentioned and that is why a lot of interviewers give you half information they do not give you the entire information you have to think like this so whenever an integer question is given to you always have to think of zeros can zeros be in the starting can it be in the end can it be middle what is like maybe the sum can be zero so you always have to think of zeros we always have to think of negative numbers and things like that these are the common cases you will get used to them as we practice more okay here also one more thing note that we can start from 1 to 9 but here we are not always starting from 1 to 9 there are some scenarios suppose 3 4 5 6 we are not starting any numbers with 3 4 5 6 why is that why are we not starting so let's think of that as well so these are the two examples that are given to us we already discussed that each digit can be a node so let's try forming that uh suppose I form nodes like this 1 2 3 4 5 6 7 8 9 they can also be zero right so in this here if you see the first example it is given that 1 2 7 8 9 right so we said okay we can start from anywhere but first let's form the graph now in the graph what is the relation the difference between any two numbers should be seven K is s okay now if we think about this is it undirected or is it directed graph now here if we see we are also going from 2 to 9 but we are also going from 9 to 2 right because the difference between these two digits is also seven so we can go from 2 to 9 also and from 9 to 2 also so this is what this is B directional so this is what undirected graph so these details are very important that is why basics of graphs are important to form the graph that okay is it directed or not and here we also have to think that is this a tree question or is it a graph question right so can we end up with a loop can we end up with cycle is there children over here or are there neighbors so this actually makes more sense in terms of neighbors and adjacent nodes right so let's think about it first let's start connecting the edges so for one will be connected to what one will be connected to 1 + 7 1 + 7 is one will be connected to 1 + 7 1 + 7 is one will be connected to 1 + 7 1 + 7 is what it is 8 so I will connect this also 1 - 8 is a negative digit right so I 1 - 8 is a negative digit right so I 1 - 8 is a negative digit right so I cannot connect to that 2 + 7 is what 9 cannot connect to that 2 + 7 is what 9 cannot connect to that 2 + 7 is what 9 so I'm going to try connecting 2 + 7 2 - so I'm going to try connecting 2 + 7 2 - so I'm going to try connecting 2 + 7 2 - 7 is negative 3 + 7 is 10 cannot have 7 is negative 3 + 7 is 10 cannot have 7 is negative 3 + 7 is 10 cannot have that 3 - 7 cannot have 4 + 7 cannot have that 3 - 7 cannot have 4 + 7 cannot have that 3 - 7 cannot have 4 + 7 cannot have 4 - 7 cannot have and now it makes sense 4 - 7 cannot have and now it makes sense 4 - 7 cannot have and now it makes sense why we do not have numbers that are starting with 3 4 5 6 the plus 7 and the- 7 are not single digits right the- 7 are not single digits right the- 7 are not single digits right similarly let's say for 7 now 7 - 7 is 0 similarly let's say for 7 now 7 - 7 is 0 similarly let's say for 7 now 7 - 7 is 0 7 + 7 is 2 digit plus 7 - 0 is actually 7 + 7 is 2 digit plus 7 - 0 is actually 7 + 7 is 2 digit plus 7 - 0 is actually 0 so let me just take this out for a better diagram and let me draw it over here correct so I can draw it like this similarly 8 if I see I've already connected 8 to one I've already connected 9 to2 so these are the only three edges and if I start like this so if I have to start forming the numbers now the first digit of these three uh digits I can fill with any digit 1 2 3 4 5 6 7 8 9 I cannot start with zero okay so I start like this and now let's see so here what can be my next number so I can either do what to do traversal so I have to do traversal over here who is the adjacent node or the neighbor now so for one there is eight so I can add eight over here right then I will say again for eight what can I add I can add one similarly for two I can add nine for nine I can again add two so we are going to the neighbor three is not connected to anything so this doesn't make sense because I have to have the number of digits as n this I cannot have because it is not connected to anything right this is not connected to anything seven is connected to zero is connected to seven8 is connected to one is connected to8 N9 is connected to two is connected to 9 so I hope you have understood how this works and yes we can do both DFS and BFS over here we basically have to do traversals yes let's try writing the code now we have to return Vector of integer so let's quickly write that Vector of integer RS and that's what I'll be returning in the end now here the starting point is what we have to start with adding the first digit now first digit can be what it can be 1 to N9 now rest of the digits can be zero also but here the first digit we have to always see it can be 1 to N9 so I'm just writing a for Loop that my first digit I'm call you can call it anything I'm just calling it number that this number is going from 1 to 9 so basically this is my starting number in the end the numbers that I'm going to add to the ARs that should be of the length n right so number Plus+ and firstly I'm writing the number Plus+ and firstly I'm writing the number Plus+ and firstly I'm writing the code using DFS so what I'm going to do is I'm going to write a function DFS where I'm going to pass the current number that I have the new n value so in this number there's already one digit like 1 to N9 so the rest of the numbers what can be the length of the rest of the numbers it can be n minus one correct K I will pass obviously as it is and obviously we have to pass the RS so now let's try writing this function do we need to return anything no right we just need to fill the values in the RS in the end so I'm just returning void and then in this d fs function I am passing this num so integer this is the present number that I have then this is the n value that is passed to me the K value and then the vector that I'm supposed to fill correct now DFS is nothing but recursion so what we have to do we have to see how we can uh divide it into smaller sub problems and what will be my stopping point what is the call that the length of every number that I'm supposed to put in this array should be three should be n correct and I'm reducing the N I started from n then I passed n minus one now every sub problem I'll keep passing n minus one where will I stop when my n becomes zero correct so that will be my terminating condition my base condition when I'm going to stop my recursion so when my n becomes equal to zero that means I have a number that I can put into RS so what am I going to do I am going to put this number into the RS and I'm just going to return because I don't need to do anything else I found my number now I am adding it to the ARs otherwise whatever is there in this number now the last digit I have to take and I have to do plus K minus K okay now think about this that my number presently could also be 29 initially it was 2 in the next recursive call it would be 29 in the next recursive call it will be 292 and so on right so at any recursive call it can be of any length right whatever length we have already formed how many other recursive calls we are done with but we have to see whatever is the last digit and then see in comparison that so I just taking out the last digit like this so my last digit will be what it will be num 10 correct so this is the last digit that I have to play with now the next digit that I'm going to add will be last digit plus K or minus K yes so there are two cases one Cas is when I do plus K one Cas is when I do minus K when I do plus K or minus K what is the condition is that when we do plus K or minus K the value should still be between 0 and 9 it should be a single digit number otherwise it will suppose it is a double- digit number or suppose it is a double- digit number or suppose it is a double- digit number or if it is negative then it cannot be a particular Edge correct then it is not right note in this question we are not actually forming a graph but we are thinking in terms of a graph that yeah we are forming a graph and now here itself we can see that if there is an edge or not you could actually form the graph but that is not needed because here I know when there is an edge when there is not an edge right basically I need to go to the next recursive call I need to go to the next neighbor now so how am I going to do that firstly I need to check that whatever this last digit is if I do plus K I have to make sure that is between 0 and 9 when I do plus K the only thing that I have to check that is that it should not be greater than 9 right I'm obviously not going in the other direction so I do not need to check that it is greater than or equal to zero I just need to check that it is less than or equal to 9 once I do this now I have to make my next recursive call this will be my next sub problem now in my next sub problem what is going to be my new number so whatever number I had into 10 because now I am adding the new digit what is the new digit it is last digit plus K correct this is my new digit that I am adding we are sure that it is a single digit number because we have added this check and whatever was the previous one so if it was 29 I have done 29 into 10 so it became 290 + 2 done 29 into 10 so it became 290 + 2 done 29 into 10 so it became 290 + 2 correct actually we are doing plus G so you can think of the condition if it was 81 I've done 810 + 8 like that okay uh 81 I've done 810 + 8 like that okay uh 81 I've done 810 + 8 like that okay uh so this is my new number now what will be my N I will be reducing it by one K will remain same RS will remain same similarly I have to do for what I have to do for minus K because I'm doing minus K what should I check that it should be greater than or equal to zero to be sure it is between 0 and 9 so what will be my next recursive call it will be number into 10 because I am doing say 29 into 10 it is 290 plus last digit minus K so this is the new digit that I am adding my n value will become n minus one K and R yes so we are actually done with the code but there is an edge case and I want you to think of it yourself think of this Edge case for this Edge case you really have to see about the constants here K can be between 0 and 9 also what if K is zero then how will your numbers look like always zero can be an edge case and integers we have to think of it so here what are the numbers suppose K was equal to Zer suppose for example if K was equal to Zer and suppose n was equal to three okay then we could have started like 1 one it could be 222 it could be 3 now the thing is that from this one when you do plus K and when you do minus K you get the same answer right we get the same answer now this is a question again for your interviewer am I supposed to return triple one two times or am I supposed to return it only a single time because when you do plus K and when you do minus K you are getting the same digit correct so in this case it is not given that we have to return it two times so we have to add a check that minus K I'm going to add only if K is not equal to Z and it is the case okay if K becomes equal to Z I will not consider this condition I will consider only the first condition let's try running it and see so we have passed all the test cases let's submit and see awesome but it is important that we understand the BFS code as well so we are going to try writing that also don't be very happy it is important that you comfortable in writing both DFS and PFS so again we have to return Vector of integers and I'm going to call it RS and in the end I'm going to return RS now in BFS what do we use a q in this Q what am I going to put uh is there any node as such no right every node is actually represented by an integer only we are not actually forming a graph every digit itself is our node so I am forming the Q of integers and I'm calling it Q again what is our starting point we'll be pushing all the digits first what digits from 1 to 9 not zero right so I put I = to 1 I less than zero right so I put I = to 1 I less than zero right so I put I = to 1 I less than or equal to 9 and I ++ and I push all of or equal to 9 and I ++ and I push all of or equal to 9 and I ++ and I push all of them to the Q so I have pushed all the I so first digit is pushed and how do I do the uh BFS I have to I trade over the Q right so I will go like while Q is not empty when it comes to BFS there's one very interesting point how will I come to know that the number of integers has become n now this is a problem right so first thing that we have to realize is that the number of levels that we go down in the tree or the graph is actually your number of digits right so when you go from 1 to 8 you're going to the adjacent node so that is your one level then there's another level right so how do you go in PFS you go breadthwise so first level second level third level fourth level you can think like that so the first level you have added 1 two and so on and in the second level you'll be going from 1 to 8 and in the third level you'll be going from 8 to 1 similarly from 2 to 9 to 2 right so you have to take care of what you have to take care of levels so we understand that okay we have to see that the number of levels becomes n let's do one thing let's first write the normal BFS code and let's see what change we would have to do to track the number of levels that we have gone down okay what do we do in BFS First We Take out the first element the frontmost element in the Q so let's do that so I'm going to call it for f itself so this is my frontmost element remember in C++ front frontmost element remember in C++ front frontmost element remember in C++ front is there but after that you have to pop also right you have not removed the element yet so now I have removed it now I have the number remember that it can be any number suppose in the front it could have been 81 it could have been 70 so now for the next digit I have to take care of the last digit of this front Okay so if you want to call it you could also call it current number right now what am I going to do I'm going to take out the last digit from this how is that so last digit is basically current number mod 10 yep so I have the last digit now in order to add to the Q what do I have to go to last digit plus K or minus K but the conditions are going to remain same to add to the Q so if my last digit plus K is less than or equal to 9 only then I'm going to add to the Q correct so I'm going to push to the Q and what will be my new number will be whatever is my current number into 10 so if it was 29 into 10 plus last digit plus K correct similarly we have to check for minus K also again K can be zero as well so we have to add that check that K is not equal to zero and last digit minus K is what it is greater than or equal to zero so if that is the case I can again call for what in my Q I can push current number into 10 plus last digit minus that is going to be my new number so this is how my normal BFS looks like but I have no idea when to stop this I cannot keep on going till Q is not empty I also have one more check that n should be equal to three I know that my number of levels is that now how do I track number of levels because the problem that is happening over here is that when I'm removing a number from the Q I'm not sure at how many am I adding right because suppose I have removed three from the Q right now but the 3 + 7 three from the Q right now but the 3 + 7 three from the Q right now but the 3 + 7 3 - s I'm not pushing it to the Q so I 3 - s I'm not pushing it to the Q so I 3 - s I'm not pushing it to the Q so I have no idea when that my number size is becoming n one thing that you could do is you could add a check that okay is the current number size equal to n you could keep doing that but there's a better way now listen to me very carefully now this is a very important part and it is very important to understand details like this in BFS so what I'm going to do is I'm going to add another number length equal to 1 because initially I've already pushed one digits right so this is basically My Level so I've already added one level I've already pushed one digit into the Q right so now when I'm inside the Q what I'm going to do is I'm going to add a for Loop for INT basically I equal to z i less than what whatever is the size of the Q and I ++ okay now note something the Q and I ++ okay now note something the Q and I ++ okay now note something very important over here why is this basically why have I written like this so This y Loop Will Go On Till My Level becomes equal to n this is that I am just in that level only I'm going through all the Q elements in that level for example initially I have pushed 1 2 3 4 5 6 7 8 9 so the size would be what the size would be nine correct now I will start picking up each of them that I will take one and I will push the next I'll suppose push 18 if it is possible to push if I take out say three I will not push if it is not possible right so basically I'm pushing the elements for the next level but this makes sure that I am going through all the elements in that level elements in a particular level so in this y Loop what I'm doing is I increasing my length or my level and I am adding a check that I will keep going through this while my length is less than n as soon as it becomes equal to N I do not need to push the next time note that it is not less than or equal to n it is less than n why because when it becomes equal to n if I push it once more then that means I will add for n + one right see when my length was one n + one right see when my length was one n + one right see when my length was one I have already pushed one element so when my length is n i already pushed n elements right if I push one more it will become n+ one so these details are will become n+ one so these details are will become n+ one so these details are also important and not less than or equal to but less than now there's one more important Point Let's see whether this is going to work or not so firstly I need to write Q do size and also in the end in the Q whatever elements I have are all of length n so I need to obviously fill my RS right because I'm returning RS I'm not filling it anywhere in the end in after going through these levels whatever elements are there are all of length N I have made sure that I have popped the rest of them all the elements are now of length n it will be clearer when I dry run you can just go to uh this time limit I'll be dry running it after writing the Java code as well so don't worry if you're overwhelmed we'll be writing this code so many times you'll get used to it okay so what I need to do is I need to keep popping the Q and fill the RS so while my Q is not empty what am I going to do I am going to push in ARS the QA front whatever is there in the front I'm going to put it and I'm going to pop the Q so one element I'm taking out and putting into the Que so now the question is this going to work or not think about it yourself I'm telling you it is not going to work but let's run it and see is it going to work or not so here you can see it is not working sometimes I'm getting the number of digits as two sometimes I'm getting it as three I put the check of level right so why is this not working think about it a very simple thing is that I have added Q do size in the for Loop and within the for Loop I'm actually changing the size that doesn't make sense I am pushing and popping it while I am using the CUA size so what size I want the size that I had while when I entered into the Y Loop so all I have to do is I have to do this s equal to Q size I'm just taking a variable and here I'm going to say I is less than S and now it should work let's see this is working let's submit it and see awesome so if this part is not clear it is fine don't get overwhelmed we'll be doing this so many times it will get clearer but I will also be dry running this and it will become clearer so you can just go to this time and see the dry run but to tell you again the number of elements that are there in that level it is there when I get inside the while loop like for example in the starting it was nine okay and the next level it is four now if I'm changing while pushing and popping then I'm basically messing up with the size right then I messed up with the level let's try and see at this time for now I'm going to be writing the Java Cod so we supposed to return the integer array but we do not know the size of it so I'll be using an array list and then converting into the integer array and then returning that in the end so let's get started list of integer uh r equal to new array list and I'll be forming return Rees and I be returning that so I'm just calling it return RS this will be new integer and the length will be RS dot now so this is just the boilerplate code now let's get started with the DFS code so this is the RS that I'm supposed to form DFS is nothing but simple recursion so here you can note it is not like I'm forming a graph as such I'm just going to be using the connection between that to see okay this is a neighbor or not so what am I going to do I'm going to do the recursive call First first that I need to do is fill the first digit of each number now what is the first digit of each number it can be 1 to 9 note that it cannot be zero we have to think of these cases so I'm going to write a for Loop uh I'm calling it number you can call it absolutely anything the first the initial number is going to be from 1 to 9 and I'm going to do num Plus+ and I'm going to call a function Plus+ and I'm going to call a function Plus+ and I'm going to call a function which I'm going to call DFS you can call it anything you can call it helper function now in this DFS what are the things that I need to pass first thing that I need to pass is the number the current number that I'm considering then I need to pass the N value now n is the length of the number the final number that you need to have you have already added one digit so now your expected length has become n minus one you are going to a smaller sub problem now initially your length was n you have already pushed one digit so now your sub problem is what rest of the digits that you going to include should be of length n minus one k is going to remain same you're going to fill the RS so let's write this function I'm going to keep it private and do I need to return anything from this I am just filling the RS itself right so I do not need to return anything so that is why I'm keeping it white itself DFS and I have passed the number so number I have passed the N so this is the length from whatever sub problem I have this is my n right this is my K value and I have passed the list of integers RS that I'm going to be filling now what we are doing is a simple recursion in recursion what do I move to a smaller sub problem but as I go to next sub problem I also need to know that where do I stop otherwise I'll end up in a forever l u i need to have a terminating or a base condition here when will be when the terminating or base condition now with every recursive call this n is reducing right because it is n minus one further suppose it was say initially three then it became two then it became one when will it stop when should the recursion stop when my n becomes zero basically I've added all the digits that had to be added I've have added n digits so initially I had added one digit so it became n minus one then when I will add two digits it will become n minus 2 and so on till my n becomes equal to zero so when my n becomes equal to zero that means that my number is of the length that was expected right n that was expected now this is you can rename it to something else also this is like new n or the left over n basically this is the n for this sub problem when n becomes zero this number is of the length that we wanted okay so now I am ready to put it to RS so in this add basically this number and I can just return from here so this is my terminating condition on my base condition now we will see what will be my next recursive call so whatever number I am passing note that initially I am passing single digit number like 1 2 3 4 5 6 7 8 9 but in the next recursive call it could become say 81 or it could become 92 right so whatever that happens so now suppose my sub problem is 92 my number is 92 now to add the next digit I need to consider the last digit of this whatever number I have it could even be 929 if my n that was given was four now I need to consider the last digit of this so I need to First Take out the last digit so I'm going to take like this that last digit will be equal to what n m 10 so now I have the last digit in my next iteration I need to do either this last digit plus K or minus K correct but while doing this plus K or minus K I need to make sure that whatever my new digit is formed is between 0 to 9 right otherwise it will either become negative or it will become a two-digit number or it will become a two-digit number or it will become a two-digit number which is not correct I need to add digit wise only that is basically my connection between the graphs between the two nodes so I'm adding a condition to make sure that I'm only going to my neighbor node okay so how do I do that if my last digit plus K is less than or equal to 9 now note over here that I just need to put the check less than or equal to 9 I do not need to put the check greater than or equal to Zer why because I'm going in the positive direction so I will obviously have a greater number only right so I just need to have this check and if that is the case I am going to call the DFS function now again what will be my new number whatever the number was I'm going to do into 10 why suppose it was 29 I'm going to do 29 into 10 if it was say 81 I'm going to do 81 into 10 so I have 810 now I need to add this 1 + 7 right now I need to add this 1 + 7 right now I need to add this 1 + 7 right which is what it is last digit plus K so this is my number for the next recursive call so if it was 81 I did 81 into 10 so 810 plus last digit plus K last digit was 1 plus K became 8 okay so now n will become n minus one because I've added one digit so left over digits K is going to remain same RS is going to remain same the same thing I need to do for minus K as well so if last digit minus K is greater than or equal to Z I'm going to call my next recursive call again DFS what will be my next number again number into 10 so if it was say 29 into 10 became 290 plus last digit minus K 9 was my last digit 9 - 7 became minus K 9 was my last digit 9 - 7 became minus K 9 was my last digit 9 - 7 became 2 right so it will be 290 + 2 so 292 and 2 right so it will be 290 + 2 so 292 and 2 right so it will be 290 + 2 so 292 and left over digits are n minus one k will become same RS will become same so now we are actually done writing the code but there is one H case that is supposed to think of now for thinking these edge cases you need to think of the constants very carefully think of it what Edge case are we missing think of it now here K can also be zero what will happen when K becomes zero suppose my n that is given to me is suppose three and K is zero so what will be my answer will look like 1 2 22 3 4 and so on so now note over here when I do 1 + 0 it is again leading to 1 - 0 do 1 + 0 it is again leading to 1 - 0 do 1 + 0 it is again leading to 1 - 0 is also leading to 1 so if I do this if I write this code actually I would have had the same answers two times right one now these are the things that you're supposed to ask your interview in this question we not supposed to return the repeated answer so if I actually run it and show it to you here this has worked but now in the test case if I add k equal to Z it is not going to run so all the test cases won't pass so you have to think of the edge cases yourself also see here I'm getting one1 so many times 3 so many times so what do I need to do if it is k equal to Z then I need to call it only once because this number and this number becomes the same thing because plus K and minus K is the same thing so before calling the next call I'm going to do if K is not equal to zero add this now note that I could have called it in any order then in just I have to avoid the second call just add right now let's run it now it is working for k equal to0 Also let's submit and see we have passed all the cases very good but we should also know how to write BFS code of this and that's what we are going to do now coming to BFS so I'm just removing the DFS function and we're going to reuse this and instead of calling the DFS function what do we need to be adding the first digits to the Q so let's form a q first for BFS we need a q so Q of integer itself right why integers why not any specific node so here for both DFS BFS we have not actually formed the graph we are treating each integer itself as the note correct so that is the reason link list and now each number I will be adding it to the Q what do we do in Q we just keep going like while Q is not empty we will keep popping the first element and then push the neighbor nodes here the tricky point is that here one more condition is given to us that n is equal to 3 how do we make sure that when do we stop here if we keep doing BFS again and again then firstly we'll have all the elements of size one 2 3 then when will we know that okay we have reached the size three and now we need to stop and we need to push it to the RS so how do we do that if you think about it think about how the tree or the graph is going to look like when you have just one element so you are at basically level one either it is 1 2 3 4 5 6 7 8 9 then from one you put you push eight then it becomes 18 right so that it is the second level of the tree of the graph then 18 then 181 becomes the next level so you're going level wise so when you are at level three basically you know that you have added three numbers and now you need to stop so we'll be dealing with the concept of length or level and we have to check that okay now the length or the level has become three now we need to do that but before we do that let's try writing the simple BFS code we have written so far and then let's see what change we would have to do to accommodate cre this level so first thing I do is I take out the current number from my Q so that is the front one okay so Q do remove if I do I will get the front element I have the current number now again going to the note what do I need the last digit so last digit is going to be what it is going to be current number mod 10 so I have the last digit now in order to go to the next node I have to consider last digit plus K last digit minus K the conditions are going to remain same so if last digit plus K is less than or equal to 9 only then what will I do I will push it to the Q so I will add to the Q how what will be my new current number it will be current number into 10 right same how we did number into 10 over there here the number is basically current number it can be 81 it can be 18 it can be 29 it can be 92 and so on so forth current number into 10 plus last digit plus k similarly I will put the check for minus also last digit minus K greater than or equal to zero again K can be zero so I have to put the check that if K is not equal to zero only then otherwise we'll be pushing the same thing into the Q which we don't want to do and what will be the new number it will be current number into 10 plus last digit minus K so this is the simple BFS code that we have written now what do we need to take care of the level 10 now listen very carefully what I'm going to do is to make sure that I'm going to the Next Level I'm going to add a simple for Loop and I'm going to say I equal to z i is less than Q size and i++ and this entire thing I size and i++ and this entire thing I size and i++ and this entire thing I putting into a for Loop so now you will say k there's a y Loop and inside that there's a for Loop why are we doing that so what is happening is this is within a level so every time in the next iteration of w Loop what am I doing I'm basically going to the next level and this is essentially within that level I'm going to iterate through all the elements is this going to work or not think about it and I'm going to continue my while loop till when till my length becomes equal to less than n not less than or equal to n why is that when it becomes equal to n if I add again the number of elements will become n + 1 so number of elements will become n + 1 so number of elements will become n + 1 so when I'm less than n the number of elements are already n so I won't I don't want to add again right so when it is n minus one I have actually added n elements already so if I go within the loop again for length equal to N I will basically end up adding the digits for the next level and I don't want to do that so these little details are very important so now in the Q whatever numbers are there are all of length n right and that is what I'm going to do I'm going to add another loop that while Q is not empty what are we going to do I'm going to keep adding the elements from the Q to this RS so rs. add Q do is this going to work or not I'm still saying it is not going to work think about it why let's run it and see so here you can see I have a lot of numbers of a lot of digits but I put the check of length right so why is this happening so note one very basic thing whenever you are adding CUA size now inside this only you're removing and you're adding the numbers you basically Chang changing the size inside that is not correct right you're changing the size inside that so the whole purpose of that is gone what if I do this I just take out the size outside and now when I'm inside I am changing QA size but this s is still same so now I know that within that level whatever is the size I'm going to be going through that it is okay if it is not clear we are going to dry run it we are going to be writing this quote so many times it will be completely clear don't worry about it let's run it and see so now we have passed all the test cases let's submit in and see so congratulations we have written both DFS and BFS code but let's do a quick try run let's understand the BFS part a bit more in detail so initially what happened in the Q we have pushed like this we have pushed 1 2 3 4 5 6 7 8 9 right we have pushed like this so inside the while Loop when I come my QA size basically s is 9 now I have a for Loop to go through each of these elements one by one and I'm going to see is it connected does it have a neighbor and is that valid connection then I'm going to put it to the Q so here for one I can see 1 + 7 so I put 18 1 - 7 doesn't make see 1 + 7 so I put 18 1 - 7 doesn't make see 1 + 7 so I put 18 1 - 7 doesn't make sense so and then I remove this right now if you see within this for Loop only right now this is same right for two also suppose I push what I push 2 + 7 also suppose I push what I push 2 + 7 also suppose I push what I push 2 + 7 which is 9 similarly for three now 3 + 7 which is 9 similarly for three now 3 + 7 which is 9 similarly for three now 3 + 7 becomes actually 10 I cannot push anything so here what happened that I removed one element from the Q but I did not add anything to the Q so I'm changing the Q size while I am inside this wi Loop so I need to take care of this s outside itself so now what I'm going to do is I'm going to keep taking like this that for four there is nothing to be pushed for five there's nothing to be pushed for six there's nothing to be pushed then again for seven it becomes 70 for eight it becomes 81 for 9 it becomes 9 0 now I am done with all the nine elements now I'm going to go to the next iteration of the Y Loop and my S is going to become what it is going to become 1 2 3 4 5 now s is five and then I'm going to start picking these elements one by one so if it is 18 I can now push what I can push 181 similarly I will pick up 20 9 and I will push what I will push 292 similarly I'll push 707 similarly I'll push 818 similarly I'll push 909 so initially the length was one and here when I Chang like this my length became two so in this white Loop my length became two I already have the numbers of length three now when my length becomes three I don't want to add again now I'm done I can just take out this q and put it to the RS and I'm done so now I hope it is completely clear I hope you like the video you have no idea how much effort it takes to write both DFS BFS code in both C++ and Java if you DFS BFS code in both C++ and Java if you DFS BFS code in both C++ and Java if you think I deserve your appreciation please do consider subscribing and please do share it with your friends check out edu courses you have no idea how much it will mean to me thank you so much and be consistent see you next time bye
Numbers With Same Consecutive Differences
minimum-falling-path-sum
Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**. Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed. **Example 1:** **Input:** n = 3, k = 7 **Output:** \[181,292,707,818,929\] **Explanation:** Note that 070 is not a valid number, because it has leading zeroes. **Example 2:** **Input:** n = 2, k = 1 **Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\] **Constraints:** * `2 <= n <= 9` * `0 <= k <= 9`
null
Array,Dynamic Programming,Matrix
Medium
1224
700
hey everyone welcome back and today we'll be doing another lead code problem 700 search in a binary search tree this is an easy one you are given the root of the binary search tree BST and an integer valve find the node in the binary search key that node values equals the value and return the node if such a node does not exist return null so this is a binary search three these things are easier for us because we know that in binary search tree we are going to have the elements which are less than the node on the left and if they are greater then we are going to have it on the right so if we have not our root let me just check the indent okay so we will just return none and if root dot val is equal to the valve then we are going to return the root and if root if value is less than the root that well then we are we know that we are going to Traverse to the left so self or find going to find it on the left basically so search as ears ear CH okay search it with the root dot left with a well and if not then go to the right okay so that's it returns Dot search binary search tree okay this was an easy one and still there was a mistake so that's it
Search in a Binary Search Tree
search-in-a-binary-search-tree
You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 2 **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `1 <= Node.val <= 107` * `root` is a binary search tree. * `1 <= val <= 107`
null
null
Easy
null
234
hi and welcome to this video today i will be talking about lead code problem 2 3 4 palindrome linked list the question says given a singly linked list determine if it's a palindrome now i'll assume you already know what palindrome is um but just to summarize it's basically the inverse of the word or the string will be the same so one two three if you reverse this part here it will be the same so if you read it from any direction it will be the same this is not um because one two three is not the same as 3 2 1 but a third example which is not mentioned here if it's 1 2 1 then it would be the same if you read it from the inverse direction so this is just a quick summary this video is more focused on how to write the code so the example gives us this here one two three two one now and here is a representation of that example so i wrote down the procedures that we have to do here which is basically step one we split the linked list in the middle so we take a points right here and we split the linked list from the middle and then we reverse the list so to say and then when the list is reversed we can compare each value and if the value is the same then this is a palindrome if it's not the same then this should return false this is one of the more interesting problems that require a bit more thinking and i found that a lot of videos online don't go into details and the goal this time is to go into details so uh the first steps will be to create four variables and i will be explaining why and how as we go through and things hopefully will get clearer as i progress through the video so the first variable is going to be called fast and that fast is going to get its information from head and head is this right here if we were to define the function i'm just excluding the function headers for now just to focus on the contents but it's basically going to be passed in the function from the function sorry um before i go into more details we're going to use a fast pointer and a slow pointer which is basically the two pointer method the second one we will create is slow and that will be hit and i'll be elaborating as we go along i'm going to create two more variables which is ref which is basically reversed which will hold the reversed list and i'll give this none and i'm going to create the fourth one called temp slow that will also get none and this will be holding the temporary variable of slow as the list is getting reversed and when i code it will get clearer okay so let me stop here for a moment and i'm gonna actually write the last bit of the code just to clear things uh just to show you how things should connect i'll just change the color here so the last bit of the code while slow so while there is still data uh while there's still nodes in the slow if that value which is stored in there does not equal the value stored in the reversed val list then return false however if they are the same then iterate to the next one so do slow dot next and reverse dot next and obviously if it doesn't come to this f you simply return true now one can ask why did we why did you start with this well basically the goal of the code is to get from here to here so we're gonna bridge something in the middle so how can we go from just having this here into actually creating two lists and comparing them and if they don't match then it's not the palindrome return false else return true so i wanna i wanted to put this to sort of set the foundation of this so we start by saying this here while fast and fast next while both of these have values i want you to execute a set of functions so fast is the head so fast is currently here slow is also the head so slow is currently here when i say currently here that means they have a copy of the whole linked list here or the singly linked list here and basically what i want to say in the first iteration or basically while there are data fast i wrote this in capital letters no i just don't want to make my life hard so fast equal fast dot next and that basically means fast dot next is gonna go from here to here and in the iteration after that from here to here now let's imagine the green is the fast and the purple is the slow so in the first iteration fast is going to go here and then we want something else to go here and the iteration after that is going to be next so it's going to go here and the purple will be here in the iteration after that next we'll be pointing here and the purple will be here and as you can see this is exactly the middle of the list then we're going to cut this out and we're going to compare each value so i will write down the code here and then i will show you how it exactly works so we can think of this as the variable that flags the end of the list since if you're at null then basically while fast and fast dot next this is going to be false so it's going to exit this while loop so this is the person that will flank us to exit this loop now the next four lines actually reverses the list so let's think of this as the flag person so temp slow will equal to slow next and i will explain exactly what this is doing the arbitrary speaking if slow is here slow dot next is here so all of this will be temp slow next that slow next will now be pointing at the reverse list which is none for now the reverse list is gonna point at slow people back wait a second reverse what's going on i'll we'll go into details now and then finally slow will get the temp slow okay what is going on here so i've prepared this so we can do it step by step can i fit both in the camera yes i can okay so in the initial iteration fast gets the whole values of head which i wrote it up here i'm just gonna write head for now so i don't have to copy everything but head is this is a head the temp slow gets nothing the rev gets nothing the slow again is head and slow dot next is two three two one now but for the sake of space again let's keep it empty for now and let's get to it in a bit so let's draw a line here and this was the initial initiation or the initial now what happens at the first iteration so while fast and fast dot x so as i've mentioned earlier here so fast is here so while fast and fast next so yes that is uh that is true fast.next.next so fast is here it's not fast.next.next so fast is here it's not fast.next.next so fast is here it's not going to shift it to here so this is so this will be so fast was here now it will be here so this will be three two one null three two one now temp slow is gonna get slow dot next so again slows initially here slow dot next is here so this will be two three two one now slow dot next will be rev now remember slow is still here but what we're saying here is that the next will be pointing to rev and rev is none so basically it will be null pointing to one right because the value of slow is one and the next thing you should point to is rev and ref is none what does rev get here rev becomes the value of slow so what is slow in this case slow is null 1 and finally slow becomes temp slow so temps law is the value up here so that will be 2 three two one null it will get clearer as we do more iterations so jumping into the second iteration the head the fast head was here now it will be here so it will be two one null and temp slow will get slow next so this is as you can see here this is your slow so slow next starts at three so that will be three two one now the third line of code slow dot next will point to the ref so slow dot next in this case is right here is number two so if we keep this as is it's gonna point that way and this point here is perhaps causing the most confusion in this problem so i will repeat it again slow the value of slow and the last time we checked the value of slow which is the slow dot next right here it was three two one null what we're doing in the next step is saying that the slow dot next should point to the ref value so our rev value was one pointing to null what we're going to say is that the next value of slow which is 3 in our case will be pointing to sorry 2 will be pointing to rev so if we were to imagine it this if we were to imagine this point and i'm gonna draw it for the second iteration so it's clear so if i were to draw this part here two three and so on and this line here slow dot next so it's at number two is pointing to three we're saying instead of pointing at three you're literally getting rid of this connection and you're telling it to point at the values of rev which in this case is one and none and you are actually ditching everything here and that is the point of temp slow is to still keep a copy of this now let's go ahead and do some more iteration now rev will equal slow in this case it's just simply that null one two and slow is going to get the value of temp slow which is up here three two one now let's do some more iterations so now actually this is the last iteration because fast is here and it's going to go here so basically it's now just null or yeah it's now just null and temp slow gets slow next so slow next is a three so it's going to be simply b3 two one null and as you can see actually we're in the middle now and slow dot next should point at rev so the next value of three should point at rev and the ref is this here which is null one two three and rev gets a copy of this slow and then slow will equal to temps law which is three two one no and if we go again while fast and fast next actually that's not true and now we simply go to the last line here and it says right i'll get the camera angle and here it says while slow which are these two points right here compare each of them and this will return true as it compares each of them now what happens if our list is odd number and it's a pounder because in this case it was even numbers so one two three four five six which was perfect but what if we actually get a problem that looks like that so this is actually a palindrome because it's the same if you go in both direction in this case you have to skip the value in the middle and to skip the value in the middle we simply check the code by writing if fast so basically if fast which means you are still here and you are not at null if fast then basically skip a connection from slow by moving it from here to here so you would write slow equal slow dot next so this basically checks that you are not stuck in the middle in an old list where it will be the same length uh sorry where it wouldn't be the same length in both directions so you would simply omit the link in the middle and you would compare these so if you were the example there's more and more here you would omit these hi it's me from the future there is just one thing i did here um i put the circles around these two and compared both of these that is wrong you compare the rev and the slow and not what's in the slow next so if we take out the slow it will look three two one null and then if we take the reverse list it will be three two one no so i did the comparison on both of these this is wrong it's both of these let me know if you have any question would always like to help thank you
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
847
first okay 847 shortest-path first okay 847 shortest-path first okay 847 shortest-path visiting or notes and untie my have to connect the graph of n nodes is convenient and input graph grabbed our link as you go to N and J of chain IG goes to minus in the list graph sub I exactly once if and only if notes I and J are connected so yeah we're adjacency list it seems like we turned the link with the short path down visits every no maybe we start and stop at any node you mean we recent notes multiple times and you may reuse edges okay so this is um huh and it's just drops I think that's okay so I like this problem well for some definition of that but uh well don't only think that makes this possible so yeah I mean you could revisit notes which is also may be useful but uh Oh Chris oh yeah sorry yeah I stopped on a toy uh don't want iPhone in this is fine probably I should practice more Python anyway uh yeah the thing that makes this you know I wouldn't say easy but easier is that n it's only twelve right so you could do very before see things for sure and that's Oprah for saving because the most put for see thing is prize like 12 factorial is I'm like that which is still too big poignant eighty million okay sorry actually in theory doable open do you want to do no we could do it we could still do better yeah there are couple things we can do I want to you see because I want to play around with a suppose possibly because I should practice it post personalities but I already know C for reason that I'll show in a bit yeah maybe that's not a good reason well I want to use because I want to do I will create a matrix that's why I want to do you C++ because I know in Python to do you C++ because I know in Python to do you C++ because I know in Python they're like not real matrix I mean they're like what do you think what's the difference like it they're not matrix they're just more tied dimensional arrays to them extent because then it could be jagged versus like an actual rectangle room in this case square matrix so yeah so I'm gonna do and suppose that's looking reason why it's not a big reason they could still do it I mean like you could manually force it but I just prefer it that way so the first thing I'm going to do because n is 12 and you could maybe we could think about optimizing it later but we're gonna do the shortest path from every node to every node yeah and you could do that with was it chord washer well typing up so you could maybe I could type it up correctly that's just for the viewers I mean to kind of go a little off stream no yeah so I don't have to explain it a little bit but yeah so we'll just use that later to kind of figure out the shortest path which in your points then you could actually just calculate and there's an optimization that we'll get into in a second I know excited how to solve this problem I think so that's why I'm kind of hand waving a little bit maybe you're in an interview that's not great I mean I would explain a little bit more but uh but I don't in China I also don't see these comp forms and interviews don't only because you know reason to point out a little bit because it's a little awkward but uh well I'm going to start coding and I'm going to describe what I'm coding so I'm going to structure that or this form this way instead and also proposed to write I think about dynamic program problems it's another dynamic program file to kind of work at for optimization so yeah maybe I you know it so this one I did take couple time for web forms I'm bad at but uh yeah so yeah let me get into that and a graph form I love graph forms in general duh they don't always love me okay novelist have crush about je yeah I isn't the less exactly once if and only if note I and J are connected yeah that's facing is a little bit I think it just means that yeah each number that appears in a sub list will appear only once and I guess they don't really define what J is which is probably why you're confused but jr. I assume now looking at it is the it's an individual number in the list and J is not equal to Y so like this is the element civil of graphs of hi elements civil of graph so 0 would not be in this so yeah I think that I interpret it's an adjacency list so that's how I interpreted and I kind of didn't really looked at you'd be into it to be honest but out I am gonna convert this to an adjacency your way which is oh sorry Jason C matrix which you'll see in a second okay whoo that was a mouthful let me clear my phone open and now start coding I know the answer to this one I swear okay cool okay so now we have I should say shortest path yeah I know max is 12 I always like to Pat myself just in case for which we call it off by one Valley over stuff no I guess I could just get in well yeah I should definitely at some point actually a waiter may be mighty wonders I could be one of those cool kids with love a medium person how do you sleep go do something I don't mean that in the kind of sending way so I buy it came out that way but I just mean like I do get questioned like a couple of times I scream and I do try to explain every time but I do want you know to explain it but uh but yeah I know maybe that would be cool let me know if that's y'all think is useful if I do I mean if you're on the stream maybe you don't because you already heard me talking about the same thing more time oh yeah but the max here is should be max because you can you don't have to go that far you're going to go like a cup of notes away I mean I should be okay yeah I think and I could do this one yeah I don't know for me it's just something that this is just like a hobby of mine and also like good to keep up with my you know being was not you know just good keeping in shape I get that trouble typing in talking at the same time he's talking about unrelated things but yeah I don't know how I feel about it I mean like I said I was a aspiring academic person so like I don't know what does money stuff is yeah maybe I just like I already you know I feel like I definitely had been very fortunate in many ways in different parts of my career both yeah different stages of whatever have been very lucky with kind of mentors and stuff like that and I just this is kind of like my way to give back a little bit but you know like my eyes and James don't match the description so this is right sorry I'm talking about typing oh yeah I definitely think about it and it's giving back a little bit to you know future generations or people I don't know if that sounds too grandiose but that's how I think about it I don't really you know otherwise yeah I mean it's I don't know but yeah I also just happens to find this fun and or like yeah it's stimulating right like its intellectual like I said I mentioned this before like some people do crossword puzzles some people - so - I crossword puzzles some people - so - I crossword puzzles some people - so - I do these kind of things just to kind of keep myself sharp and it's tangela related to programming so I keep myself into a shop and down as well so that's why I kind of do it I know I mean I'm not like outside of like a close group of friends or whatever sorry about that I just think you know for me I'm you know I'm getting up there in age I think for me time I saw like time is a disproportionately while you're part of my life and I don't know and once you put money into things are stressful and like you have obligations and stuff like that I feel like I mean I still try to do this every week but you know in theory you know hope you're getting for free you know if I don't show up a week or something because you know I don't know beat somewhere like I hope yeah I would forgive me a little bit for it but uh yeah I mean I think there are a lot of resources and also a lot of my kind of in real life mentees shyam just like make sure I got this right yeah a lot of my real like mentees I all like by now actually like relatively senior maybe not well it'll be seen it but like senior ish and then we kind of yeah do it that way so I don't even like sometimes it's kind of a little crappy to say but I just maybe know disconnected to the more to new people sometimes maybe I need to be better about it but like you know but I would also say that now more than ever they're very more resources to you know how to get better in three years an algorithm that's not like this like I think people to human earlier so I don't think like I'd have like I don't have crazy amount while your power position I think like a lot of people could do it so you know I leave it to them okay so what I just premiered to Walsh or for Warshaw algorithm look I mean it's actually also considered a dynamic programming algorithm which is calculates the shortest path for you know a lot of things you could actually be like this in a quicker way to make it not to the addition choice but that's why yeah I'm not gonna explain it because it's a standard a it's not a standard e-pawn algorithm but it is standard e-pawn algorithm but it is standard e-pawn algorithm but it is something that is Google and fun factor stuff would wash album is probably one of the earliest how come I learned and I was just like wow this is just three four lifted I could do the shortest path or pass what that this is like crazy magic so definitely looked at hell because if I can learn it as a young kid maybe you could figure out - I mean maybe you could figure out - I mean maybe you could figure out - I mean that's it I'd learned how to code it I didn't really understand until many years later when I have a more we find algorithm training of you well yeah okay so how can I start from anywhere we start and stop at any node okay uh all right when I stole it I guess we found nothing okay Oh this on a calculator I know such anair things you know no I don't want to okay oh it isn't really what I did is just I forgot a dimension that's it's you're going to miss press well what's the worst case dad I just say a million maybe not to be made I guess so technically I just so what I'm doing is structuring in a way that I don't have to write an additional base case but maybe I should have done it just return press and this is it this is the part of recursion we question is also kind of my tip about the question I think because I've done recursion now and someone asked about it which is that the question I think it's just reframing a pom in terms of itself but just literally the definition because you know I know but what that means is kind of I mean I guess I just that is literally what it means I don't know how I don't I guess I'm coming short on how do they explain that particular one but they are I think this is like a well studied or well YouTube people would create a lot of videos about recursion I think I'd that's what I would recommend I don't have nobody have where I don't think I could do it better than like you know thousands of youtubers I think dissipate so I'm gonna leave it at that maybe but because I guess the because what I was going to say is that I'm going to recursion right now but DP recursion is kind of a special case of it kind of and I don't know it's just all really difficult given the view uh you know goodish recursion so I don't want to like set things up in a weird way I don't know if I'm saying it right because I'm trying to code to again but okay I know I promised to explain my DP a little bit which is I think this is a good time so I said because n is equal to 12 you could use this optimization and XS maybe this is not we're learning but up but this is kind of yeah okay whatever let's just go to X because I just don't change it but because yeah so just dynamic programming function or dismembered and with memorization it's just that I'm at node X right now and these are the mask is the it's a boolean set of or like a bit mask but or bit vector or whatever except for if it's an int because it's not there's only 12 possibilities but just which means or and it's equal to 12 so there's only two to there twelve possibilities right yeah so mask represents like all the stuff that we've already visited and one thing that I did which I didn't talk about is I know that you could visit the same path multiple times but essentially oh I guess that's not the case but oh no we do miss it zero all the time but good but because we calculate all the shortest path using the for show album and to did we already has to distance of 2 which factors in visiting zero again so that's already factored in so then we could do everything directly that way treating it like we only visit each node once contact was kind of a good enough explanation never you asked in the comments if we go I'll try to explain it a little better but okay yeah and this is just you know standard dynamic programming memorization what am i call it right I mean I did magic constant I also have to oh I guess I need more corner things I mean these are just poor news I could have passed it into the recursion but maybe this is a pretty mature optimization well but that's not doing okay so what's your other base case base cases we visit all of them so mass is you go to return see you're done maybe this could come before and there's a matter which other states now we just need a look in a second bracket because a why is probably something I always talk about that means this is are not used the temper available or cause I should be named element better cause you go to they going to eye mask you add this bit and then the course of going from X to Y so why does this not in computer actually now that I just want to calculate okay and you can't go to itself because these are okay that's just one let's go - Dada - I guess that's an equal ad - Dada - I guess that's an equal ad - Dada - I guess that's an equal ad in math so let's just understand 60o what i J yeah I'm hungry today so buffer overflow means absolutely just totally sure when indexed okay Wow this should be yep okay so we type Oh hopefully that's it okay hey daddy nice of you to join us welcome to the maybe an empty case I guess you need one that's right in one case there there's a good day okay all right cool Wow slower than 30 did yeah it's funny okay think about it too much man this is like one of those weird backwards day where I'm like doing what a high-tech look like I done them really a high-tech look like I done them really a high-tech look like I done them really quickly in all the mediums I've been just like strong gonna know that there's one of those days I guess um yeah uh how do I talk about this so yeah I think graph palms always no tricky and just I am a program problem because you have to do this big mask ring it's a little like it's a weirdest thing that doesn't come up as much so that's why finding do bomb I generally don't do stuff that requires big masks any such an optimization that is necessary like if I could do it in a like if you could I don't know maybe like do a bit away and then store that in the hash table there may be never been okay but that usually the running time things way higher than it needs to be or should be well it's just way too high anyway if I got optimization but that said this is a this is wealth of the yes I've covered bits and pieces I like certain parts of this poem it's an interview but I don't know I like all of them and in terms of cleaning into air cleaning the code there's never a lot of cleaning I could have done that I didn't do because I kind of watched with her a little bit he's in a way that I saw did I stop doesn't happen now I mean I talked about other stuff doing it but like summer white for sure I could I do I could have put this in a helper function for sure these are just or well this is a we this is just resetting the code so put that in a helper this kind of convert in adjacency list to an adjacency graph so that could have been a helper function maybe the sister kicker for the recursion something that's fine but maybe I could clean that up no but I could rename this is cause this is probably as short as sweet as it could get so I mean maybe I could have changed some wearable names here and there but probably not by that much oh yeah so that's kind of the two things that I would do to improve this ovoid this algorithm is n cubed plus 2 to the n times and times ok n cubed plus N squared times 2 to the N I think and in space it is n times 2 to the n plus n square I guess so yeah I guess I'll put it down somewhere just so I can remember I talked about it the time is and cube plus N squared times 2 to the N I think I said and I still think that's right spaces of N squared plus and times 2 to the N I mean the space it's easy to do the math for me because you know this is our space deserve rectangular away so it's you know you just look at right and you just multiply I mean I think that's straightforward ish if not you have to be wizard some data you know basic data structure this well n cube comes from FOID Warshaw may not be super necessary per se but I think eventually you differentiate comes in handy so maybe that's unavoidable because it makes a lot of things easier yeah so this is query n cube because this to a foot and I think that's clear so this suggests n times 2 to the n subproblems for dynamic program form and each of these have n 4 inches of your well so the an amount of all of one work so that's why I sent squared to the end so that's the time complexity that's how I go about this problem I don't have your about it I think this is a crap bomb but like I said it's kind of a little brute force but in a cool smart kind of way but it's in a way that is very straightforward if you have seen this kind of perforce or this kind of dynamic programming Paul maybe I'll do it think about different types of you dynamic programming problems at some point but uh but yeah but because of dad I don't really like to ask these kings on a on an interview but and I don't know if I would expect to see this on an interview I think it's a little bit on the hot side I mean I know I it's kind of funny because I on the medium stuff I say it's easy but I struggle a little bit and I said that's too easy born and for this hard form I feel like it's still too hard for a normal person diem guy kind of relatively brief for it but it is like an assembly line 9 to code I mean it's definitely hard it's just hot in the sense that like just a lot of high level or like high power machinery if you will dad like I just happen to know but I these are also knowledge that I don't know if I would expect everyone to know like on an interview way I generally prefer more primitive albums like binary search or sorting and stuff like that actually like Guam Stata kind of related to one of those two things don't you Jamie it's an interview yeah meet Austin don't take my word but uh but so that's why I wouldn't choose this problem I think it's still a little hard for the normal people to be asking like I don't think I seen anything similar maybe I'm wrong but I like it like I'm just trying to think if I've heard other people ask this type of problem and I don't know if I have an example of it so I don't think I think it's a little hard it just happens that I know more the pieces about it yeah so that's why say about this form contend this faster I mean I think I solved just as fast as I could I mean I know I talked about during its own not as fast as I could best as fast as I could while talking fooling yeah so that's sort of yeah I'm okay with moving on with this and that's anyone have any questions for certain to answer your question next but um yeah void well sure is just one of those things where I mean that's why they kind of had waved over I mean there's a good Wikipedia or a CO about it so that's what I would recommend and it's one of those things that with literally like I said this part is an algorithm or like a research paper right I mean that's two people say more than two kind of famous people to this point did a lot of graphi stuff as well and war sure did some other DP things but so like you know like I don't you know whether you don't because you're not going to prove this on it you're not gonna prove this on an interview so just take a look we're interested I think and I don't think this should be on interview old Ford we're sure so but that's my opinion so again if you get caught you know apologies in the fans and but yeah but it is once I mean once you do get it is like three four loops so that's why I like it but uh yeah cool
Shortest Path Visiting All Nodes
shortest-path-visiting-all-nodes
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\] **Output:** 4 **Explanation:** One possible path is \[1,0,2,0,3\] **Example 2:** **Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\] **Output:** 4 **Explanation:** One possible path is \[0,1,4,2,3\] **Constraints:** * `n == graph.length` * `1 <= n <= 12` * `0 <= graph[i].length < n` * `graph[i]` does not contain `i`. * If `graph[a]` contains `b`, then `graph[b]` contains `a`. * The input graph is always connected.
null
null
Hard
null
216
uh hey everybody this is larry this is day 12 of the lego dairy challenge for september hit the like button to subscribe and join me in discord uh let me know what you think um yeah my neck's still a little bit sore but i feel a little bit better now so i could talk a little bit faster so i hope that's okay uh and today's problem is combination something through it uh okay what is this find all possible k numbers that add up what is k oh well given that only num ones to nine so okay so three numbers n is you go to n okay so i think the thing is that there's no really uh is it unique yeah so there's no really shortcuts about this the answer is that uh given that only one to nine um so the worst case for choosing k numbers out of one to nine it's gonna be nine choose three oh sorry nine choose four nine just five right and nine choose four uh which is should be equal to nine choose five is 126. and what that means is that you're going to do a proof for us after that and if you could do it before then you should do a proof first and in this case because um maybe there's some tricks that you can think about to optimize it if you only need a count but in this case um in this case because you have to output the answer anyway so brute force is going to be the best way to do it and that's how i'm going to do it um yeah uh so this is a good practice in backtracking um you know some people may cause that for search for some reason but i just go straight up backtracking uh there's some in python and other languages there may be ways to kind of pop off the explicit or pop up the state implicitly but it's still backtracking uh okay so let's um let's get started and yeah i'm gonna use a global variable called results uh do i have to be in any particular order i guess not so that's okay uh and then we just oops return results and for me um the way to do this is think about it as kind of a for loop that goes recursively and then and so in fear he give it uh you know given k for example k is equal to three you would do something like for i and da dad for j and da well k and dot right um so forth but if k is equal to four then you have for l and dot right so basically you're just converting this into a recursive function um okay so now let's do that and we're gonna take k one at a time so we're gonna do that and then we're just gonna count from one to nine so let's also keep that so those are gonna be your two states so i'm gonna and the trouble i always have is just naming things so hopefully you have better times than i do but uh let's just quite get remainder maybe um like doesn't get remainder of the away um and then we're gonna go with uh k left which is well maybe just left which is the number of k that is left and also distort and if left is equal to oh because we have to convert uh we have to store the state so we actually have to also um yeah so we should definitely uh keep the array as the current array as well um yeah and just for kind of easier accounting i'm going to keep this uh just the total which is the sum though we don't really need a per se and then anyway if left is equal to zero um then if total is equal to n could be okay um up to exactly right okay just wanna make sure the base case is in this case i'm just checking that if it's exact the end and that just you know this is this way uh for example if it's less than n or greater than n that's how you would change it so it's pretty straightforward in this case we want to do results.pen case we want to do results.pen case we want to do results.pen uh the array uh and then if you're new to python um this syntax just copies uh the entire content of the array into the a new array and then append that to the result otherwise you may only copy the reference so every time you change it uh you may be different but uh but that's the way i do it otherwise you just return uh early actually you should return early united case so let's do that uh and then the other thing is if total is greater than uh n then we also return early don't you could also do uh maybe check for that otherwise let's see uh so now we do a follow from i is in range sub uh start to i guess nine inclusive because the max number can only be uh yeah from one to nine inclusive so i'm gonna write ten here and then we just have to do get remainder uh left minus one because we used one number the new start is going to be uh i plus one yeah should be okay and then next is array plus uh the element of i and then total plus i right uh and then now we just have to kick it off by going uh get remainder of k start should be one uh of empty array and total is just zero and that should be hopefully good let's give it a spin that's why we still do the test uh don't win the number and let's also squeeze in four nine because that's as reset and five nine why not um because those should be the two worst cases um well those are not the two worst cases um there's nine choose four is the number of cases but the sum right so actually i don't know what number should be let's go for 20. yeah so it looks okay the running time seems fast enough the answer looks okay i don't know if this is because just eyeballing but yeah let's give it a summit cool uh and what is the complexity of this right so this is um yeah so this is gonna uh take uh nine choose k uh time so uh it's gonna be at most you know nine choose five uh which is like i said at most like 126 or something like that i don't remember so it's gonna be pretty fast uh and given that nine is a constant i guess technically you could say it's all one um and in terms of space uh it's always going to be um you could say that is o of uh it's output sensitive for one so that depends on the number of things it outputs uh so but it's going to be on the order of um again nine choose four or whatever it is uh so yeah so also of one if you want to count that or one times k if you want but then k is also into the four or five so depending how you wanna call it um but yeah but that's all i have for this prom let me know what you think hit the like button to subscribe and join me on discord and let me know what you think and i will see you tomorrow bye
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
1,696
let's solve this problem let's see today's sleep code problem 5. or six what is that look at me I don't even know Roman numbers uh Let's uh what I'm going to do is I'm going to think at the uh think as if I'm in the interview and I am going to solve this problem so and I'm going to guide uh you or let's say uh talk through these problems as if I'm talking with the interviewer so you are the interviewer and you have asked me this question uh so let's see how should I approach or how should anyone approach this problem because this is the question that I have never seen before um so first thing I would like uh as a um I'm going to ask for like two minutes to go through the problem understand it try to understand it and ask any questions if I have so let's see the timer this one minute so I'm going to take exactly one minute and uh yeah we'll talk you are given 0 in text integer array nums and integer K you are initially standing in one mode you can jump at most K steps forward without going outside the boundaries of the array practice you can jump from index side to an index at this one uh okay inclusion you have to reach the last index of the array uh your score is some of all numbers of C for each written there it is a maximum score you can uh yeah so I understand I'm trying to understand this question so uh what I usually do is I um I talk through some important things uh in at least I think I should talk uh in the interview so first thing uh I will ask or I will tell the uh interview or that okay uh what's the input in this uh in uh this question right so the input is going to be an integer array which is uh zero indexed okay zero uh index obviously it's written here on the left side but still I try to write it on my own so that it's really important that you don't miss some age cases so try to understand it is just an integer array that's the input and there is one more input which is integer k uh what's the K now you should understand what's the K here you are initially standing at okay that's fine uh you can jump at most K steps forward without going outside the boundary so K is how much bigger the jump you can take maximum jump you can take so let's say it's two so you can take two Atmos two jumps like two unit jump or you can take even one unit jump right if you take zero unit jump you will never go forward so that's not gonna count so you can take two unit jump one unit jump or if it is five then five four three two one any jump but it should not go out of the boundary so yeah so that's what it's saying at least for now I'm understanding it in this way so I will talk with the interviewer and if I'm mistake a mistaken he will at least tell me uh think harder or something like um yeah I think it's not correct it's something um different so uh right now I think that's uh that's correct okay so integer K uh now the most important thing you should write is what's the output going to be sometimes in this in any problem uh what happens is you think oh um so this question the output must be an array or something but I have done this mistake hundreds of time or uh not in the interview because I have never given hundreds of interviews but yeah while solving problems that I think out this is the output and I try to solve in that way and then I understand that okay this is not the output so let's see what the output uh is or what they want written the minimum score you can get so here the output is only going to be integer result or something which is uh which is like um maximum score see I said minimum but again if I read here it's a maximum score so yeah you can catch many of your bugs or initial assumptions if you write down the things okay now another thing is you should not do this like directly going you should keep talking while writing these things now another thing I say is okay I asked the interviewer so yeah we have the integer array as an input and K integer K right so uh what is the size of the array can we assume it's going to be some limit or it's going to be a huge uh or uh it doesn't matter so most of the time the array size or some the size of the input uh in interviewer will say it kind of doesn't matter or uh don't worry about it for now just assume it's uh it's okay uh it's taken care of so in that case it's fine but in some cases like uh if you have to use recursion or it's a Brute Force solution then the size Matters and at that time most of the interviewers will say yeah um I think it's not going to be more than 10 elements or 15 elements so if they say that you understand that okay I can just go for Brute Force solution okay so in this case uh let's say the interviewer answers be like yeah you don't have to care about it so it doesn't matter I'll write that and um size and next thing I ask you uh I asked about the values because this is also very important um in case of arrays at least so Wells I read I write down these things so what it means um so I asked um so we know that I know that this is an integer array so do you think we can have negative numbers uh yeah probably we'll say yes you can assume that and what about uh I'm assuming uh we can also have a zero in it he will say yeah that's absolutely right and what about duplicates uh do you think we can have duplicates or um it doesn't matter uh he'll say uh the thing is the interviewer who is asking this question he has asked this to like tens or 50 people in the past so he knows in and outs of this question so if he knows that duplicates are present or they might cause problems so this uh the assumption is not good to have duplicates he will tell you but if you know uh it's very important that you ask and I have made uh made some mistakes uh by not considering duplicates in the array because in most of the cases in examples given right there are not no duplicates present and those are the age cases so you have to have um or at least you should talk uh these things in the interview okay so I think I'm taking a lot of time uh here but this should happen in like uh at most initial five minutes as I am explaining it to you as well um this timer is uh eight minutes now um also um I just don't start the coding right now so I'm just understanding what are the inputs what are the outputs um the main problem and then uh Size Matters or what are the values in it um that's it then I've tried some few things so uh test cases um uh age cases I'll just write it down in and I will say that uh we'll come back to this but let me write down few things so that um I don't miss out anything so I'll go design code and time space so uh so we'll come back to this um I'm not thinking about any test cases or edge cases right now let me try to come up with the algorithm first and then uh we'll go through this letter so now um now I'm going to try to understand the problem come up with the algorithm and uh honestly I'm just gonna do this for uh when this timer is like till 30 and if I don't understand it in 13 minutes then till 30 minutes then we'll check the solution or something in the discuss um but yeah um let's start uh okay so this is the nums array I am at the index 0 and integer K is 2 so the most important thing is you start with the examples given don't create your own examples start with them and then for edge cases and test cases you design your own examples okay so again standing at index 0 I'm standing here and in one move you can jump at most k-steps so I jump here okay k-steps so I jump here okay k-steps so I jump here okay uh without going outside the boundary okay that's that is um inclusive you want to reach the last index of the array so I want to reach three okay and your score is sum of all nums of J for which index J you visited in the ad so if I jump from here to here and from here um the sum of these numbers so 1 plus minus 2 minus plus minus 7 plus minus unknown plus 3 right so you can choose your jumps forming this sequence one minus 1 4 3. underline above the sum is 7. okay so we have to maximize the score so uh in case of negative we can uh so obviously we have to maximize the score right so uh positive numbers uh most positive numbers will give us the right answer so in this case um four three so um yeah uh so what I'm trying to understand is now what kind of a pattern will go here so after reading this question um I'm thinking about two patterns uh one is greedy pattern choose the positive numbers and go ahead or choose a deep solution or um DP solution and one more thing that is coming to my mind is um going backwards from so we have to ultimately reach 3 right so 3 has to be in the array now I can jump from four to three or seven to three that's it right so what's gonna give me a maximum score so if I add this or add this right so obviously four so now I add 4 to it and the result now here I check uh what's the maximum out of these two going backwards is this maximum or is this maximum um it's giving me this and from here I cannot go here but I can only go here so that should be added right so um yeah Okay so now I'm thinking I do not even need this um need this array I can just start going backwards and keep the maximum array so far um to but there is uh but there is an issue right there can be a issue this could be a wrong answer um so far what I'm understanding so next thing I am going to do is okay um it's gonna take like five minutes so um think of discount until 19 or something I'm going to take this question and I'm going to paste it in this so that I can draw something okay uh let's say this is height and oh come on and I'm also going to copy this solution because most of the time one solution is not good invite yeah so um now I'm going to draw this thing uh for this I have already gone through the question right so I just choose the maximum of previous two jumps or whatever jumps and then I um go there right yeah so obviously it's not a right question and obviously um as I'm thinking this as an interview I am a little bit panicked and I know that I don't know the solution for this question that's why um I'm talking anything or doing anything but this is how it's going to be you have to be talking and you have to uh see what are your thoughts um otherwise uh there can be a problem and second thing if you are talking in the wrong direction most of the time interviewer will just say something that is kind of a hint okay uh why do you think that and do you think um what about this case do you think it will work in that case so you have to think about that uh so you know that you are going in the wrong direction with you are talking out loud and if interviewers ask you some questions that means he's trying to interview something or pointing you in the right direction so let's just say this is three so far I have three with me right and I can jump three uh I can take three at most three jumps so two is three I can take any of these jumps so with my algorithm I'm going to choose maximum of it so let's say I add 4 here okay uh yeah so now from four I can take to reach 4 I need to take three steps right so I go back three and I check what is the maximum of these three uh elements so that's 10 so I add 10 and sorry about that okay so obviously this is um uh you cannot go back from 10 so this is first element so uh the answer will be 17 which is right but I still think there is something some problem with the test cases so again I'm going to go here I'm going to take another test case and I am going to figure it out if I am doing a wrong solution or something because most of the time uh the test cases are not designed to give you the right answer initially they are designed to obviously help you but also you might miss some edge cases so let's just start again at 3 minus three so um I had to have I have to have minus 3 in my array right because I have to jump there then uh what happens um six three and three so for me now the maximum out of no I cannot go I can only go two steps back so out of six and three what is the maximum so it's three so add that out of one and four what is the maximum um I add four uh out of uh minus twenty in five what is the maximum minus five and out of one there is obviously one has to be included okay so now you can see um this cancels out plus four plus one which five which cancels out to minus five and output is zero so I think uh this solution is will work obviously if K is like huge let's say uh so now the point you have come up with the algorithm obviously you don't know if it is best solution or is it uh Brute Force solution you just think that okay uh for three examples this is working that means it should work so you should be confident enough that this should work and uh if it's not going to work your interview if he's a helpful he might give you some test cases that do you think in this case it will work or something but let's say it works now I am assuming this will work and uh now next thing is uh just saying out loud and time complexity or trying to calculate what will be the time complexity of this uh algorithm um so yeah for this in this case um I'm checking the maximum of these three elements okay and then I'm choosing four so the thing is um I need to have index of four uh okay and then from that index again I have to check three places back and I have to maintain the index of largest in that right so uh it's gonna be like uh I'm going to go through each element once at least once and then for each element I'm going to uh let's say find the maximum of those previous uh jumps right so um at right now what I'm thinking is uh the time complexity will be o of n number of elements into k uh which could be wrong and I'm pretty sure uh I might say some wrong complexities in most kind of interviews but approximately this is what I think now while thinking of time complexity I just thought of a h k so I will tell that let's say if K is 1 so what do you think um tanza should be the answer should be all sum of all elements so in that case you just have a single if case if K is equal to 1 that kind of is an edge case right and you um is that right so if K is one you can only jump one back so every element should be counted and some of them is the answer um that's gonna be it so yeah that's the edge case another Edge case is like um you and you have one two three four five six elements and you have K is equal to six so you can jump to any element so um any element right so you can just take positives from uh all the jumps yeah um again um this is kind of a greedy solution I am still having some doubts that this should work I don't know why but I have feeling that I'm missing something so for that I'm going to create my own example Okay so let's say um here I'm going to have similar example 10 why it's not white man come on okay let's take this 10 um minus 5. minus 2. 45 3. uh yeah so in this case what should be the answer it should be three Plus uh case is equal to uh K is equal to 2. okay so I will have at least three in it now I can check a maximum of two previous two so five plus maximum of previous two that is 4 and minus 2. um which is 4 uh so 5 and minus 2 and 10. um okay so I'm not going to waste any more time um uh I think this should work so I'm going to start coding the solution and this again this should this is not an optimal solution this is what I think is um I can come up with uh within the time so I will go ahead and start coding it yeah so first thing is a result it's equal to zero to say now what I have to go um I have to start from back and then or can I start from the front what do you say um uh let's take this example I can jump three right so in this 3 I take 10 then I can take yeah it won't work in that way so now the question is how do you code this solution and it has to be good enough right um 10 minus 5 2 maximum is 10. then I add 4. maximum is 4 then I add 0 and i3 is there a sliding window kind of a solution here a better solution so uh this is initial window so I choose this so next window is this uh so I chose this okay so next render is this okay uh so what I will do is I will not waste any more time I am I can sense this there is a better solution uh in one pass without checking elements again and again but uh I cannot think of it right now so I will just say that okay I am going to go with the correct solution uh as a priority and then I'll try to optimize the solution okay so let's see how can I go okay uh this is zero so index current index is length of nums minus one okay and then what I'm going to do is for mm-hmm how should I do this cannot use four okay so while current index is greater than zero greater than equal to zero what I'm going to do is result plus equal to nums of current index right that's the first thing I added the last element then find the largest in previous K elements right and set its index as current index okay um how can I do that in Python um it's going to be I'm thinking and the largest in previous K elements questions the question um how can I know let's just say I write up function which returns me a tuple so what I'm going to say is idx so current idx is equal to find previous largest okay and values will be value will be current idx comma okay uh if I write this solution I'm pretty sure any interviewer is going to reject me but again um it's not to just um your optimal solution it's just to show that yeah you can come up with the solution okay let's be positive yeah and the previous largest okay I get the index and I get the k yeah and I have to find the largest right so let's say largest is going to be minus float Infinity okay and then for I in range idx minus 1 minus k TK till idx so what is this is uh I have to start from K elements before so let's say 0 1 2 3 4 5. so idx is now 5 and K is 3. so 5 minus 3 is 2. 0 1 2 right from here till idx till 5 so from starting from 2 inclusive till 5 3 limits so I don't need this minus 1. okay so starting at -3 elements till so starting at -3 elements till so starting at -3 elements till uh the current index okay uh largest index as well say it's set to index okay and if nums of I is greater than largest complete largest is equal to number I and an index is equal to r once this is done I just need to return and index right so in this case what happens is it starts at 2 minus 2 is greater than largest uh whatever the minus floating feet infinities so I set this index then I go to uh this 4 is greater than minus 2 so I set that as last index I go to 0 and then I come back here now there could be a problem that you are going Beyond uh the limit so what I can do is starting from Max of this comma zero we don't want to go beyond zero so let's say you are here and you do minus so 1 minus K is minus 3 so you start from minus to this so that's not going to work right so um I was good enough to find this solution um at least a bug um let's see um okay I'm pretty sure this is going to fail but for my uh satisfaction I'm still going to go ahead and complete this now what will happen is um okay and current index we will just keep repeating we'll just keep repeating uh current ly next break and let's return result oh my God I wasted 40 minutes okay let's solve the Box let's see come on oh now you have to understand that when your test gets runs right this is the most satisfying thing and now you can just say code is written time complexity is Big O of n star k and star dot k and space you are not using any extra space so space is we go one um I'm pretty sure it will fail for multiple test cases oh to my surprise it's passing for this um but it will not pass many of the test cases because I know that this is not the correct solution um there has to be a better one so we'll go through a discuss section and we'll find out but let's see uh what are the test cases that feels yeah um it's feeling some big test cases um okay so without any uh more let's check discuss and best solution that could we can find wow this is crazy I don't even want to read it this one um monotony Q yeah it came to my mind but I didn't think it's going to be this problem is very similar to problem this okay we'll see that let us ask the question what is the maximum score we can get when we reach the index I it is equal to sums of 5 plus maximum among the previous K or less if we reach the boundary numbers the idea is exactly the same as we use okay ah honestly this kind of solution came to my mind but as I said the initial uh running through the uh the test cases gave me a confidence that my solution will work um so I went with it yeah so let's try to find out uh what this solution is doing let's DQ be the monotonic DQ this is pretty standard uh algorithm monotonic increasing or decreasing Q okay is a DQ where element inside will always decrease in fact we keep indexes not numbers okay got it uh so this is better because we are keeping the indexes so while DQ and DQ of 0 is less than I minus k oh this I don't understand so the first element in the DQ is if it is less than I minus K this has to be DQ of I minus K right uh okay we are keeping the indexes DQ dot path left uh this line removes all outdated elements from the TQ yeah now I understand what this line is doing is um if you reach so let's say if you are here and uh or let's say if you are here and in your queue you have all these elements so far added but the case two right so you only want these two elements to be considered so this that sentence is deleting this element so index we are taking here index and not the value at the index here we are checking value at index so now what this means is uh you will only store the queue in decreasing order so let's see now the queue is empty so you will store 10 here let's take this example then minus 5 so you it is decreasing so you store -5 you store -5 you store -5 okay uh you minus 2 is decreasing so you store minus 2 now uh now this is a limit so When You Reach here obviously you can have still the limit is not reached okay you have to add a 4 right but you don't add a 4 here that's the beauty you add you before adding four uh if you add 4 here this is not going to be strictly decreasing it will increase here so you pop this element of this element and you add four uh in our case We'll add index and then we go here now 0 is decreasing so that's fine uh now once you are here uh you cannot have 10 again so in that case the first line was deleting this 10 from the queue and now top of the queue is 4. and I believe once you are you have used that uh you should pop it as well so yeah and then you add three so you cannot add three because uh this is zero so you pop zero uh there is no four so you add three and then you add top of the Q three and you pop it so at the end the queue is empty you have finished the scanning through the array and uh and you have the result okay cool and this line is doing that so while DQ and numbers of I is greater than numbers of top uh the last element is greater than then keep popping it and once you have popped all the Lesser elements on the grid oh yeah all the Lesser elements than current element you append that okay so uh why you are returning numbers of minus one I'm sorry why not returning numbers of minus one foreign place hmm yeah and this is something I didn't understand okay I believe this is this uh this question has gone like one hour so I should stop this video and uh submit this hey it's a progress at least you ran through initially initial things right initial test cases sorry yeah up so yeah bye um it took a lot of time I should probably think of it as solving the problem in less than or less than 20 minutes yeah that's the ideal thing for YouTube but yeah this is for my um theme yeah so ideally the interview is like one hour long so anyways um see you always view bye
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
392
so our question is to find the subsequence so we have given two strings so we have to return true if s is a sub subsequence of T so we can say that ABC can occur in this string if we remove h g d so a B and C similarly a c there's no X in this and we only have a and C we don't have any X between them so it is not a subsequence so we can use a two-p subsequence so we can use a two-p subsequence so we can use a two-p pointer approach here so we can not exactly a two pointer but we can keep a pointer for this string and a pointer for this string so whenever we find a character that matches a character in s we can increment both the pointers so that means we have found that character and if we don't find let's say we match a and we move to the next character so we match B and H we can see that they don't match in that case we will just increment the pointer for B because that H is not part of the subsequence that s is so let's try to code this and so I can just have a pointer for S so I can use I and J and I can set them as Z and zero I can have a y Loop here where y i is less than length of s and J is less than length of t so if s of I is equals toal to s d of J we will just increment both the pointers otherwise we can increment only J we can combine this statement to just like this and after that whenever we are whenever the Sub sub whenever this is a subsequence of T all the characters of s should match with this right so in that case our J Point our I pointer should point to the length of s if it doesn't because let's say in this case I will only stay at zero right I will only stay at one so that is our final check to return the solution we will just check if J is I is equals to length of s so this should work yeah we can see it's working and the complexity is biger of n so yeah big go of length of T so yeah this is a bit pretty simple uh question thank you
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
727
hey what's up guys this is john here so uh so today let's take a look at this uh 727 minimum window subsequence uh heart problem you know i think this is a good one okay let's take a look so this is like another classic like two string problem you know basically you're given like a string s and t and you need to find out the minimum like con contiguous substring basically substring right uh from s where the uh where the t is a subsequence of that substring and you need to find the minimum of that okay so okay and if there's no such window in s then covers return empty string and if there are multiple such minimum last unless windows return the one with the left most start index okay so now basically not only it asks you to return the minimum length it also asks you to return the actual substring itself okay um i mean so basically for those kind of like a two-string problem you know this like a two-string problem you know this like a two-string problem you know this is like i think it's pretty obvious it's like a dp problem right and with those kind of two string dp problems you know there is a like certain there's like this template basically you know we just define the dp right so we just when we define the dp here we always follow the current uh we basically we can just copy the we can just copy whatever uh the problem is asking us to do here and so basically in this case right so what the dpij means what it means that uh starting from zero to i okay and this one is from zero to j okay which also like ending with i and ending with j so the reason we are like we need to make sure that it's ending with i and j's because we will be using the last two the like the i and j character right to do uh some to do different things here so basically the dp i and j here means that uh from zero to i uh and also ending with i uh what's the minimum constraint what sorry so what's the minimum substring right that's from zero to i that contains which is the uh so uh let me give you some examples how this thing works right basically you know uh let's say we have uh x and y okay x and here we have i here and we have a y this is j okay since we're defining like the defining dpij means ending with i and j okay and we are we're trying to see uh the value of the dpij it means that the uh the basically the smallest substring length the minimum like substring length uh ending with i that will that includes the j here okay so basically the reason i'm defining it that way is because by following the uh the problem itself the description itself is it's always usually the easiest way of defining the definition defining the dp here so okay so let's say for i and j so for all these kind of two string problems they're always like gonna be two cases basically if the uh s i okay equals to the j i the ti the t j so the fir there are always going to be two scenarios here so either this uh this is character is the same as the j's character okay so if that's the case what's going to be the dp dpi here so if the current that the last two characters are the same okay then the uh we okay so don't we know that okay that's fine because i and j are the same then we can just uh just try to compare what's the minimum length from here to here right because we already know that i and j they are they're already matched okay so basically this means that we can just simply do the i minus one j minus one plus one remember we're storing like restoring that like the minimum length of this of the dpi minus one j minus one to it okay because let's say for example let's say the uh the minimum length that from here to here like a let's say in the case of s i equals to t j here let's say the minimum length is two which means the minimum uh actually we it can it cannot be two here because it because for the y here at least we need three let's say with uh the length is four for like the for the dp i minus one j minus one okay it means that okay we have a four uh a length of four substring that can i will contain like this uh yy as a substring as a subsequence then from here right we then we know okay since i and j are the same then we can simply include this i right so that uh this four plus one will definitely uh includes this three y plus j because i and j are the same that's why we can simply do a plus one here okay else right so what's the house else means house means i and j is there is different okay if i and j is different then we have to rely on basically we have to rely on the still the i minus one dp j equals to dp right uh i minus one but in this case it has to be j plus one uh oh sorry oops did i oh come on uh okay sorry i think i messed it up here so uh i j okay so if it's different if it's the ing is different then the dp okay uh i and j will becomes what because since the is not the same as j then we cannot rely on the item to match this j here basically we have to rely on everything b before i to match with the whole uh the whole target string here which means we're gonna have like a dp uh i minus one j okay yeah so basically that's the case that's i it's not the same as has js i basically that's on the only two options here you know and see for the problem let's say what if like let's say what if the uh from here from the sp from the dpi minus one there's no valid let's say there if there's no valid like substring that can match this y or either y or with the y plus j here then this like this dpi j will be like uh an infinite will be gonna be the infinite biggest number here so that in later on we will treat that number as like as the invalid answer okay and cool so and let me try to start coding here um i will try to explain a little bit more while i'm doing the coding here so basically you know uh first we're going to have like a s and n here right to uh to get the length of both the s and t and then i'm going to define a dp right as uh i'm going to start with the beginning at zero okay and then like as usual as we do uh n plus one right for this thing in range and plus one okay so and then we start from i uh in range like one two uh what m plus one and then or j in range of one to n plus one okay so like i said if the i minus one equals to the t i minus 1. we do i minus 1 because the uh we're using like the i represent the length which is the one base but uh the s the characters for that length is 0 base that's why we do i minus 1 here dpr i j equals to dpr i minus 1 j minus one plus one else dp i j equals the dp uh i minus one a j oh i think i'm sorry i think i made a mistake here so we also need to uh plus one here because the dpi and j means that i mean the uh it's it the ending like character has to be the current i here so which means let's say we have a for the house here right y and j here even though the i and j is different right so the for the i if the ing is different so we need to use this one to tell us uh what's the rest of the length of the substring right that compare that can contains this y this uh entire string here but still since well we are like uh we still need this i here that's why we also we need to add a one in the end regardless because uh here we are we're saying that okay so this dpij means that we ending with i here okay so cool so i that's that but as you guys can see here since we have a i minus one j minus one like i said and if there's no valid if there's no not a valid answers we need to set those values to be at the biggest number okay so how can we do that right i mean we just need to consider like a two uh edge cases here basically the first one is the dp 0 j and the second one is the dp i zero okay so the first one this one means that i mean uh we don't have any s string here so as string is basically is empty but we're trying to find the uh all the we're trying to find the substring right which means there would that means it's an invalid answer in that case okay that's why for that for j in the range of one m plus one here okay and uh it means that the dp like zero j equals to the system dot max size so the reason we're doing we're setting it to the max value is because in later on we'll be doing like the minimum value here right so i mean so that's why for everything that is empty right we just uh we just set it to the max size and when it comes down to the like this dp uh transition function here right i mean let's say for example if this thing if this uh dpi minus 1 cannot contains this y j here cannot contain the target string basically we'll go back here this will plus 1 and plus one in the end here right whenever it is empty so here we're gonna have like a biggest a max value here okay that's why i mean that's how we use this one as a base case okay if there's no match for this for the substring and the target at all in the end this dpij will be like the max number okay cool so and another case is this one basically for the dpi of in this case basically the t is empty so when t is empty but the ice is not empty what does this mean means that uh basically anything right so anything that any substring for ending with i will would will have the zero as a minimum substring length because since t is smt and with the minimum substring to contain an empty string is also an empty string right that's why the minimum length is zero since we have already set everything to zero we can just uh skip that part okay cool so that's how we uh initialized our dp array here to the array here but so by this time it's finished we remember we cannot simply return the dp uh dpr m and n like the other like problems why is that because right now the dp m and n means that ending with the last character what's the minimum like length that contains this t here but as you guys can see the answer is bcde here right which means it's ending with like this character e here it's not ending with this one so that we cannot simply return this instead we have to do a for loop here basically we need to loop through all the places and we check if any of them when we need to find the smallest number of the smallest length among all those kind of dp results okay so to do that uh we need to maintain like a max current maximum length a system like max size okay and then uh we're simply gonna besides the current max length we also need to uh maintain like the position of the uh of this uh of the max of the smallest length okay so it's going to be a minimum length here okay of this minimum length because we need to return the uh like the actual string here okay and then like so for i in range of uh one plus m plus one here okay actually you know since i think we can simply start from the uh from what from the uh from the length of t here okay so why is that because you know we need at least four we need at least the same length of the characters sorry uh same length of the characters as a t here to be able to at least to do a match to have a sub string that can contain everything in t here but i think it doesn't really matter because i think we just do a start from start everything because you know for everything that's before that right we'll definitely have like a max number of that so we can just simply uh rely on the uh the values to help us eliminate that part basically i mean the dp i and n right so why we do i n here because uh since we're trying to i match everything we're trying to match uh the whole t here that's gonna be our end goal right that's why the second character has to be n represents the whole t here and i means that at each position okay if this length is smaller than the minimum length okay and then and for those actually so here you know i think we're going to add like a plot uh do a plus one here i mean for those if i if you guys are not using like python or java or something i mean a small trick here is because we are doing like plus one here if we uh use this one as like a starting point you may get a an overflow okay so instead we can just simply do a uh divided by two here okay so that we it to make sure it won't overflow okay and also here i'm gonna also do a divided by two here okay but since this is it's a python i think python can automatically increase that but i'll just do a divided by two just to be safe here and then uh the minimum length will be equals to the dp i and meanwhile we also like update the uh the position of i okay the position of i yeah and yeah actually the length i mean is the length right so the position is i minus one in this case okay so and now we just we need to do a sim uh simple check here basically we need to check when we should we need to return the empty string basically i mean we can do two things right i mean we can check if the minimum length right if the mean length is like uh is equal to the system is equal to this okay and then we simply return like empty or we can check if the position is like uh is equal to the minus one then we return the empty okay else what else we just return this right since you know we have the position here so the position is like and uh basically you know this is the ending position actually so i mean it's the ending position right because we are we said this i mean says everything that's ending with i here so with ending positions how can we find that right we just need to find uh the ending position minus the minimum length okay and the plot plus one that's the uh that's going to be the starting point and for the ending point we do end point uh actually you know what so here i'm going to do this yeah position okay so this will just uh happens to be uh that the last location plus one because i'm just utilizing this like the zero base and one base trick here otherwise you know since the if this is like the index the ending index instead of to get everything including the ending index i have to apply i need to do a plus one here okay right but anyway so that's that okay let's try to run the code here oh sorry so j means n not m sorry ah j here okay cool so this one test case passed let's try to submit it all right cool accept it all right so uh real quick so for the time and space complexity i mean it's i think it's pretty straightforward right so i mean space is of course the o of uh m times n okay and the time is also like here right it's also uh like m times n okay i mean this one it's like a little bit of variation of the uh the other like two string problem you know and but still that it's i think it follows still following the same like template where the uh you just need to define like a 2d array here 2d dp array here and with the uh the length plus one as the size and then here you still follow the same template basically you compare the uh if the i and j are the same okay but in this case like uh the explanation is a little bit different because though if it's the same then it means that uh we can uh throw the uh the answers right let's throw the answers to the i minus one j minus one because we know the j minus one i minus one they have already been uh matched to i and the j character okay otherwise we cannot throw j away we have to also in we also need to include the j because the iron j is uh is different so we cannot uh rely on the eye the ice character to match j we have to uh match everything that's ending with j with the uh with the i minus one characters and here we do a plus one because we are maintaining the minimum length the length of the uh of this uh ending with i and ending with j okay and then we are doing this one to make sure we have a base case for all the invalid scenarios okay and then the last thing will be uh once we have initialized the data we need we cannot simply return the last one from the dp because uh i mean that the ending plate the substring the ending the substring can it could be ends at any anywhere okay so that we cannot use the last uh the last ending letters here we have to go through uh everything from start to the end and to find out the minimum length okay that includes the that contains uh this all the target and letters and then we also like um maintaining maintain this like the end position and from the with end position and the minimum length we can in the end we'll get the uh the final answers which is the uh the substring itself we need uh cool i think that's pretty much it is i can think about this problem yeah let me know guys uh if you have any questions and if you want me to add some other explanations yeah i'll be more than happy to do that otherwise and stay tuned and i'll be seeing you guys soon yeah bye
Minimum Window Subsequence
minimum-window-subsequence
Given strings `s1` and `s2`, return _the minimum contiguous substring part of_ `s1`_, so that_ `s2` _is a subsequence of the part_. If there is no such window in `s1` that covers all characters in `s2`, return the empty string `" "`. If there are multiple such minimum-length windows, return the one with the **left-most starting index**. **Example 1:** **Input:** s1 = "abcdebdde ", s2 = "bde " **Output:** "bcde " **Explanation:** "bcde " is the answer because it occurs before "bdde " which has the same length. "deb " is not a smaller window because the elements of s2 in the window must occur in order. **Example 2:** **Input:** s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl ", s2 = "u " **Output:** " " **Constraints:** * `1 <= s1.length <= 2 * 104` * `1 <= s2.length <= 100` * `s1` and `s2` consist of lowercase English letters.
Let dp[j][e] = s be the largest index for which S[s:e+1] has T[:j] as a substring.
String,Dynamic Programming,Sliding Window
Hard
76,674
994
uh hey everybody this is larry this is the ninth day of the august decode dairy challenge uh let's get to it uh hit the like button hit the subscribe button and join me on discord and let's get to one oranges uh okay in the cellar of empty cell fresh orange and white oranges every minute of any fresh orange that's adjacent to uh in a while manager gets one we turn the minimum number of minutes that must elapse until no cell has a fresh orange okay if this is impossible you turn negative one okay uh and n or the number of rows and columns is less than ten so we can probably just simulate it so you could simulate it but it also seems like it's a shortest path problem because the longest time is just the um the distance between well yeah the distance between um uh any orange and or any wine orange to the furthest fresh orange and we can do that pretty straightforwardly so let's yeah let's do that with a breath first search that i think that's what i want to do um as the shortest path so yeah let's just do roses um okay hmm yeah okay i think that's okay so now uh yeah let's just make it a hash we could probably make it uh a rose by column grid but it doesn't really matter i think i know we have to uh do this populate it first x y is equal to what's it is two to one okay and now we just have to do uh yeah x y distance is equal oh this is a it's always forgetting too late on and then that's okay so latest is equal to max of latest of d um negative theta and now we just have to for dxdy in uh okay and now if this uh this is equal to one of course and if that's the case then we can i think by setting this we don't actually we have to worry about distance but uh let's play around with that oh just a negative one answer so i don't think we got that one uh which is fair so yeah definitely did not get that case but uh yeah so now just have to go for just making sure that order i mean there are different ways to check this but if there's still a fresh orange return negative one yeah and that looks good i'm going to submit because i'm a little bit confident today uh yeah accept it so what's the running time uh each cell will it's going um each cell will only get um queued up at most one so it's going to be linear in terms of the input which is rows times columns um in terms of space well we still have something for each uh cell as well so it's also going to be linear which is rows times columns as well uh or o of r times c or something like that but yeah uh this is pretty interesting um a pretty foot uh let me know what you think um yeah i don't really think i have much to say about this one because it's just my first search um i don't uh and once you do the reduction to the shortest path i think this is straight forward uh so it's maybe goes to say it's a little bit of a flat feel but um but except there's a distance component so that makes a little bit uh not quite but uh yeah let me know what you think hit the like button and subscribe and i'll see y'all tomorrow bye
Rotting Oranges
prison-cells-after-n-days
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`. **Example 1:** **Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\] **Output:** 4 **Example 2:** **Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\] **Output:** -1 **Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. **Example 3:** **Input:** grid = \[\[0,2\]\] **Output:** 0 **Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 10` * `grid[i][j]` is `0`, `1`, or `2`.
null
Array,Hash Table,Math,Bit Manipulation
Medium
null
1,359
hey everybody this is larry this is day six of the lego daily challenge hit the like button hit the subscribe button join my discord let me know what you think about today's problem i'm in the airport right now i met it in uh mesut again and i'm going back to new york but i have maybe an hour to the fight so hopefully i'll finish this prom uh but yeah let me know what you think and hit all the buttons or whatever now today's problem is 13.59 count all right today's problem is 13.59 count all right today's problem is 13.59 count all right pick up and delivery options and it's a hard problem okay so hopefully i get to finish this otherwise i have to finish when i get home okay so there's a mod so let's get that so i forget that a lot so let's get that into the place uh and then maybe something like this okay so what do we do count already pick up positive such a delivery okay um wow the first thing that i would say about these problems is that usually i will um uh prove not before us but well maybe before if i have to but i would um you know like using pen and paper manually create the first few um and then kind of see if i could feel a pattern sometimes i will also prove force just to see a pattern but you can see that this actually grows really fast from one to six to ninety um so uh there is also a website called ogis um so you can look that up um but i'm not going to do that because you i you didn't watch this video as you know so that someone could tell you to google something right uh so i hope not anyway i don't know but anyway i'm gonna challenge myself so okay so let's start with n as you go so n equals uh okay n is equal to one there's only one case which is uh i don't know how to i guess the same notation they do right then n is equal to two so then okay so then that means that you take the previous thing um and the previous thing had two items right um this is almost like dynamic programming or memorization but now i'm doing it bottoms up but manually and try to figure out the logic so here so let's say you have two items right so then now how many places you can put to pick up um that means that you pick up in three places right um yeah and then well and then the drop off if you put the pick up here then you have one two oops three places um yeah so then that means that there's three plus um and then let's say we put the pick up here then we have two right so three plus two plus one you can kind of extrapolate a little bit for example we have p and a d here then that's three plus two plus one right okay i mean of course this is going to be 6 and that's 6 times f of 1 because well in this case it doesn't matter because there's only one example so this is 6 which matches so then n is equal to 3 means that you have four of these right and then now you have um yep let's say we have put p here then one two three four five uh plus four plus three plus two plus one so that's i don't know what that is right uh that's 15 times f of 2 because um for here one of every x you can um there are six different ways to do this thing right now so that means that there's six different way of having these x's if you want to say that like fill it in the x's um and because there's six different ways then you have 15 um ways to kind of put in the new ones on each of those six so that's why your 15 times 6 is equal to 90. so i think this um so i think now we have a good idea um i don't know if it's a good idea but we have an idea to play with um we can kind of even try it out for do uh yeah so we have four things so you have six prior things right um so this is gonna be let's say we have put p here then you have one two three four five six seven so seven plus six plus five dot plus one so that's what uh i'm always bad at this actually uh is it dirty six times for 21 no it's the other way uh 56 28 right is that right i always so that's 500 yeah okay i think this is right seven times eight over two right it's the idea i always forget if it's plus one or minus one over two that's why i always mix them up like a lot so this definitely equals three is equal to um 28 times 90 which is equal to i'm just plugging in the calculator now that i could do my head 20 right and of course um you should be able to verify this but i am going to cheat a little bit and just run the code this will actually give me wrong answer or not compiles or have to run it again but if this is right then i think we have a good pattern uh and it seems like that's correct right so that now we can play around with um with how to generate this sequence right so answer is equal to zero and then now we have um let's see oh maybe n is equal to 1 um how do i want to say i mean we can do the constant way and then now for i it's in range from maybe one to n plus one m plus one being exclusive bang of course um or maybe start at two yeah maybe start at two because one is just one right um and then now what is this so two means that um two means that the previous number is one so i minus one right because for example three is we get two times two so this is times two times this right um and then now you have this plus one num is the number of gaps right okay so let's put it backwards uh previous uh let's just call previous number of uh barriers or you know like a thing so yeah previous okay let's go previous right and then now you have uh pickup possibility as you go to previous plus one because that's just the number of gaps oh yeah the number of spaces you can put to pick uh right like for example here you can put one two three four five so that's just previous plus one um and then after that the drop off uh the total drop off the total is equal to pick up times pick up plus one over two right so that's this part and then that is of course times the previous answer so and in this case that means answer is you go to answer um i mean we can you can uh okay i'll try to make this a little bit clearer right so um next or current is equal to the pre answer is like technically the previous number um we can extend it to an array we like but times total um and then at ray n answers you go to current right um of course i probably should do more mod math here so let's do that here i think this is a good place for it um yeah let's give it a spin i think this is maybe right oh i didn't do n oh this is just small and okay again yeah that looks good of course let's try for some bigger numbers but i would say this problem is a very common torquey very mafi problem this looks good for random numbers so let's give it a submit unless i do something weird um so definitely oh that was the first time i saw this 705 day streak from the airport i met it in so yeah this is obviously going to be linear time linear in the size of n but technically exponential in the size of the input um so yeah because n is you know number of bits and stuff like that and of course space is going to be just technically constant technically linear you know you want to say depending on the size of the input which is a number of course uh the mod will bound it by um 32 bits or whatever right in this case maybe 31 bits but the same idea um yeah so this is a combinatorical problem and i don't know that i would think i don't think this will show up on an interview to be honest but it is a good fun problem if you like commentaries or math or something like that um cool i think that's all i have for this one i'm in the airport after all so i'll see you later stay good stay healthy take your mental health take care bye-bye
Count All Valid Pickup and Delivery Options
circular-permutation-in-binary-representation
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1. **Example 2:** **Input:** n = 2 **Output:** 6 **Explanation:** All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. **Example 3:** **Input:** n = 3 **Output:** 90 **Constraints:** * `1 <= n <= 500` Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Math,Backtracking,Bit Manipulation
Medium
null
1
in this video we're going to take a look at a legal problem called two sum so given an array of integer nums and a integer target return indexes of two numbers such that they add up to a target so here you can see we have an example of two seven eleven fifteen so the target is 9. so the goal is we want to return the indexes of the elements in the array that add up to the target so in this case 2 and 7 add up to target 9 so we return it's in their index in this case 2 has it index of 0 7 has an index of 1 so we return that in array and here you can see we have another example 3 2 4. so the target is 6 and in this case we just return the elements the index of those elements that add up to the target in this case 2 and 4 add up to 6 so we just return their index is going to be 1 and 2. so here you can see we have another example of 3 and the target is 6. so ideally what we can do is we can um use the element twice three and plus three will give us target but the question says that we cannot use the same element twice so we need to make sure that the elements are not the same right so in this case three plus three in this case this the other three will give us a target so in this case the indexes will be zero and one right so in this case the only one valid answer exists right so the goal is that there will be valid answers and if there's no valid answers basically we're just going to throw an error or what we can do is we can just return a um emptied array right so anything works basically to solve this problem one way we can do this is we can use a nested for loop and i'm going to show you what that looks like so in this case here you can see we have a 2 and 7 right so if we have two and seven uh what we're going to do is we can be able to iterate and starting from the first element right here which is two and then we just use a nested for loop and then just try with each and every single combination we'll try two with seven right two plus seven we see if that gave us the target if it does we just returned index if it doesn't we're just going to continue try always two and eleven and then we're gonna try was two and fifteen then we're going to move the eye pointer uh one to the right we're gonna try with seven and eleven seven and fifteen eleven fifteen and so on right so we'll just try with every single combination for adding the sum to get to the target so that will that would be one approach but this will give us a time complexity of big o of n square so it's not the most ideal approach right it's not the most ideal solution so what we can do is instead is we can be able to uh use a hash table right and be able to cache the result on the table and be able to bring the time complexity down to a big o of n because for hash table it will give us a constant on average for look up a value in table in the hash table right unless we are using array so what we're going to do is we're going to have a table and the goal on how to solve this problem is that we basically just going to say in this case the target is in 6 and the current value is three so what this what we really want is that we want to see if there is a another three in the array if there is another three in this array then we basically found our sum we found our num we found our two sum right so in this case we have three here we want to see if there is a three in the array if there is we can just return that index and as well as the current index and then return that in array form right so we can do is we can use a table um right what we can do is we can use a table that has a key and a value and then the key is going to be the elements value right so in this case three has an index of zero then we're going to have two and has an index of one so the value is going to be the index and we also have a value of four which has an index of 2. so all we're going to do is we're just going to do a one pass right in this case we're just going to iterate um all the elements in the array first we're going to save their value their current value as well as their index in the table then we're just going to iterate starting from the first element all the way to the last element and basically all we're going to do is we're going to get a difference between the target versus and the current element so in this case the current difference is six uh it's three so we check to see if there's a three in a table that does not equal to the current index in this case is going to be zero so we check to see if there is a three in a table in this case it is and the index is zero which is equal to the current index so we do not want to use the same element twice so in this case what we can do is we can just continue to move on to the next iteration now we have two so two six minus two is a four right so in this case we have a 4 for a difference so we go to the table we check to see if there's 4 in the table in this case we do so its index is different is does not equal to the current index which the current index is 1 right so in this case what we're going to do is we're just going to add the current index onto the array and then this index onto the array as well so now at the end all we're going to return is one and two right so that's basically our result now before we continue our video i want to talk about how can my channel better prepare you for your nest coding interview so if you're currently preparing for your next coding interview i have a playlist where i should see a section in my channel called algorithms which i cover the most fundamental uh most important things most important algorithms that you should know things like bfs dijkstra topological sorting and all the sortings that you should know and data structures i cover wide range of data structures from array all the way to trees heaps graph tables and so on and i also have a section cs fundamental which i cover bigger notation solid principles and so on and there's a one important category which is going to be the leeco by categories so i basically sort all the leeco problems that i did in categories so basically here you can see i have two pointers which is one category sorting usually in using min heap max heap and applying sorting algorithms and so on uh sliding windows greedy algorithms binary search array and string tree usually in binary search tree dynamic programming link list search and backtracking so i hope that you can use my resource to better prepare for your nest coding interview so let's continue with our video okay so let's take a look at another example let's say we have three and three right so let's say we have three and three okay so pretty easy example what we're going to do is we're going to use a hash table to get the result in this case we're going to have a key and a value okay we're going to have 3 which has we're going to iterate the entire array to get the value the current element as well as their index so we're going to have a 3 and their its index in this case is going to be 1 right because we're going to first we're gonna have index zero then we get to this element right here this element it has an index of one so we over we just basically change that value to one right so now we have three and one so then what we're gonna do is we're gonna first start with this element we're gonna see if there's a three in the table in this case we do then we see if that index is different to current index this case the current index is zero right because six minus three is equal to three so we check to see if three is in the table in this case we do right and that elements value and that keys value has a one is different than zero so we return both of those index in array form okay so hopefully we go over those uh weird cases let's try to see how we can do this in code so to solve this problem basically you can see here we're going to have our table right we have our hash map key is going to be integer value is also going to be integer we're going to do a pass in this case one pass to get all the elements and their index so in this case we're going to have a table that going to have a key and a value and the key is going to be the element's value and then the value is going to be the index of that element in the array then we're just going to have a for loop to iterate each and every single element and get its difference once we get this difference we're going to check to see if that difference that element contains in the array in other word we're trying to see if that element is contained in the array num array that would that were given right do we have that difference do we have that sum do we have those two sum in this case if we do have those two songs we can be able to add those two elements up to equal to target so what we're going to do is once we're going to get our difference we're going to see if that element is in the hash map and we also want to see if that element does not equal the current element because we do not want to add duplicate elements and at the end we're going to return integer array that has a hashmap.getdifference that has a hashmap.getdifference that has a hashmap.getdifference and i so i is going to be the current index and then uh hashmap.ear difference is going to be uh hashmap.ear difference is going to be uh hashmap.ear difference is going to be the index of that difference element right so time complexity in this case is going to be big o of n or they go up to n but we just drop the constant so we're going to have a time complexity of big o of n and the space complexity is also going to be big o of n because we're caching the result onto a hash map so as the input size scales the space complexity this the size of the table will also scale so in this case the time complexity and the space complexity is all going to be bagel of them so there you have it and thank you for watching
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
11
hi everyone in this video Let's solve lead code problem number 11 container with most water the problem states that given an integer array height of length n where all the elements of vertical lines drawn such that the two endpoints of the ith line or I comma 0 and I comma height of I we need to find two lines that forms a container with the x-axis container with the x-axis container with the x-axis such that the container contains the most water we need to return the maximum amount of water a container can store for example for this input array the answer is 49 because we form a container with height 8 and height 7. and the water cannot flow Beyond height 7. and hence the area of this shaded region from this example is 49 which is coming from the minimum of two heights 8 and 7. but and the distance between the two bars so our example the eight is having an index one and seven is having an index of eight and hence the distance between these two bars is seven and the minimum of the two heights is again seven so the height of the Shaded region in the example is 49. let's take two random bars from this graph and try to understand the problem before we solve the problem now this is my input hide array from the first example and the bottom row just points the indices of different elements of the array if we plot this in a graph this is how it is going to look like now let's randomly pick two bars from the input let's pick these two and if you were to form a container between these two heights how much water can we add into the container let's fill the container with water and see how much the container can hold after which the water is going to flow out of the container so as we start filling we notice that the water can reach a height of 4. after which it is going to flow out of the container so the max height of this container with which we can fill water is going to be 4. and the distance between these two height is the distance between the index corresponding index and that is pi minus 2. now if we were to find the area of the Shaded region we need to just multiply the width and the height which is going to give the area of the container and in our case the width is the distance between the two index which is 5 minus 2 and the height is minimum of 6 and 4. in other words this is how we are going to find the area of water within the container so the area of water within the container is going to be distance between the two indices and minimum of the height so in this example is it is 5 minus 2 multiplied by 4 so 3 times 4 the area of this container is 12. now let's take another example let's take these two Heights and we know from previous example we cannot fill water more than the minimum of these two heights so if we fill water with inside this container we cannot go beyond height of 2 after which it is going to flow out of the container now the area of this container is going to be the same width into height and the width here is 7 minus 3 which is 4 and the height will be minimum of 3 into that is 2 so the area of water in within this container is going to be 4 into 2 which is 8. now that we understand the problem let's see how we can solve let's go back to our input graph and to start with we are going to stall this in a Brute Force approach The Brute first approach is going to be uh considering all the different combinations of heights calculate the area of water within all the containers and then find the max among them so we will have our right and left pointer pointing to the first two elements now we're just going to find all the combinations of containers of our input array and then we are going to just calculate the max so for example if these two are my Heights of the container we know that water cannot flow beyond the height of one which is the minimum of 1 and 8 in this example so if I fill water I will have water up till this point and hence the area of this container is just going to be uh difference between the index and the minimum of 1 and 8. the minimum height in any example is just going to be a limiting factor which is going to limit the height of our container so no matter how big the other height is the shorter height of the container is always going to limit the height up to which we can fill water so in our case uh this example the limiting factor is one so the second height which is of eight length irrespective of what height it is even if it is high 100 it doesn't matter because we cannot go beyond one and one is our limiting factor here the area of this container is just one because the width is one and the minimum height is one and since this is our first container in The Brute Force approach the max area at this point is just going to be one and we move on we move the right pointer to the next height notice that since one is a shorter of the two numbers it doesn't matter how big the other height is the height of the container is never going to exceed one as I said one is the limiting factor here and the area of this container is two just because the width is two the height didn't change but the width is 2 and hence the max areas two and we move on now again we increase the width but the height never changed as always one is the limiting factor uh since it is the smallest of the two heights the height is never going to go beyond one the max area is three uh because it is more than the previous Max area so we update the max area and move to the next height and the width is four now and hence the area is also four and we update the max area because it is more than the previous Max area we proceed to the next height and similar to the previous examples now the area has gone up so we update the max area as we slowly move towards the next elements in the input array you can see that the area is increasing just because of the width is changing but the height never changed so once we reach the final element in this cycle the area that you see is the best that we can do by keeping the first element as part of the container in other words if we were to form a container with height 1 and any element in the array this is the best that we can do in terms of Max area now we proceed to the next round where we move the left pointer to the next index and then do the same experiment notice that now we have a bigger number the height is going to change as we move the right pointer in this particular example 6 is the limiting factor the height of the water cannot move above six it is otherwise it is just going to flow out of the container now the area here is six because the minimum of the two height is 6 and the width between the two height is 1. but it is still smaller than the previous Max area so we are not going to update the max area we are just going to update the right pointer now the right pointer points to a height of 2 which becomes our limiting factor here so the water cannot go above a height of 2. and the area of this shaded region is Just 4 because it is the width differs by 2 and the minimum of two heights is again two so the area is 4 which is smaller than the max area so we are not updating the max area we're just moving on move we are updating the right pointer and now because we have a height of 5 which is the limiting factor the area suddenly becomes 15 which is uh higher than or larger than the previous Max area so we update the max area uh we update the right pointer to point to the next one and as you can see this larger than the previous Max area so we update the max area the height is 4 because that is the least of uh the two heights eight and four and we multiplied that with the difference between the two indices which is five minus 1. and hence the area for this shaded region is 16 and we update the max area we proceed further by updating the right pointer now we have a Max area of 40 because both the heights are same we can fill the container up to eight and the difference between the width is 5 so the max area at this point is 40. and we continue we update the right pointers and now we have a height of 3 which is the least of eight and three and the distance between the two indices is six so the area is 18 but it is smaller than the max area so we don't update the max area we proceed to the final element in this cycle now we see that the area is 49 because the difference in width is 7 and the least of the two heights is seven and this is the max until now so we update the max area let's take one more cycle to bring out the point and then we'll see how we can implement this so now we are done with the container starting from the second element of the input array so we update the left pointer as well as the right pointer so this is similar to how we calculated the area of water in previous examples so the area is the difference between the width and the least of the two heights which is two in this example so the area is two and we update the right pointer now the areas 2 times 5 because the difference between the width is 2 which is 4 minus 2 and the least of the heights is five minimum of six and five which is the area is smaller than the max area so we don't update the max area we just update the right pointer and uh now with this example the area is 12 let me complete the full cycle for uh this particular container that is starting with 6s one of the heights of the container so as we complete this you can see that uh the height of the container is always going to be the minimum of the two Heights and the width just increases by one but every time we move the right pointer and we calculate the area appropriately the time complexity of this Brute Force solution is going to be Big O of n Square because we are going to have two for Loops the outer loop is going to control the left pointer and the inner loop is going to control the right pointer the inner loop will be incremented by 1 at each step until it reaches the end of the array and the outer loop will be incremented by one every time we complete a cycle with the inner loop at each step you are just going to calculate the area by multiplying the width which is the difference between the two pointers and the minimum of the two heights every time we calculate the area we compare the area with the current Max area if it is larger than the current Max area we update the max area let's quickly see how we can implement this let's create an integer variable to hold the result or the max area this is what we are going to return once we are done with our calculation so let's initialize this to zero and then we'll start the outer loop this is going to control the left pointer and this Loop is going to run until we reach the end of the array this nested Loop is going to control the right pointer the right pointers initial value is always going to be I plus 1 at the beginning of a particular cycle so for any new value of Phi J will start from its neighbor or the next pointer so J's initial value is always going to be IE plus 1 and we are going to run this until we reach the end of the array and at each step all we are going to do is compare the current area with the result and update the result if the value of the new area is greater than the current result so this we can simply do it by using mac.max and comparing uh result with the mac.max and comparing uh result with the mac.max and comparing uh result with the new area now the new area is going to be the product of the difference between the index and the index difference here is J minus I lines minimum of the two heights it's a minimum of two heights nothing but Matlab Min of height of I and height of J yeah so this step we are calculating the area of the container which is formed by height of high and height of J and x axis by multiplying the minimum of the two heights with the difference of the index and once we have this we compare the value with the result if it is larger than my current result we update the result once we are done we are just going to return our result this will return the a current area of the container with most water let's run the code to see if the two test cases pass okay so for these input the order of n Square solution seems to be okay but let's submit the code and see if it works for larger arrays as expected for larger arrays the order of n Square solution seems to exceed the time limit so let's see how we can optimize our Brute Force solution this is our input array and the goal is to find the container with most water so our goal is to find a container for which the width into height is maximum the height is going to be random based on the input array but the width in order to maximize the width we can always start from the first height and the last height that is just going to give the maximum width possible and then we can optimize for the height so to start a sliding window approach we're just going to have these two border elements into consideration let's forget about the intermediate Heights for now let's start with the first and the last height of our input array and we know that from The Brute Force solution given any two heights the shorter one is going to be a limiting factor so for this example with height 1 and 7 we know that if we want to form a container with a height of one this is the best that we can do because any other height if we pick other than seven we are just going to reduce the width and we cannot get a better height than one because one is our limiting factor so with these two heights uh especially with the shorter one this is the best that it can do so if you were to form a container include that includes the height one this is the max area that we can get for one and at this point the max areas just eight so we update the max area and at the next step we are just going to move either the left pointer or the right pointer how do we decide so we just move the pointer that points to the shorter height that is because the shorter height is the limiting factor for RK so irrespective of what the uh Euler Oneness we are not going to exceed the height pointed by the shorter one so if we were to move one pointer to its neighbor it makes sense to move the shorter one because with the shorter one in the current state this is the max we can do or this is the best that we can do whereas for height of 7 we might find another height where the area can exceed the max area so for height of seven we are not sure at this point whether this is the max that it can do so we should not move the right pointer for this example but for the left pointer with the height of 1 this is the best that we can do if we were to form a container including height one so we're just going to move the left pointer because that's the shorter one and that's the limiting factor in our case once we move our left pointer to the next one now we have an area of 49 which is better than the previous Max area so we update the max area again we need to move one of these pointers to the neighbor how do we decide like before we are just going to move the right pointer now because between 8 and 7 if we were to form a container that includes seven this will be the best that we can do in terms of area so we're just going to move the shorter height to its neighbor and see if we can exceed the max area let's move the right pointer because right pointer is the one which has the shorter or minimum of the two heights now so once we do that now we see that the area for this container is just 18 which is smaller than the current Max area let's move the right pointer because that has the minimum of the two heights now once we move the right pointer now we see that the area is 40 which is smaller than the max area now we see that both the heights are equal now which pointer to move if both the heights are equal we can move either of the pointer and see if we can con identify a container with the max area so let's move the left pointer like before the areas uh just the minimum of the two heights multiplied by the distance between the index which is 24 in this example uh again smaller than the max area so we're just going to update the left pointer because that has the smaller height and we proceed uh because this area is again smaller than the max area we are going to update the left pointer which has the smaller value and this container again it has an area of 10 smaller than the max area so we proceed further by updating the left pointer and now we see that the area is just four and the max area is 49 in our case so the time complexity for this problem is just Big O fan because we are just updating either the right pointer or the left pointer until the two pointers meet and we started with the boundary Heights or we started from the first and the last element of the input array we continued until both the pointers met so the whole time complexity for this solution is Big O often let's see how we can implement this with create a result variable this is what we are going to wrote down and I will first initialize this to zero and let's have a right and left pointer let's point it is initial X to Zero and right pointer just points to the last index and that is I dot length minus one now I'm going to run this while loop as long as my left pointer is less than the right pointer okay inside the loop at every step we are going to update the max area if the current area is larger than the max area so max area is going to be map.max of map.max of map.max of itself and the product of difference between the width is Right pointers minus left pointer times minimum of the two heights which is math dot min Bob I pointed by my left pointer height pointed by right pointer so this is just going to update the max area if needed and now we need to update either the right pointer or the left pointer so how do we decide we are going to update the pointer whichever contains the minimum of the two heights so we are going to compare the two heights if height of left pointer if that is the shorter one we're going to update the left pointer so this will be once we do this check we know that if this condition is true the height of left pointer is the shorter one so we are going to update the left pointer or if that condition is false we are going to update the right pointer now right pointer is moving in the opposite direction so we are going to decrement right point of and once we are done with all these we are just going to return our Max area let's run this code to see if the two test cases pass as you can see the two test cases passed now let's submit the solution I hope this was useful thanks for watching
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
1,637
hey everyone welcome back and let's write some more neat code today so today let's solve the problem widest vertical area between two points containing no points and if you ever needed a reminder that the difficulties on leak code problems can be really random this is a perfect example of that probably the hardest thing about this problem is just making sure you understand exactly what they are asking for because once you know that the solution is not so difficult I think it's really more of an easy problem but let me know what you think so we're given n points on a 2d plane so that means each point such as this one is going to have an x coordinate and a y coordinate so we have a bunch of these points on this coordinate what we want to know is among any like vertical rectangle that we can create between two points and what we want to know is what is the greatest distance between two points but not just like the entire distance that would mean we actually have to calculate a diagonal but this problem is even more simple than that what we're actually doing is just calculating the difference in X values between two adjacent points that's not how this problem is worded it's worded with like the idea of like vertical rectangles but given that for these rectangles we only need to calculate the max width it becomes clear that all we really care about among these points is not the Y values those don't matter at all we care about is the X values okay so that's one but what we can't do is take the X difference between this point and this point that would give us a result of two because the X difference between 7 and 9 is of course two but the reason we can't do that is because in between these two points there's another point so we're not allowed to do that for a line that has other points like in the middle of it so in other words what we can only do is get the X difference between these two adjacent points and then these two adjacent points or you could also do these two adjacent points and then from here you could technically get the difference between these two but that would be zero anyway and then we don't really have any more points to the right so what we realize is that since we only care about looking at these points in order of like the X values then the only thing we have to do is take the array of points and sort it based on the x value and then just iterate over the list of points so suppose like these are our points and then for each pair each adjacent pair of points we just calculate the X difference and among all of those X differences that we calculate we want to end up returning the maximum of all of those what's the time complexity of this well we're going to sort and then linearly scan so the bottleneck is of course sorting because that is an N log n operation a linear scan is just Big O of n so this will dominate the time complexity in terms of space depending on which sorting algorithm is used under the hood because you're probably not going to implement that yourself it might take additional memory so it could be like o of n it could be a constant or it could I think even be log n now let's go ahead and code this up so the first thing I'm going to do is take the points array and just sort it so by default we know each point is actually a pair of XY values in Python by default it will sort them based on the first value of that pair if there's a tie it will sort them based on the yvalue it doesn't really matter in our case if there's a tie but that's just how it the Sorting Works under the hood now after that's done we want to compare every adjacent pair so I'm going to have an index for I in range length of points and I'm going to say minus1 because every time we look at a point at index I we want to make sure that there is a point after it that we can compare it to so that's why we're only iterating the number of points minus one that's how many times we iterate and then among the point so the point at index I and the point at index I + one we want to the point at index I + one we want to the point at index I + one we want to get the x value that's going to be at index zero it's not going to be at index one it's at index zero because the x value comes first we're going to take that and subtract from it the current point at index I and the reason we're doing it this way like I + 1 is here and doing it this way like I + 1 is here and doing it this way like I + 1 is here and then I is here that will ensure that this value will always be positive or it will be zero remember we're trying to maximize the distance so this will calculate the width of the rectangle and we want to maximize this like I said so we're going to first declare a result which is initially going to be zero that's going to be the max width that's what we're going to try to return and here to calculate it we're going to set result equal to the max of itself and this current width that we have calculated and then by the end of the loop result will be maximized we're going to return it let's make sure that this works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out n code. thanks for watching and I'll see you soon
Widest Vertical Area Between Two Points Containing No Points
string-compression-ii
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._ A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width. Note that points **on the edge** of a vertical area **are not** considered included in the area. **Example 1:** ​ **Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\] **Output:** 1 **Explanation:** Both the red and the blue area are optimal. **Example 2:** **Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\] **Output:** 3 **Constraints:** * `n == points.length` * `2 <= n <= 105` * `points[i].length == 2` * `0 <= xi, yi <= 109`
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
String,Dynamic Programming
Hard
null
1,022
all right so let's talk about some of the root to leave binary number so you're given a root of binary tree so basically you just have to keep adding the number from the root to the leaf and you will return the final answer so you're going to be you're going to add 1 0 to the equation and then 1 0 1 and you will get 22 this is primary number so this is actually equal to 4 right and this is actually equal to five six and seven right so how do you actually do it like you can actually use the recursion solution so you'll create a helper function and every time you traverse to your children you have to check if the if your current root is actually equal to null if this is true then you return zero and then if not then you just have to like um shift your value your current values are left by one union and then plus the current root uh rule bow and then you'll go on your left and right children and this is the solution so let me just stop holding so you have a helper function and for this hover function you know you will need a ink valve and i will just return some root come on and now passing the initial value which is zero and then i would have to have a base case the basically is if you equal to normal you will return zero right so if the root is not equal to zero right then uh it's not equal to no sorry if not equal to no then i would have to just uh shift my um vowel left by one plus the current root of l and if the current node is a diff so i have to say if i will have to return val right away and after i have to check my left and right subtree right so i will say some room some roof to the leaf and then root out there and now we're passing the valve plus some roof to lift to the right parting about so this is the solution so let me run it hopefully i don't make mistake and submit all right so let's talk about time and space so this is going to be space uh it's going to be constant right uh which is i mean you're not allocating any space beyond it so the space is constant for time this is also time that you traverse every single one of it in the uh trino right so this is actually all the fun but you only visit one time right and this is the solution and then you go backward and then this is pretty much it so all the fun for time constant for space and this is the solution and i'll see you next time bye
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
295
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 295 find median from data stream the median is the middle value of 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 array two three four the median is three for example for array two three the median is two plus three divided by two equals two and a half because it's obviously an even length list so we need to simply take the uh average of the two numbers that are in the middle and the reason we don't have that for three for this one is because three is actually in the middle whereas with an even one there's two items which are technically in the middle so we're asked to implement the median finder class and this medium finder is going to be initialized as you know standard class and it's going to have two methods the first is going to be add num which takes an integer number and doesn't return anything it's simply going to return add the integer to the data stream stored somewhere in the data structure the second method is going to be a fine median which returns a double and what it's going to do is return the median of all the elements that we've seen so far and we're told here that answers within 10 to the minus fifth of the actual answer will be accepted obviously we're doing a median if we have to do some division that's why we have this little bit of leniency here so that's the question prompt let's think about how we might solve this so before we get to the actual best answer for this problem there are a few other solutions that you could use to solve this problem now you probably won't want to implement these in the interview because they're not exactly the most optimal solutions but it's still worth bringing them up to your interviewer to show that you recognize that there are other solutions to this problem and then you can actually talk about the pros and cons of each solution and discuss this with your interviewer before actually going with you know your optimal solution you may think this is pointless but actually it shows your interviewer that you are considering multiple solutions to this problem and that you can pick one based on criteria so being able to weigh the pros and the cons of a solution is a really good interview signal for your interviewer because you know this is what you do in a real life scenario right you're going to have to there's going to be multiple ways you can solve your problem and they're each going to come with their own pros and cons so it's not just a pointless exercise to just jump into the most optimal solution you don't actually have to code these inefficient solutions but they are sometimes worth bringing up and i guess good to know in case that maybe you forget the most optimal one you can actually go with one of the sub-optimal actually go with one of the sub-optimal actually go with one of the sub-optimal ones and at least get something down so they can you know maybe give you um some sort of you know i don't know credit for your solution maybe they're not looking for the most optimal they just want you to solve the question anyway i'm going to stop rambling the most simple way to do this is simply to take the numbers that you're given so let's say that our stream looks like 1972. what we want to do is the most simple way is just let's just say that this is our stream we'll just call it s and then you know our internal data structure is just going to be a list so first we get the one then you know we get the median which is the nine uh sorry one and then we get the nine and then now the median is going to be the middle value here and then we get the seven so the problem with the seven is that this list is no longer sorted so we can no longer look at what the median value is remember that we can only look to the middle if the list is actually sorted so our first solution here which is kind of the inefficient one is to be sorting each time to just store it as we get it from the stream and then sort each time and then you know simply just return whatever the middle value is and then obviously sorting is going to be an n log n operation and then to get the median is going to be big o of 1 because all we have to do is look at whatever the middle element is so that's going to be each time we need to find the median that's going to be what the run time is obviously this is inefficient because we're resorting the list every single time if we now got a number that would break this sort then we need to add it and then resort so this is why we don't want to go with this one because we have to restore every single time well you may be asking okay well what if we don't have to sort each time we've sorted it once can't we maintain this sorted structure so let's say we have the one seven nine sorted and then you know we get a two right we don't have to just resort it what we can do is because this is sorted we can actually use a binary search here to find where the insertion should be right we can basically do a bisection here to figure out where to insert it and we can find that position in worst case of log n because this array is sorted and we could find the insertion point in log n and then obviously to insert it is going to be big o of n and the reason that it's going to be big o of n because we need to insert it right so that means that elements you know we put it here because it's going to be between 1 and 7 but then these ones have to get shifted and because we're shifting elements in a list that's going to happen in big o of end time right this is a standard array it's not a linked list so we can't actually insert something there in constant time and then to actually find the median would be big o of one again so obviously we don't want to do that because you know it's quite inefficient the big o of n is actually going to dominate this log n so asymptotically our runtime is just going to be big o of n so obviously that's not great well what is the optimal way to do this and we want to achieve ideally if oops can't see that we want to achieve if possible log n runtime in the average case now you're probably wondering how in the world are we going to find a median in log n time you know given that we have to maintain this nice structure well here's what we're gonna do and the way that we're gonna do it is going to be to actually use two heaps and we will discuss how this actually works in a second so i left you with a little bit of a cliffhanger there i told you we need to use two heaps but you're probably wondering how in the world are we gonna use two heaps to find a medium this sounds ridiculous well let's think about what a mini heap and a max heap give us remember that a max heap will give us what in big o of one time the largest element right in the heap and then a min heap will give us what in big o of one time the smallest element so how does this help us well let's say we have some list with values and what we're going to do here is we're going to have two heaps right we're going to have the max heap here on the left and we're going to have the min heap here on the right and what are we going to do well in the max heap we want to store the smaller half of the array and in the mat and the min heap we want to store the larger size of the array so let's say we had the numbers 1 2 3 4 5 6. so the heap here is gonna have you know four five six and this is just a rough drawing uh and then the max heap is going to have three two one so why is this important well if we can split it up evenly this way then to find the median all we need to do is one of two things and the reason it's two things is because we can actually have an odd number if in the case that we have an even number in our you know min and max heap so basically there are values equal to each other there's the same amount of elements that means there's an even number then remember all we need to do to find the median since technically that you know this list is sorted within these heaps right all we would need to do is take the average of this three and four wait a minute this just happens to be the top element of our max heap and this four is the top element of our min heap so to find the average all we need to do is take the top element of our max heap so this is going to be three and we're gonna add it to whatever the top element of our min heap is and then divide by two bam we have 3.5 as our median bam we have 3.5 as our median bam we have 3.5 as our median see why we use heaps okay great but what if we have you know a seven here what if they're not actually equal we're only going to allow one heap to actually be bigger so let's just say that this is actually you know like seven here in this case we're going to make sure that one of the heaps always stays the bigger one we're only going to allow one to actually have that extra element in the case that we have um you know odd elements so we'll just say that the larger half is always going to have it in this case well we can see that the larger half is actually has more elements so that means that the median is actually going to be the element here the smallest in the min heap so we can simply return whatever this element is cool so that's how we actually find the median and it's really simple right the problem is actually keeping these heaps balanced because say we add something that breaks this structure then we're screwed we basically have to rebalance elements and sometimes we're going to have to move elements from the you know this larger half to the smaller half depending on the next item that comes through in the data stream and this is where the complexity of this problem is but essentially what we want to do is when a new element comes in we need to make sure um you know to figure out which heap it needs to go into and also to rebalance the heaps so we always maintain the structure such that the smaller half of the array is always going to be in this max heap here and then the larger half of the array is always going to be in this min heap here and then this min heap can at most have one more element than the other side and we're going to have to maintain that at all times that's really the difficulty of this problem but if we're able to do that then we can just solve it pretty standard and then all we need to do is again actually finding the median is really trivial it's the actual balancing of the heaps that's complicated so instead of drawing this out and as you can see it's already messy this isn't even a real example we're just going to go to the code editor i'll break it down line by line and you'll see how we actually rebalance these things i'll walk through the steps and hopefully it should make a whole lot more sense but essentially just to summarize we want to maintain these two heaps because we'll have access to these elements here at the top of both of the heaps which will be used to actually compute whatever our median here is so that's kind of the trick of this problem is actually maintaining those two heaps so enough talking let's go to the actual code editor and write this up and you'll see how brilliant this solution is the first time i saw it i was like wow this blows my mind there's just some problems on leak code that do that anyway enough rambling let's go write the code okay we're back in the code editor and it's time to write the code you're actually going to be surprised at how simple the code is for this problem despite how complex it seems we're using two heaps we have to balance them to make sure that we have the proper amount of elements and the proper amount of numbers in each heap but really the code is like 10 lines so let's get into it remember that we need to initialize our median finder here with two data structures the first is going to be our heap of the elements smaller than whatever the median currently is and the other is going to be another heap with elements that are currently larger than our median so let's set those up so we're going to say self.low those up so we're going to say self.low those up so we're going to say self.low is going to be equal to you know an empty heap and we're going to say self.high is going to be equal to an self.high is going to be equal to an self.high is going to be equal to an empty heap and remember low is going to be those elements that are smaller than the median and high is going to be the elements larger than the median and remember that we're allowing high to actually have one more element than low because in the case that an odd it has to go in one direction and we're going to put it into the high for consistency so when we add a number remember that there's two cases that can happen either our heaps currently have the same amount of elements in which case we need to add it to basically the higher heap but we also need to do some sort of rebalancing or we can add it to the lower heap uh and do some rebalancing so let's do the case where they're actually equal in this case we actually want to put that element into the larger heap remember the larger heap is allowed to have one extra element so let's do that so we're going to say if the length of self oops if oops let's go back apologies so if the length of self.low apologies so if the length of self.low apologies so if the length of self.low is actually equal to the length of self.hi of self.hi of self.hi then what do we want to do so we want to push our element onto the bigger heap but we need to make sure that we're actually pushing the right element so let's say we're going to heat push and actually we should just call into the heap cue module here they're all like imported globally in leak code but just for good practice we'll actually write out the module name so we'll say keep q dot heat push so we're gonna put the value on to the biggest onto the heap with the bigger elements but now we need to decide what to actually push onto there because it could be the case that our number needs to go into the smaller heap and if it needs to go into the smaller heap then obviously we don't want to put that number in there we want to put it into the smaller keep let the heap reorganize itself and then what we're going to do is we're actually going to take whatever the biggest element of the smaller heap is and we're going to put that into the larger heap because we want to make sure that we're always keeping those larger elements in the high heap so what we're going to do here is we're going to say we're going to push on to the heap of high we're going to say heap push pop and i'll explain this in a second so we're going to push pop from the low heap whatever minus num is here now let me explain this because it's a little bit confusing so in python when you use a heap the default implementation is actually a min heap there is an api for the max heap but the method names are a little bit confusing they all start with underscores they're not easy to find the documentation is kind of shitty so typically what you do in these cases is you actually use a min heap but you use negative elements and that way it becomes a max heap so that's why we have these negatives here because we're working with the high which remember is our um you know min heap we need to basically use negative numbers here so that's the reason that we're actually using a min heap as a maxi so that's why we need the minuses here so essentially what we're doing is we're pushing this minus num on to self.low and remember self.low here is self.low and remember self.low here is self.low and remember self.low here is actually the max heap because it represents you know the elements less than the median and we need the largest element so that's why we're using a max heap of the smaller elements so since we're using a max min heap as a max heap that's why we need these minuses here on the actual self.low so essentially what we're doing self.low so essentially what we're doing self.low so essentially what we're doing is remember the push happens first so we're going to push minus num on to our low here the heap will rebalance itself and then we're going to pop whatever the largest element is and remember since we put numbers in as negative when it comes out it's going to be negative so that's why we need to nullify that negative so that way we can put it in as a positive into self.hi so essentially what we're into self.hi so essentially what we're into self.hi so essentially what we're doing in self.hi is we're pushing doing in self.hi is we're pushing doing in self.hi is we're pushing whatever the largest element in this heap here is of the lows so essentially we put in our element first because obviously the push happens first and then we pop whatever's at the top of the heap and then we move that over to the high so hopefully that makes sense and that's basically how we do the rebalance in the case that they're actually the same size remember that we can always put that larger element into high otherwise uh high is already greater than um low then what we need to do is in that case we actually need to put it on um actually sorry there's two cases it can be either the case that high has that one extra element or uh low has actually um an extra element so we need to actually move um an element from the high heap onto the low one so we're going to say heap cue heap q dot heap and again we're going to be pushing onto the heap except this time we're going to be operating on the heap of the smaller values so we're going to be pushing on to the low heap basically we're going to do the opposite of what we just did here so remember last time we were pushing onto the small heap this time what we want to do is we want to push num on to the larger heap self.hi larger heap self.hi larger heap self.hi then we want to take out once we push it's going to rebalance itself and then what we need to do is simply to take out the smaller element and then put that into low and that way we'll have that rebalance happen and then we'll be able to maintain our nice invariant that basically that the low heap will have all the elements less than the median and the high heap will have all the elements greater than medium so let's do that and again we need these annoying negatives because remember that the low is going to have the is going to be operating as a max heat but we're really using a mini heap so to do that we're again flipping uh the signs so we're going to say heap push pop and we're going to do the same thing except this time it's going to be operating on the high and this time we're going to put num in there and the reason that we don't use negatives here is because again the high is operating as a min heap so we can just do it normally we don't have to put minus numbers onto there so to recap we're basically pushing the number onto high letting the heap rebalance itself and then popping whatever the smallest element is and the negative of whatever that smallest element is getting inserted into our self.low which getting inserted into our self.low which getting inserted into our self.low which is our max heap of the elements less than the median and that's the way we're going to keep our kind of invariant here going so that way we can you know find the median so that's going to be how we actually implement adenom i know it's super simple it's literally like an if else statement um it seems really complicated but you can do it in one line it's ridiculous uh so now all we need to do is just implement the find median so remember in the case where we have two numbers um the median is going to be the average of the two numbers in the middle uh and then if it's an odd length then it's simply going to be the number that's literally in the middle of our kind of sorted array here and remember that um in the case that they're not equal in lengths then we just want to pop from the high so that's going to be the value we use there so let's do this okay so we're going to say if len self dot low equals to the length oops length of self dot high then this is the case where they're equal so we need to do that um addition of the two elements and then take their average so we're simply going to return float of self dot high of 0 which remember is going to be the smallest of the big elements and then we're going to say minus and the reason that we're using minus is remember that our low heap here we're putting negative elements into there so that really this is gonna be like minus whatever the number is and then this is really just gonna become a plus so that's why we need the minus there so we're gonna say minus self.low of zero we're gonna say minus self.low of zero we're gonna say minus self.low of zero so that way you know we're taking the two elements at the top of the heap and then we're simply going to divide by two and that's all we have to do and in the other case we just return whatever the element at the top of our high is and that's it so we're going to say return float self dot high of zero cool let us submit this make sure it works and we haven't made any bugs and it does cool so what is the time and space complexity for our algorithm well the time complexity here is going to be what it's going to be log n why because every time we add a number all we need to do is simply um we're going to be just doing heat pushes and pops right that's all we're gonna do and they're gonna happen serially so in the worst case right we're pushing from the heap uh we're pushing onto the heap and then we're doing this heat push pop so remember to push from on to the heap it's always going to be a log n operation because the heap has to rebalance itself in the worst case uh popping from the heap is always going to be a big o of n big o of one operation sorry because we can always get the largest element easily uh it's going to be in constant time that's just a nice property of our heap so um basically you know these operations are just going to be you know big o of n and then it's going to have sorry big o of log n uh is going to be the time complexity for adenom obviously for the fine median this is going to happen in constant time because accessing these elements from the heap here we can just do it in constant time uh we'll always have access to this in constant time so this part is um you know big o of one so our you know entire algorithm is really bounded by the fact that we have to do this heat rebalancing here on the two heaps but that's just going to be asymptotically big o of n space wise uh if you think about it all our heap is doing is storing the entirety of our data stream except it's split over two heaps um so you know in the worst case one heap will have you know we'll say big o of n divided by two minus one and then the other one will have big o of n elements but asymptotically this is just going to be big o of n because you know we're just storing basically all of our elements um in the data stream as they come in and that's just going to be big o of n so however long the data stream is that's however many elements we're going to need so that's your algorithm surprisingly simple this is a hard level question you know some big companies amazon google asks this question it's quite tricky if you've never seen this before to be honest you probably aren't going to come up with the heap solution but look at this is literally like if else blocks um to solve the hardest problem and it's a one-liner i problem and it's a one-liner i problem and it's a one-liner i think that you can easily memorize this the intuition is actually quite simple once you've seen this before so this isn't really one that you have to worry too much about i think if you watch this video you kind of understand how it works maybe walk through um you know this part line by line if you don't exactly understand it but essentially we're just moving elements around to make sure that our invariant stays correct uh in that you know the low heap here is always going to have the elements less than the meat the current median and then the high will have the values greater than the current median and then by simply doing these operations we can maintain that median um as we go along so and then this is how you calculate it really straightforward anyway i'm going to stop rambling here that was your solution for this problem your timing space complexity analysis if you enjoyed this video please leave a like comment subscribe if there's any videos you'd like me to make please leave them in the comment section below i'll be happy to make them for you guys just tell me the problem um number or you know tell me a topic you want me to cover or you know just random questions about working and paying what's it what it's like how much do you get paid yada all that stuff i can answer it for you guys just tell me what you want to see anyway thank you for watching have a nice day bye
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
286
hello everyone welcome to this great dfa series of videos again so this will be the last video in this series so that is walls and gates 86 so the problem statement is saying you are given an aim into a grid rooms initialized with these three possible values minus one is represent as a wall or obstacle zero means a gate infinity means an empty room so they will put some value in that to represent it as an infinity fill each empty room with the distance to its nearest gate if it is impossible to reach a gate it should be filled with inf or infinity so here if you take one example what it is saying is you will be given with one grid where minus one means one wall is present and zero means one gate is present and infinity means that is an empty cell what you have to do is you have to find what is the distance of this empty cell from any gate so if you check here they already filled it up here so the nearest gate for this cell is this one so that is one because the distance is one for this cell it is one four two three four like that from here it is one two and three so here if you check for this particular cell the distance from this gate is 3 but from this gate it is 2 so we have to update with the minimum one so if suppose the grid is very big and we have multiple gates and multiple walls and all that time there is possibility that a particular cell is near from a particular gate but it is far from the other gate so we have to update with the minimum one here and one more scenario is if you will not able to reach any gate then that time you have to fill it with infinity only suppose there is a wall here okay so that time as it's a wall here so this two cell you can't reach from any of the gate so that time you have to operate as infinite that's it so now we will check how to solve this problem so now we will discuss about the approach so we have to do a dfs search or you can use bfs also so here in this solution i will talk about the dfa solution so as for the other videos what we are doing for a particular cell we are starting a dfs call which will go to the fourth direction right same thing we will apply here also so we will first scan through the entire grid using to follow and we have to first search a gate so here if you check first cell there is no gate here it is not yet but here it is a gate now from this gate we have to start our dfs call to the fourth direction left right top or down okay and we have to update the distance so our main goal is suppose this is one gate okay from here we have to go to left right top or down with the distance value as one and if we can reach there then i will update that cell as one because the distance from this particular gate to that cell will become one and from one suppose we have can go to other four direction apart from this one because this one is already visited there we have to carry two and if it is possible means there is no wall or outer boundary is there then we have to update two in that cell and gradually we will proceed so here in this example if you check i will just change the color and show you let's say here we can go to the fourth direction top direction we can't go because that is going out of the grid left side it's a wall present so right side if you go using the dfs call we can see one infinity is there that means that is a greater value so we have to update it as one okay and from here we can't go anywhere because all this call will be remain here only because they are either going out of the boundary or wall is present so here the another dfs call which was coming from that direction so that will update it as one now from this cell now we can go to the fourth direction and possible direction is this one and this one because here wall and gate is present now here onwards whatever cells are there that we have to update with two because from here all distances are one from one all we have to update is two then only gradually we can increase the distance so this two cell i have to update as 2 and from here whatever call will go that will start with 3 so if it is going this side then i have to update it as 3 and from 3 whenever in 4 direction i am going here i have to update it as 4. so this part of the dfs call is completed so we have to start a program from here because here we left so from 2 whatever direction you will go we have to update it as 3 so if you remove it you have to maintain it as 3. then from 3 this 2 direction we can go and both we have to update us 4 and i think we are completed right so here if you look we started from here and we updated all the empty cells now from this particular gate we updated all the distance right but maybe that is not the minimum because from this gate it should be one right then it's a nearby but as of now as we started the dfs call from this particular gate we updated everything with this gates distance so here if you see it is 4 and it is true also because it is the 4 direction now what we have to do is we have to again search for another gate so here no gate is present till here we found one gate so i will change the color to some different color and update accordingly now from here four direction we can go with one value because we are just starting this time what we have to do is we have to check if a present cell value is if it is greater than then the upcoming value then only we have to update so from here we are starting so we have one means we have to update it using one so this one is actually less than this four means the already presented value in this cell that time we have to update but if it is less then we don't have to update because that got the proper value so here we have 1 but it is 4 so we have to update it using one from one we have to propagate two right in four direction only we can propagate this side so we can propagate two and the value is three means we are minimum so we have to update it so it will be updated with two from here we can go to this direction and uh this side we can't go or this side we can't update the value because 2 is not less than 2 right it means already it is getting the perfect value but here if we have to update with 3 right sorry it was my mistake so from 2 i have to update it with 3 but 3 is not less than 2 so we can't update here right but here in this case we have to update it using 3 but the value present is 4 that means it is less than right so we can update it so it will become three now we can't move anywhere else because this direction we can't go so we can't proceed with this path and all and this will be the final value so here now we have updated everything and if you check here all the cells got their proper distance or the minimum distance from the gates and if you match it with the answer in the lead code example they provided three two one and two one two three four and one and here in this grid they have provided the direction also like uh which cell is following which gate so all this ah bottom word direction cells are following this gate because one two three is their distance and this particular gate is followed by two because the distance is two from here it is one then one two three and 4 okay now we will see the code okay so coming to the coding part here i have taken this method which was already provided so there first we are defining this row and column as a global variable to pass into the recursion call and then uh first we have to find the gates okay so for that purpose we have to iterate over the whole grid and we have to find the get if we get the gate actually from there we have to start our dfs calls into the fourth direction so here if you check using this to for loop i just first found the gate here as it's a gate from here we have to call four direction using the coordinates like i minus one or j minus one like that and that time we have to pass one distance field so if i am going away from this gate that means all this area if they are valid then they will be one right means distance from the gate will be one so that's why i am passing one here and i am calling it four direction so here if you check left side it can't go right side it will go bottom it will go and top it can't go so that condition i put here in the dfs call that if it is going out of the bound or out of the cell then we have to stop there or else if the uh cell value is minus one that means wall is present that direction will not go and after some time if we again get zero means we will get another gate so that also will not go right so if all these things are valid then we will check that if the distance or the new one is less than the previously calculated distance or not so suppose from here when we are starting initially everything will be infinite right so and i am assuming that the distance will be one so by this condition i can check that my distance is one and the this cell has the distance as infinity that means we can update it so it will become one let's say we are here and one gate is present here so that time this is more close to this gate and should be one right so if it is already calculated that time when i am started calculating from this gate we do not have to update that one right so if my distance which i am going to update is uh less than the already distance then only we have to update it as room i j equal to this and then again we have to go towards four direction okay so from there we have to again call the dfs in the fourth direction that's it the simple approach so after submitting yeah it's working thanks for watching
Walls and Gates
walls-and-gates
You are given an `m x n` grid `rooms` initialized with these three possible values. * `-1` A wall or an obstacle. * `0` A gate. * `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distance to a gate is less than `2147483647`. Fill each empty room with the distance to _its nearest gate_. If it is impossible to reach a gate, it should be filled with `INF`. **Example 1:** **Input:** rooms = \[\[2147483647,-1,0,2147483647\],\[2147483647,2147483647,2147483647,-1\],\[2147483647,-1,2147483647,-1\],\[0,-1,2147483647,2147483647\]\] **Output:** \[\[3,-1,0,1\],\[2,2,1,-1\],\[1,-1,2,-1\],\[0,-1,3,4\]\] **Example 2:** **Input:** rooms = \[\[-1\]\] **Output:** \[\[-1\]\] **Constraints:** * `m == rooms.length` * `n == rooms[i].length` * `1 <= m, n <= 250` * `rooms[i][j]` is `-1`, `0`, or `231 - 1`.
null
Array,Breadth-First Search,Matrix
Medium
130,200,317,865,1036
190
If you see a special then what you have to do is you will get this number, you have to print the final of this number and its reverse smile, you have to print this, if you got 11:00, then do 11:00. Bring to front 101 if you want 3000 1000 only here. But if we you got 11:00, then do 11:00. Bring to front 101 if you want 3000 1000 only here. But if we you got 11:00, then do 11:00. Bring to front 101 if you want 3000 1000 only here. But if we do too much here then we will check from here, we will make this mask, this is like this, if it has come in this vegetable, then this one will grow from the bottom, all the party will be done by inch and this line option will come like your private. If it is as it is, it will come. Aggarwal Mitthu is zero and if there is an end then it will go. If all is zero then mobile is the best option. If only the loan remains, the lights on the pillars then how does the end react. Use anything with 1000 1GB data inside the end and This is the whole meaning of this Yagya appointed 01 2019 I should keep making the sun, it will make it and whoever sits here will come to know that it is theirs, sitting like this, we will know, till we do not get the first and then we will paint, the day we go here This is such a universe that I will check it and I will get the norms for the first time and I will get the destination for the first time that on that day I will get my first one printed Ghunghru and after that I will close it, before that I am okay to even talk about the reverse. If I am talking about printing submit then see a picture started at this time the features son is called sun due to which or west is a first width I and till I come I will see all this now I will see with a phone Try ending with the number, this number and mother is equal to zero no it is a the most good there is one more thing till date one is not found then goli employee applied for that till date there is no one then the day you turn on here then This is that if you have got your flag, now it is very simple in the school, the union has got it, then we have to run that after this is one page, in this we will set the system dot print to off because and plant is through and here we We will print it, okay, as long as you get it will be a printer, and then, after understanding it from school, I will take the compromise explosion, I will submit here, I will take it, I will try to explain it to you. Here is this side of our court, which latest one do we talk to in a tweet? I don't talk in 31 minutes, I talk in 8 minutes or you, this is a trick, if we don't have to return, then we are here. I made the meat this which let's check how do one do it like if this then I will just put this and this in the mask everybody is here because inside the and there are 10 and a and if we discuss the relation of lineage then the mit comes back You will go to the manager and if this is not complete, if this is also completed, now first of all, we subscribe then subscribe this 12345 6 If you have not subscribed then I have taken it here and till now I have not found anyone then on the other side flight poll It's my flight 's rise plug right now 's rise plug right now 's rise plug right now that you got some down and including me all I got is zero so do n't print nothing do nothing so when they wo n't do nothing I got some friends this I didn't print anything for it Done ok then I am demoting this boot but you - done and I got it in 2008 you - done and I got it in 2008 you - done and I got it in 2008 taken by again zero came like ever reached temple from fruit this is norms and I in two states if someone and dynamic little shy If I got running then that is the video, I have to prank again, I have done nothing, I went up twice, you became less, so I changed my meat, my mask, took this again and took this and zero came by Mars and Jupiter and Venus, look carefully. You have changed a lot that there are some changes in the master plan, there is a plan for this palace, we still have to join it, this time we have taken jobs and taken it, so we have got to listen to the one present here and this band was going up which was That here one of them is true, I will go here and took it, this time I will make it zero, I am forced to live life, I got down, removed the mask, changed into meat, this is the one that took the pot, so I came here, it is good, okay It means Jajman zero, nine districts should be closed, 1 print went up - new, this end was taken, 1 print went up - new, this end was taken, 1 print went up - new, this end was taken, this time too, if it was not subscribed, then how could it have been made, then this is what you see on the next page and On this, we need to set sweet, second jet will be used for Jio net in zero, so when will you set the first date and complete it, if you can save the first, then I will make set meat, we will set mass, so this one go to Z one drops. It is Ujjain from which you became the first one, from where what should I do, if you get zero, if I don't do anything, then if you get zero, then do something or is it okay, now look at the set eating meat, everything is going well, this zero is going on smoothly. Se did not say anything that if you get the first one then here is a pimples number of mine, it is crying at all, there is no shatter in it, of the table to teach a lesson that 1234567890, you will get it for Ghritham at their place, I its this Make this set of more and more, okay, then when I will give you another bigger one and you have made the next one has come, the yagya of making us the next one, now like here, made us the next one, then let us subscribe, we will not do anything until it comes. Unless the bad comes, we will not do anything, this is my reverse number and here this is my this, the day I made the first one, I will set this and make this big, now come here, whatever it is, do nothing, this is cut, this is bigger. Now this is a bun, so we will set it. It was cut, it has grown. Okay, now it is a bun here too, so it has to be set. When you reach here, you have come inside the forest temples. Look, remember not to do anything until the plug comes. It will be given to you on that day if you do this weight in the same year then reverse and cold reverse and equal to this master at measurement has been set in it. Now after this, the same thing has been done here every time, the strength will increase every time, otherwise this will happen every time. But when he comes, now set zero that there is zero vacation in it, if you chat again then keep in mind that when he comes for the first time, God will put you on the spot and health will start increasing. If his plant remains two, he will die every day. If zero comes, we will not erase it. If one comes, we will turn the butt on. Okay, cover it again and show it twice. When we mean, I show it like this, it erases that until we got the first and, we did not do anything. If I found the first one, I was here, I have turned it on, now after this, when or here, this is whatever, you had found something here, now this is one, so we had turned it on, here, so we have this and What's more, we need to like this, we will put a correct WhatsApp printline so that it gets placed under the banner and reverse like, a friend likes reverse like, we don't see if this is working, so it is working from now on, we submit it and it is correct. Answer: Punit Pawan, I understand your correct. Answer: Punit Pawan, I understand your correct. Answer: Punit Pawan, I understand your question, thank you very much.
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
1,814
Hello Hi Everyone Welcome To My YouTube Channel Students Were Decided To Me Awasthi Vriksha Subscribe My YouTube Channel Now Subscribe Our Channel Telegram Channel Subscribe Skin Problem Solve Question Subscribe The Giver Is You Are A Great Words Of The Non Negative Integer App For Example Reports 1234 Giver C-20 To Angry Reports 1234 Giver C-20 To Angry Reports 1234 Giver C-20 To Angry Birds 120 Ki Winters To A Peon Is Remedy All Of The Calling Condition 1000 Equal To Oil Angeles Times Dot Length Subscribe This Video Plz Subscribe To 1192 Ki Side Ko Sairat2 Par Vichar Satisfying One Condition Ok So You Can Hear What To Do A Plus Revert 997421696 22137 subscribe The 0 MP3 Indices Sexual Let's Talk About One Kill Elements To Take Index One And Tourism Also Considered As Nice Place To Abuse Inclusive Waste Is Equal To Wealth And Also 11111 20 Over Two Years Ago That Jaswant Singh's Feelings Se Jaswant How Is This Question Android Question Is It Is The Meaning Of This Point To That This Smart Value Bhaiya 122 - Who's That This Smart Value Bhaiya 122 - Who's That This Smart Value Bhaiya 122 - Who's Going To Table That ATM Right And 9717 Fennel Want To GIVE IT YOU CAN SEE VALUE THIS TEAM GOT PROPERTY TO 990 0 mid-1990s 98100 11:00 - 11.20 9717 087 797 Possible Nice to Meet You Dictionary and Calculate Differences Between Boys and Girls Toy Way Tools What Were Supposed to Get Neither has it been agreed upon Price interferences tried So what is the possible number of years that we can have for its practical value Shodh Ashwin Simple Calculator Using the Formula Depending on 2 and Minus One Divide by Two Soldiers Went to Give to * - Video give where to * - Video give where to * - Video give where Responsible For All Total Play List A 13050 476 1535 V0 To And 679 Basically A Member Of What We're Going To Get Long After Girl After Doing For Liberation And Storing This Element * Dictionary Sudarshan Storing This Element * Dictionary Sudarshan Storing This Element * Dictionary Sudarshan Tower Defense Game Tubelight's Tweet - 800 Tower Defense Game Tubelight's Tweet - 800 Tower Defense Game Tubelight's Tweet - 800 to 1000 Jobs Times one to three and with no weir is the number of birth * * * * - no weir is the number of birth * * * * - no weir is the number of birth * * * * - 121 hands free mode on information via going to get to * - 1818 and we raw how many nice to * - 1818 and we raw how many nice to * - 1818 and we raw how many nice pick and you will read pick nice pick and you will read torch light and A large simply beat go through all the elements present in Delhi at Solan to edit me increase size for that is possible only visible through online quiz will do the difference between the elements which are the President of USA that What the lighting operator thinks and this is going to give yours now but a p converted to get converted into a big difference between two on this difference is not done Dictionary What We Will Do Not Difficult 251 Laxative in the What is the Code A [ __ ] scene ok bhaiya getting from obstacles if A [ __ ] scene ok bhaiya getting from obstacles if A [ __ ] scene ok bhaiya getting from obstacles if not a registered singh rajput ko unmute units can see from this is the list what they need 1000k not meet you name what we will do to s discussed will just go through the history of oil in Basically Vihar to go to the dictionary values ​​for this house values ​​for this house values ​​for this house jhal values ​​functions dot values jhal values ​​functions dot values jhal values ​​functions dot values that all so let's take off but for holding the sum of nice piece window ac equal to a plus will lose weight for mulayam* - wwc2 a plus will lose weight for mulayam* - wwc2 a plus will lose weight for mulayam* - wwc2 discuss here I will do I * discuss here I will do I * discuss here I will do I * That I - One At That I - One At That I - One At A Time To Say What Means Sacrifice Making Is Basically Going To Rule 10 For Software Basically Going To The Value Of The Best When You Consider It Will Go To Give They Will Go To The Next Election 2014 is forced to do Du Plessis but one thing this question is the value of switch of the model of this is two 9 are you can see hair tips knowledge question more miss you don't see the number two ten plus two 9 how To Train Successful In Vihar To Submit So Let's Summit Jhal Ok Sweet Heart Test Case Which Work On Five Were Proven That You Can You For Solving Its Problems Nice Pictures Torch Light Bill Divisional Offices Dhawan - Torch Light Bill Divisional Offices Dhawan - Torch Light Bill Divisional Offices Dhawan - Discover With You Thank You So Much For Watching Like this video and subscribe my channel thank you
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
35
hi guys today I will be explaining the lead chord challenge which is called search in insert position in Python language so there are two parameters in this function uh numbers list and the target value the task is to return the index of the target value and if you cannot find the this target value in this list it wants us to return the index where it will be if it were inserted in order because this number this nums list is a sorted array so if you can find where the index will be here you see the examples uh the index of the target value of 5 is 2 0 1 2 and the index of the this target value is not one actually but the this output represents the index where we wanted to put the target value inside the list and again if the target value is not in the list and the target value is higher than all of the value of this num list nums list you will need to put it at the end which means you need to return the length of this nums list so it may be a bit complicated right now but when you write the algorithm it is much easier let's go to the visual studio code for this so here also it asks us to write this algorithm with all again runtime complexity but I will write both all again and all and runtime complexity just to see the difference so first let's write or an solution so let's get these first and so be I'm riding with a big o n runtime complexity uh I will do actually uh sequential search it can be also called linear search so I will just go through the list basically with one by one and uh to find the target value if there's in the list and find the index if the if it doesn't exist so I will just go through the list one by one if you can find any index I will just return it if you cannot find I will return the index where it would be if I wanted to insert it so for Mom in alarms sorry I will do enumerate here for index and the num value in enumerate nouns so if this num value is greater than or equal to the Target value which means I have reached the point I have reached the index I want to return or I already accessed it but I will return this particular index because uh it is the index where I want to insert my target value assuming the list is already sorted return the index value particular index value so if this if condition is never satisfied it means that this target value have always been higher than the number of values so in this case you just need to return the length of the Norms list to append the target value at the end of the list return land nose so it is very easy to write the sequential search let's apply it um object solution Dot search insert and I will put nums is equal to let's get one two three four five and the target value will be three so it needs to return 0 1 two value print this yeah I will just delete this so is expected the index is uh two so let's put this 10. it will basically return the length of this nums list which is five so let's write this same algorithm with login or login complexity login so here I want to explain the difference between uh sequential search and binary search so I actually want to see it visually so in the binary search it basically ignores one part and selects the other part by considering where the target value is so if the target value is in the left side of this 23 it will ignore the left side and focus on the right side and again it will go in the middle and it will decide which direction is that any the target is in and ignore the other side again and at the end it will find the target value or it will find the index where the target value should be in but in the sequential search you will just basically go one by one uh and it takes much more time than in binary search so here in the sequential search it takes 11 setups to find the 37 value but in the binary search it was like three I as I remember so let's go back to the visual studio code and write the function for it I will get these and I will Define lower and higher boundary lower boundary will be zero fire boundary will be length of this norms so I will create a while loop a while log is less than High at the end it this condition will be broken um you'll first need to define the middle value low plus High divided by 2 so this will be the middle value unit you will just basically sum them and divide by two so if the value in the middle is less than the target value you will need to ignore the left part because the target value is at the right side of the list so I will update lower boundary with uh middle class one and in the opposite condition you will just need to update the higher boundary you can think of it as opposite logic and at the end you return the lower boundary to get the index value so let's run this and take this so we got the same answer right but the runtime complexity is different so let's find tree here yeah we got the index of two five index of four as expected so I have both explained the sequential search and the binary search I hope it was helpful for you thanks for watching this video
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,314
Hello hello friends today in this video Vikram discusses another problem from dynamic programming problems fiction show problem test matric verse no shirt you in simple terms of list with you are with all the tips and cross ho but problem vitamin c tomato x and jakve loose it Front Development Research Assistant Answers of IPL The Amazing and Answer Matrix with Answers Phase System of All the Elements of Migrants from Lack of Lord can be Rich I - That Digestive Lord can be Rich I - That Digestive Lord can be Rich I - That Digestive Enjoy Day and Night See You Can Also Form Range of James Pattinson Jaipur Today Date Start Yuvak ko meaning of and land ok so let's get the elections in the matrix Lakshmi like it is matrix that and k is equal to laddu dam 34 element it is after to find out the sum of all the elements in the range of electron at the time of return Must share all doing what is the art can enjoy the eye - click on one leg enjoy the eye - click on one leg enjoy the eye - click on one leg element 12th of 151 aap apna aapna as per office fans of ginger and pains lightly its slices in the morning for witch this element more center dry ginger sexual side click Here voor but front left side open products and sister and find the sum of all the middle east and attainment of 108 elements like this that in the top and solid or jasmine oil December fennel debit the subscribe to the Page if you liked The Video then Duty Mix Limit OK So Honest He Grew Into Operation President India .au Into Operation President India .au Into Operation President India .au Operation But A Phone Number Second Year For Every Position So Straight From Left to right unit taking two chords Vikas till 10 minutes Sanjay request to all it's ok acid attack on 10th and 12th I request to back to for that but no one apart from 200 to that you can be used only one fact one young man update don't know The question know what you think in terms of his desires Indian scientist drops is this is the element how to update okay I want to see the index block 1282 involved so that this no extra reservation in jobs in order to avoid you want to To 16 District President Updated Every Time You Thank You Are Not Alone Hain And Decrease Updation You Can Gautam Video Update You Want To Update The Rain Storm Destroyed His Bit To Do You Want To Give All Subjects Day Celebration Will Have To Sorted Out where this point and then go into her top 10 we top 10 perfect dowry to end - 381 Adhir Veeravati perfect dowry to end - 381 Adhir Veeravati perfect dowry to end - 381 Adhir Veeravati on login button to start love you to love you will benefit in the company that you have to start to that they new Hit - Too Is Just Now Lakir With To they new Hit - Too Is Just Now Lakir With To they new Hit - Too Is Just Now Lakir With To And Stop Acid Attacks On Twitter And Updated With Multiple Times Jism You Starting Mitthu And Regressive With - 64 Starting Mitthu And Regressive With - 64 Starting Mitthu And Regressive With - 64 Benefits To Ride On Tubes Artwork In The Book Authored Trends - 2018 Last Date Book Authored Trends - 2018 Last Date Book Authored Trends - 2018 Last Date Handed Her Zor Plated Diamond Drop Candidates Will Vote For All Updates Range Bhi Aapke Update Pimple Min 60% Power And Bhi Aapke Update Pimple Min 60% Power And Bhi Aapke Update Pimple Min 60% Power And Water Lake Placid In The Middle Of This Element - Are Mine - Are Mine - Are Mine A T-Shirt Bill-2010 Elements Of To Find The A T-Shirt Bill-2010 Elements Of To Find The A T-Shirt Bill-2010 Elements Of To Find The Subscribe To The Page If You Liked The Video then is but let's do ireland indices laksh element head office work but if you want to minus to hair oil but not appointed to board virat 282 to objects and daily don't mind and intellect witch course - to mind and intellect witch course - to mind and intellect witch course - to retail markets end of the race but here enjoy Don't Hwy To Loot But In Dishaon Dongri You Inflows Into A Gift Next Vikas Don't Subject And Object And You Can For Every Element Your Kids From Left To Right Leg Top To Bottom And Also Taken From - K To Plus On Festival Taken From - K To Plus On Festival Taken From - K To Plus On Festival Time Agency Businessmen K Raw To You To Find All Threads Started By Sanjay Dasharupaka Vivechan Problem Short Top Most Polluted Water Enters In The Everyday What Do Black Return Again Deposit Only Next Point To You Can You Three Arrested For Bluetooth Quikr OLX Matrix Transportation And Lost For You Can You Do It's Over Every Day For Kids From All Roads For Every Problem I'm A Straight Boy And Friends Love You Can Chasma Powder S Pointed Toe Spoil Of The Box Distorted Ripe Fruits Trending Towards Samsung And Just Travels Every Problem From Left To Right And Updates And The Cockroach Problem Give You Can Understand The Range Updation Languages ​​Traffic Understand The Range Updation Languages ​​Traffic Understand The Range Updation Languages ​​Traffic And Videos Difficult Channel Video [ And Videos Difficult Channel Video [ And Videos Difficult Channel Video Update Ranges From Top To Bottom Alludes To Point Out The Name Of The Respect To For You For Editing That's The Matrix And This Is The President Of Tax Minus Plus Minus I click the plus like button state can be subscribe in 2012 subscribe a reminder add the metrics cellular to stop this a well-placed in the father stop this a well-placed in the father stop this a well-placed in the father and mother is the function of this artist in hours till the valve will attract - volume hours till the valve will attract - volume hours till the valve will attract - volume subscribe The Video then subscribe to the Page if you liked The Video then that Enid all the best till now and updated at point system will keep track of what is the capital on Android app The reader enabled MP3 format will change for every voter maybe from Left to Right and Updated Daily with Them and Updated in the Current President and Not to Answer This Question on
Matrix Block Sum
matrix-block-sum
Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_: * `i - k <= r <= i + k,` * `j - k <= c <= j + k`, and * `(r, c)` is a valid position in the matrix. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1 **Output:** \[\[12,21,16\],\[27,45,33\],\[24,39,28\]\] **Example 2:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 2 **Output:** \[\[45,45,45\],\[45,45,45\],\[45,45,45\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n, k <= 100` * `1 <= mat[i][j] <= 100`
null
null
Medium
null
1,041
That this controversy, today we introduce a new list of problems, the problem is that by setting up a robot wedding in advance, what is there in this, that they gave us a robot, whatever zero this above is the president, in the back of the plane and then we got a string. Have you seen the instruction, friends, how to free it, the stream will be high in this trick of ours, Yadav still became a fan, you must have got one of these three items, okay, what happened, maybe you are busy, maybe it is a common thing, yes, meaning. What will happen, be accurate, okay in which section, in this current affairs, this question was given, its corruption is fine towards Nath, then as I say, it is the first station of this group, which means each and every unit is in trouble. Then what will you say till the balance means take the plate, do the side issues with the discord about seizing it properly, now this side will be changed and right, what will happen to all of us is that we are frying this after agreeing, the direction is from here, like the recipe, if we Purvanchal state is separate from here, it is right, it is fine, if you are under more tension, then Aamir, please fold that this is the instruction we have today, if someone will unite us for the final time, let us do it on Friday next, then what is the robot doing my Kunwar's films? That is not doing us after doing a point means I collect a statement at this point then once the major is doing sea to stop the loss then return it otherwise for the form what do we do first In this case when we will create a position called ok position is ok which will tell what is its current position what is the current position of the robot so now what is the current position zero means ok and after that a Datsun here Let's make the address of the name, okay, what was told to us, that's why we have made the direction, like what is its working caption now, where are the notes, the protestors have written that Harold, first of all, understand how to differentiate the typing, okay, this is voice messages, this is the best. This is the name, this is all, you find that if my vote is not removing that nice, if the subscribe position will change i.e. we do, the position will change i.e. we do, the position will change i.e. we do, the Rashtra Sangh says that it will be subscribed, so what would have happened if it was covering it. Which I have cut from - 140 means school and subscribe, set a reminder for Quikr, this will strengthen your mind, I am worthy of you, it will be tips for you. If you want, this Manush Nagar gives a free strip, then we will give it to you. If you want to make a plate from us then you can print it facing this direction, it is okay with two commandos, it will be a little bit pistachio and clear which will come on a little point, okay, so first of all let us understand how we request the direction that you give us. What will happen is that you create a function named Moong, celebrate the function of currency which is of Amla, this one of this attack, this one of this team, this one, he will take whatever he can and so do a good and tell that this is going to be East and West. After this, what is the current position of the robot and what is its conduction? This monsoon will tell my mood function. Please note that the base is freeing me to check whether the robot is working on one thing or not. So the function of the address Muslims is to burn the wings of Amit four times. You have to check the current because if I burn it four times then if the same thing happens then 1145 Rani will come once more to the same place from where this happened. There is more to the matter, you understand it like this, believe that the robot, we have instructions only that and the exam is okay, testing is necessary because mother also, avoiding the case is definitely above, if one units goes up from here, it is okay and these are tips by mixing the sides. Have not subscribed the channel that tube will increase ok a little bit subject wise till PM that is 1 liter just finish for the stand ok now I have to check whether it repeats or not then comment if I find this chicken fit He is doing it like this, how many times will he have to explain that the owner has run it once, second or third and fourth thing, he can say change on the basis that he is deleting it on his pass, then if I run Movie Satsang four times in some section. I will run it four-five times, some section. I will run it four-five times, some section. I will run it four-five times, if it is done differently, it strengthens the arms. Okay, then what will we do, we will run the same movie statement MP3 movie second four times, call the option and then check it in the last, let's go with Mohan. I had gone to give bread to my friend in it, so I will check it, so only this thing, the current position is ok, is it ok, and then if it is zero, then if it is not for entertainment, then return it, if you find it, then return it is ok. Will make it possible Okay, I thought that you will do this action and tips, let's look at this free app, how does the movies function work? Okay, so what do we do, this red chilli, I have this mouth function which tells on our face. Will give that the statement should be done, current position and direction is ready, okay, what will it take, such inputs will be from this team, Salman will go, okay like this, okay, so what will I do now, run it, I have strong breasts, I have come from 15.12 districts, I am plus And strong breasts, I have come from 15.12 districts, I am plus And strong breasts, I have come from 15.12 districts, I am plus And why is this okay? Now what will happen like let's say what is the first statement, did you like it? Yes come what answer do I have? Subscribe to the passengers. Yes, it's okay or it can happen or this is what happened, I will see International further. It can come or it can happen or it can come Ghr meaning skin position what position if I have to show you that Meghwal ni 0 place this is when easy station will run and this will change you are wrong this notes chapter Okay, what will happen with this, voltage will be there and if 10.00 is applied, then what will happen with this, voltage will be there and if 10.00 is applied, then what will happen with this, voltage will be there and if 10.00 is applied, then we will be printing it on any Ishwar channel, what should I do, okay, plus equal to director, you, 0, plus qualification, because if what happens to me, then its Position and in which if you have this white click here introduction if you subscribe you are fine from here how are you and we first Kimam ji you lipton you will cover plate from here ok let's take a look at the letter Which direction are you? West direction, North and West direction. So we are requesting someone - Comment one. - Comment one. - Comment one. A fixed. If this thing will take the letter, then this thing of mine is needed. Okay, what can I give in the bank? Test of zero, what will happen to you? Section you must definitely give up - should you? Section you must definitely give up - should you? Section you must definitely give up - should also be - 148 I can't say this also be - 148 I can't say this also be - 148 I can't say this - one types of dereliction of - one types of dereliction of - one types of dereliction of war of more than 130, its white is good and even Aa the Bihar and means squadron more this part. Increase di 78050 like what will we do with this ghee subscribe to remove some of the previous ones so I understood that you will be watching so if we do so that this playlist when that what will happen if I write this of Rajasthan I take it that we are high - should be - how will it come, it that we are high - should be - how will it come, it that we are high - should be - how will it come, what are all the Muslims for this * what are all the Muslims for this * what are all the Muslims for this * position you are 151 quarters ok - 151 test, position you are 151 quarters ok - 151 test, position you are 151 quarters ok - 151 test, these are threads etc. and this is the one in the first one, my voice is from your wife, it is a point in Maithili but Pujara takes zero salary like this, boss, when we are ahead in this quarter, then we are fine here, and he says, you will do it right, you have to take it from here to the side, his time has been set, he is your mistake, if he asks you should come. The environment of zero is fine, in the middle I can say that whatever current mix fall has happened for him, it is fine, that is, I can Xiaomi that lamp age come one, I have this jugaad negative you lamp Diya Ul Haq CO is fine and prosperity comes. Go, what will happen, it is ok, subscribe this channel, it is ok, hey friend, what will we do, we will make the gas flame medium, what will we use to start it, ok, sorry friend, I want to say it is lost, or its jo Body part is there, if you have time definition but will vote then you can definitely search the whole idea and that too in any voice comment box.
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
237
hey how's it going guys today uh we are going to have a quick tutorial about how to recode the delete notes in a linked list in python so um the question itself is pretty straightforward you are given a linked list for 519 the note to be deleted is also given is five and your output should be on the four one nine so if your input is four five one nine the note to be deleted is one then you output four five nine so um the trick to this question uh let me just copy paste here so the trick to the question is uh well remember five is what we want to be deleted right so the trick to this question is to confer the note to be deleted into the same value of the next note next to it so we convert five to one and then we just delete the next one in this case we successfully deleted the node okay um and let's just code it up so um four five one i let me just put it here so we have access to the note right the value itself right now is five but we are gonna convert it into the next note value know the next value so basically you are replacing five to one and then we just delete the node so what we are doing for this step is to um so previously this node the node itself is
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
1,503
hey everybody this is Larry this is q2 of the recent contest last moments before all ends for our of a prank these this problem descriptions are very funny straight to the point but yeah hit the like button hit the subscribe button join the discord but the there's only one observation that you have to make and I made this because I've heard this is a trivia question maybe along that trivia but like a brainteaser question a long time ago but the key thing to notice about this is that when two ends cross each other you know you could simulate them you know juggling back and forth but the key thing to notice is that actually when they go with each other you can actually treat them as going past each other because it's almost like a reflected mirror where like you just do-do-do-do-do right like and do-do-do-do-do right like and do-do-do-do-do right like and you treat it that way you know they all just look like they cross each other right so that's kind of the logic behind the intersections and then when you make that observation then you know that for each end for example this t00 case you know see has to go three steps to the left D has to go four step to the left a has to go a four step to the right B has to go three steps to the right and so forth way and then now you just take the last moment that the last and force out the plank is just well the people would have to go right and just you know depends on where them how far they are from the right end point and then the people die there and stir have to go to the left just how far they're from the left end point right and excuse me and you could show that it's n minus X and then just take the max out Waldo's and that's pretty much all you have to do for this problem you could watch myself just live afterwards but in it you know it's just me typing up five six lines so I don't know but stay tuned anyway I guess and hit the like button but that's how I have and this is obviously o of N and then your time you don't get you gentlemen once we don't use an extra space it's it I don't I can't imagine it beyond an interior because it's more point ease and more than anything but hey you never know I guess so it's good to make that observation but yeah that's what I have with this bomb I hit the like button to subscribe button and stay tuned for the live contest portion now it sniffers oh it's a slow testing day yeah scuse me
Last Moment Before All Ants Fall Out of a Plank
reducing-dishes
We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**. When two ants moving in two **different** directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches **one end** of the plank at a time `t`, it falls out of the plank immediately. Given an integer `n` and two integer arrays `left` and `right`, the positions of the ants moving to the left and the right, return _the moment when the last ant(s) fall out of the plank_. **Example 1:** **Input:** n = 4, left = \[4,3\], right = \[0,1\] **Output:** 4 **Explanation:** In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). **Example 2:** **Input:** n = 7, left = \[\], right = \[0,1,2,3,4,5,6,7\] **Output:** 7 **Explanation:** All ants are going to the right, the ant at index 0 needs 7 seconds to fall. **Example 3:** **Input:** n = 7, left = \[0,1,2,3,4,5,6,7\], right = \[\] **Output:** 7 **Explanation:** All ants are going to the left, the ant at index 7 needs 7 seconds to fall. **Constraints:** * `1 <= n <= 104` * `0 <= left.length <= n + 1` * `0 <= left[i] <= n` * `0 <= right.length <= n + 1` * `0 <= right[i] <= n` * `1 <= left.length + right.length <= n + 1` * All values of `left` and `right` are unique, and each value can appear **only in one** of the two arrays.
Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient.
Array,Dynamic Programming,Greedy,Sorting
Hard
null
267
okay are we live hello i don't know how i'm doing in terms of the gain um i don't want to talk too loudly i don't remember what i did yesterday oh right now i recall i don't recall what i did yesterday i was kept my voice pretty low i don't know um i'm trying to keep my voice somewhat low today too so hello and welcome hope you're doing well i uh i just want to um solve another problem here um let's see so let's get to it let's just get right into it um okay given a string s return all the palindromic permutations without duplicates of it return an empty list if no palindromic permutation could be formed a b excuse me oh so for a question like this um there's a few things to consider so the first thing that comes to mind is with palindromes basically palindrome is you could take the middle of it actually i guess the definition would be it's the same string left to right as it is right to left so if you reverse the string it's the same string that's the that's probably the easiest way to explain what a palindrome is and what we probably want to do is generate all the palindromes here that's actually what they're asking for so all the possible palindromes and a couple things to note so it looks like you cannot have any palindromes if the number of characters you're dealing with if you have if you take the frequency map uh of all the characters for the string um basically just count the number of characters each for each character right that's what the frequency map is so like there's two a's two b's you know one a one b one c right depending on what you're looking at it looks like if you have more than one odd frequency then you won't be able to build any palindromes because the characters need to be equal on sort of you could sort of because reversing the string you sort of this notion of like a left side and a right side where you can it's symmetric there's this notion of symmetry there's sort of a left side and a right side and you could have no you could have only even characters in which you know half of them on the left have them on the right um or you could have um one odd frequency where one character is right in the middle and then the rest are on the left or the right you know that even number on the left even number or same an equal number on the left as there is on the right um but you but if you have two odd frequencies then there's a there's an extra character on the left or the right side that you can't match um with another character because it's odd right so that seems to be a pretty obvious thing is that you could basically just it's a sort of an edge case where well if you have that then you just you can't make any of these permutations um now how significant is that or important um it's kind of a minor point i think uh the next thing we want to do is probably take a look at uh probably look at how do you actually generate all of these strings what i would suggest is actually um let's consider the case where we don't have any odd numbers at all or any odd yeah any odd number and any odd frequencies for the characters at all think about it that way if we only had so basically our string is always going to be um symmetric from left to right this sort of like a string you build and then you can reverse it and append it to the other side um in that case actually every string if you divide all of your frequencies in half and have this sort of character count of each of these characters i would suggest that every possible permutation of those characters uh works and all you have to do is just copy it across whatever that permutation is the other side um and so you can actually just build a string um and then use that to produce all the permutations of that string and then for each of those permutations you just copy the same string across now obviously that gets a little bit funky if you're dealing with if there's an odd number somewhere in there so all of the there's only going to be one odd number uh at most right so there's no odd numbers what i just described is sufficient if there is an odd number that has to be at the center piece on the right side it has to always be there so basically you can just remove you could just do the same algorithm except append you know take that odd number subtract one before you do your division by two um take that one character should hold on to that and then before you copy across all of your character or your strings um sort of this reversed copy you just plug in that character right in the middle as sort of the centerpiece and that's it i think that's pretty much it i think that's sufficient i think that'll solve the problem so let's try to do that then so let's build a frequency map first um let's start with that so kind of complicated um somewhat complicated approach but it's not too bad you know shouldn't be too hard to code it so it's going to be character to int and we're going to say frequency let's say 4 auto c s we're going to say frequency of c plus i'm going to say so plus c plus i'm going to say so build frequency map there are more than one odd frequencies no palindrome permutations exist so we say uh int c just count equals zero for auto p and frequency say if p dot second modulo two equals one increment the count if count is greater than one return empty um i'm just going to use a empty return vector uh i want to say if you have so if count is one will handle one approach if count is not one um okay so we're gonna rewrite the code but suppose for a moment all of you know no we'll do this we'll do it this way first so we'll do it this way um just thinking we could do it this way center say if count equals one and we'll say we're going to find that about that one again just add that character count this one center and then we're also going to we're actually decremented by one as well before we do the next operation and now actually divided by two you can actually do something fancy if you divide dividing by two there's also a bit shift to the right by one so everything gets bit shifted to the right by one so divide frequencies by two and remove the center character we'll record the center character or store save all right yeah so save the center character remove it from the frequencies and divide all the frequencies by two so we do that now we want to actually build permutations build all of the permutations from the remaining from the character set so how do we want to do this what's interesting about this is also we want permutations without duplicates in other words if two characters a and a like we could put if you call label them like a sub 1 and a sub 2 there's like a string where a sub 1 and a sub 2 are in positions i and j and then you could have them reversed where a sub 2 is in position i and a sub 1 is in position j um where the two positions are switched but it's the same string and we don't want to have the we don't want to produce those duplicates so it's actually permutations without duplicates which is kind of tricky not exactly sure how to do that at least not off hand i can tell you how to calculate how many there's going to be i can tell you how to calculate it's basically the sum of all the frequencies after we divide by two take the factorial of that whole thing and then divide by each frequency take the factorial of each one and then divide each one of those out that's how many this is going to be but how do you actually produce all of those uh that's a good question um well we're definitely going to you going to use like a kind of a search probably a depth first search this on the state um i guess what you could do is you start with you pick a character move it from your character so your frequency set your character set frequency set um add that sort of that's the first have a string stream i guess stack really string stream um set that character add that character and then um push that character and then so you pick a character and you recruit you would you pick any of the characters that you haven't used yet that you have more to use and i think what's significant or important here is to not you're not going to you're going to consider each character selection with regard to each character unique if that makes sense in other words um you're not just gonna pick uh a sub one or a sub two right in other words if you just took a string of characters and assumed all of them are different characters and got all the permutations that's not the same thing as considering sort of basically considering the frequency of the character i mean that i think because we're using the frequency map it's going to be easier to do this we're going to be able to do this correctly the first time um modify the frequency each time yeah i think that's the right way to do it um yeah i think so yeah so you so i think i know what to do so we're going to use depth first search um it's going to look something like this we're going to turn ret at the end of it we're going to we're going to use this frequency map call it f we are going to modify it actually that's going to be our state that we're going to use our part of the state and we're going to have a few things so you have a base case and that's if you really don't need a base case actually uh well you're going to have the string stream that you keep using um really the whole the state could just be kind of you don't even need this frequency map i mean the whole thing is sort of you do need you need this f though explain that in a second but um string stream you need or want uh sort of our stack that we're going to be working with it's actually really simple so the only thing that we really need is i guess the character count um i guess that's really yeah i guess that's what we do that way and we can just do a sum over uh we'll just do it through this way and i want to say if um ss.string.size um ss.string.size um ss.string.size equals charactercount then ret.pushback ss.stream. ret.pushback ss.stream. ret.pushback ss.stream. sign our string and then return um basically you've used all the characters and you're going to do a loop over every pair in the frequency map you're going to say um if p second is greater than zero then you're going to f with f uh yeah you're going to first search again what you're going to do is you're going to say your take your frequency or for your frequency map you're going to decrement minus equals one after so after the recursion you're actually going to add the character back by the way um and you're gonna say string stream you're gonna push this character to the left side and here you're gonna pop the character i don't know if you can do that with string streams let me just test something here um oh i don't know if you actually do it this way the way that i'd like to do it i could try it though find out um oops all right let's see something here do that frequently oh okay uh can you do this do you need to have okay interesting so hmm so you could push a in when you push ss into t though you print the string stream it doesn't you don't remove that character which is kind of interesting so maybe a pop we can use or pop back no so we don't really want that do we uh i can just do regular string i guess do it this way what's that look like okay that's what we want yeah so he's a regular string then that's fine yes we find what is um can we do this i don't think it works no it doesn't okay you can do that with strings gotta be careful with string manipulation though it's a very could be a very tricky thing um the problem with string manipulation is that you end up with uh you can end up with copying a lot of things that you're not supposed to copy end up you're really slowing your code down a lot like that's string manipulation is kind of a tricky thing you can do um yeah we can do instead of a string we can actually do is just do character a vector of characters instead of a string stream we can do and then convert that to uh convert that to a string later convert those to strings later um yeah should be fine just thinking hmm okay um just thinking how do we convert the vector to a string i could use a string stream i guess it's not messing with my kneecap here okay anyway all right i don't know there's a right way to do it i feel like this may be kind of awkward but i want to avoid um i want to avoid using string operations it's really simple this routine tfs rhett should have a whole bunch of uh um a result we'll use an intermediate result a vector of character vectors and push back a copy of this okay now we want to hmm okay um mirror each character vector appropriately build the corresponding strings to return okay so we're gonna go for auto reference um call it just ss and the result we're going to say standard let's two i don't know two character vector we're gonna say four um i don't know auto it equals cv dot begin it not equal to cb.end it not equal to cb.end it not equal to cb.end plus it ss it if uh center not equal to animal ss center and then we do the other way around which by the way i'm gonna go ahead and string stream i don't know um vector of strings return we go cv or begin reverse end uh push back string and then a string empty that string stream before we use it again we'll have to create it once um that's it see if it compiles warning error what oh uh all right could do this um i don't know because center could be filled with junk right uh let's make it zero i just don't like having i like the checks that i do the logic that i have i like it to be like very direct you know in other words i have this thing going on here where i'm only setting the count and the character like i'm setting the character in the count in tandem and i know that the character the center character won't have anything if it counts not one but i don't want to just check the count i want to check because that's like sort of artificially like i've imposed that like these are how these things would be related to each other i would want to just check the character directly and that way like the logic is clear so yeah try i'm trying to get that to jive but um struggling with that but uh oh um ss uh well i don't know it's called new stream new ss i'm not really sure what i want to call it i like to keep my variable names kind of short i used to be all about like very verbose variable names but it just takes so much time to write all of it something like that um it's like it i thought it takes too much time to write all of it but it yeah it kind of does it takes a while to just write all of it and you really don't need to be that express of each um you don't need to have your variables really don't need to be that if it's kind of clear from the context what it's supposed to be you don't really need that much all right anyway so um what's this count oh duh i don't know i was going to say i was like how come of course you can actually call that function now that deaf research if you don't call it then it won't do anything output bbaa abb okay interesting this didn't uh what happened it's supposed to modify the frequencies does this not do what i think it does oh uh oh i see this is supposed to happen anyway um yeah i don't know this is so one or zero if it's yeah okay no nevermind there we go okay let's see the problem yeah my logic was a little bit off here i was thinking like oh okay well if there's one centerpiece in there then do this and there's no centerpiece do that but actually this handles both cases the logic here so because between this and this we know that there's there can't be more than once is either zero or one and if there's zero then this never fires and if there's one then this fires and that's it that's all we need um all right just run some tests see how we do yes this c has got to be in the middle um empty single character three characters and then a whole mess of stuff um let's see 1 a 2 a 3 a 4 a 1 d 2d 3d 4d 1s 2s 3s4s 1l 2l 3l and go through that 3ls 1k 2k 3k 4k uh 1j 2j 3j 4j 1f 2f 3f 2f 1 oh yes we did already we did our l d j i think we did everything all these let's see how we do on that last one i may have missed a character too i may miss some things time limit exceeded no you're kidding me really no saying so say it ain't so no oh it's way too hard if the time limit on this is serious then this is gonna be impossible there are so many of these palindromes oh come on i can't do it's not gonna happen oh no uh oh um move a couple of j's a couple k's couple d's a couple a's how about that please tell me that's not too bad there's a lot of these palindromes man there are a lot 48 milliseconds on the last one okay so we got there um let's add another f yeah this is very exponential the number of uh these palindromes and these permutations there's a lot of them um okay we add another f then we add gg output limit exceeded wow really yeah it adds a lot so 200 and 200 milliseconds and we add the g and the g there it'll just be way too much you get an f and f there i think that won't be too bad uh but it's a lot should be like a few seconds instead of a few milliseconds a couple hundred milliseconds should be like a few thousand seconds wrong no what do you mean it's wrong no oh you gotta be kidding me oh this diff button just broke it just broke my computer are we still streaming to break the stream it's definitely this diff button i click it's non-responsive it's non-responsive it's non-responsive it's gone it's done that's it for the diff is like uh-uh what happened okay it's two at the bottom all right so let's remove this one pull off on this one okay let's take this guy let's see is that does that work what do we got here okay that's fine the very last one that's okay but if we add another f this should give us a problem right now that's fine empty but now if you add one yep one more f in there really testing the limits here it says we get an error on this last one let's see why let's see what happens wrong answer really now the question is why also i'm getting what is it um i'm on vacation for my job so you notice i'm getting a phone call but not i don't know who it is or what it is but it's usually spam anyway but uh now this is interesting this says with the wrong answer what's the right answer can we get this diff hmm i want to say i think the reason what does that do if you're using global variables or cc plus check this out interesting uh okay can i get back to what i was doing all right so they're saying that these are all wrong okay a whole bunch of these are just wrong let's turn the diff off is this wrong are you sure i mean there's no this thing's flat out wrong now i would say i don't agree right i don't agree j k i think the issue is uh i think it's just having a hard time with the just the gigantic output just can't handle the output is just way too big true to reconcile f and f two f's two s's a d and a that is definitely a palindrome now how many f's do we have how many a's do we have one so now is this a permutation what's going on spam with calls today um we're gonna go ahead and j l one two three four five f's a d s ss s a k s f k s j d a so this is definitely an answer so they're having a hard time they're this solution here this testing portion is just i think the output is just way too big yeah it's gigantic output for this so let's see how we do we submit it let's just see how we do we submit it i'm curious to see what happens oh there you go 100 of all the solutions nice super efficient super fast hey i like that took a while we got there um how do we do 50 minutes it took though oh 48 minutes wow that's a lot of minutes i don't know man i don't know if i could do that faster than that's probably as fast i could do it like i've seen questions like this before um i kind of stumbled and fumbled a little bit with regard to like should i use a string stream should i use a string should use a vector character vector like what do i want to do um but obviously i got the most efficient probably the most efficient way to do it um yeah you want to really avoid too many string manipulate string uh operations directed on strings and you want uh you have a vector for character vectors i think it's not bad that first search is really straightforward um this is like a pretty efficient way to do it i guess it's more efficient than anyone else came up with i guess or as efficient yeah um all right let me go thank you all for watching talk to you too soon that'll be it for this video i'm going to go ahead and um take a break nope hopefully you can still see me oh no you can't oh no there goes all right that's always good um yeah the plan is take a quick break um hang out for a minute or two i guess um and i don't want to make food or want to hang out i don't know what i want to do um i don't know what i want to do exactly um i think what i'll go ahead and do is send this stream take a few minutes come back and do another problem that's what we'll do so yeah thanks again for watching
Palindrome Permutation II
palindrome-permutation-ii
Given a string s, return _all the palindromic permutations (without duplicates) of it_. You may return the answer in **any order**. If `s` has no palindromic permutation, return an empty list. **Example 1:** **Input:** s = "aabb" **Output:** \["abba","baab"\] **Example 2:** **Input:** s = "abc" **Output:** \[\] **Constraints:** * `1 <= s.length <= 16` * `s` consists of only lowercase English letters.
If a palindromic permutation exists, we just need to generate the first half of the string. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.
Hash Table,String,Backtracking
Medium
31,47,266
1,419
milk to Ajay, everyone welcome back, paper folding, Ayo point to Delhi, our serious ones, solve this no contact mon, follow them, you are solving them, keep giving like comments, do tractors, first try to give questions pipe contest and those who Period questions contact to we put their videos back them and try to read soya sauce in the previous video I clicked on the link call for Mukteshwar I had set 195 meet 125 and got his first question done Reform and sustained buying so my questions I am going to do Doctor Spoil's 1419 question number is minimum number of frocks click 500 this portion first understands what is saying then he does pride su can take his open loop question head burst and maximum Okay, so the tips are now a scientist, he stopped the human growth, we, a person, the combination of the subscribe screen is from different from multiple problems, now it is not known whether we can do it right on time but it is multiple that all the subscribers If we can do it then it's okay, so we will understand something like this in which there is some problem, let's work which frock is okay, there might be different mix in that place, see personal, now we have to return 1/2 inch, minimum return 1/2 inch, minimum return 1/2 inch, minimum number of different strokes to finish all. Duck Hunting ok in this movie we will have some combination of life from Rok tell us what is the minimum number of frocks send all the products ok we will do it interesting oceanic now belt me ​​Akshay talks about the validity of walnuts me ​​Akshay talks about the validity of walnuts me ​​Akshay talks about the validity of walnuts this will be velvet group Cup sleep from this printing for black deals CR oy give proper this 5 minutes if am most important sequential am that chicken if this 5 minutes will be bright then this 1 stop of ours this throw will be able to do with our humor and peaceful alarm that our velvet ka to frock On print all five letters, up to one Deputy Director, Giving Water Commission of Electronic Digital - On Doctor of Electronic Digital - On Doctor of Electronic Digital - On Doctor Hussain's answer, is it correct or will you say that it should be decided that it is happening but there is a spelling mistake or not, it should be done first and then If Patan follows CR, then sequence tips of one, then we will hit him in this group and we will sign him a frock, okay, come on, you can throw this frock, okay, so there is some question like this, question so we I have decided to understand that a little or a lot of biscuits are given by this and it will come well to the concern. What is given in the box? CRO is another jackal that I am taking with me in this program. Hello, how to come here, common concern to love, close to the CPRO of the P.R.O.L. One, tell us the CPRO of the P.R.O.L. One, tell us the CPRO of the P.R.O.L. One, tell us the minimum number of more numbers required to make these two throws. First of all, it is visible in this. Okay, this is what we teared together, one from which came in which set CRO one in that, you did it completely. Now what is the second from this ruler, the first means here. You can start from here, there are multiple frocks which can be done, you can tighten one frock at a time, if you set it then do it, then when you are doing the end, then again you can start the saver so that if the minimum number from the well was not minimum, then we would have started with 120. While signing a paper, it's fun. What to tell us? Minimum number seat one, we have signed from here, CCR Oye, then we have finished this prop, now second, from start to bay right, now there, from here, then again. Will continue from ' now there, from here, then again. Will continue from ' now there, from here, then again. Will continue from ' Pro one' How many boxes do you need, put Pro one' How many boxes do you need, put Pro one' How many boxes do you need, put minimum problem one from hearing form, like it 12 times, like it and use it twice, explained the voice mail tips, what is given in it, mark the next one as beta testing, let's move on with this. First of all, okay, you come down, let's expand it a little bit, do you discuss it? Okay, now show us the meaning of this, Alam, I am telling you exactly what we met when we met, as if we understood each other. Got it means that a businessman has paid Rs. 1 crore, it has started, it is okay to be, but given a problem, but look here again we got into it, got it again, it means that we will have to sign another frog, Vivek growling. Don't hide it below, do another one, it will set it is not possible, ride, so what will we do here, will we sign the second experiment? Okay, so CR, this one is over, the first problem is over, now where is the second product? Get the CRO written, if you finish the second final, then how many minimum forms are required. If two products are put in my mouth, then number of 200 is one incident, FROC is cleared. Got it, okay, now let us see the third RO edit. We did it absolutely perfect. Diya now second first C OK Vikram no same again not this whole there is not even one in it so this whole is invalid so what will we do - but it has what will we do - but it has what will we do - but it has become medical ribbon friends invite combination of from different forms worry so we have to tell only this What is the ballot combination, is it sequential, how many boxes will it take, so what I said, there are two conditions, we have to tell the minimum, how many are the minimum from this point, we have to keep the coins from being polite to ghee and till. It is very important that both these conditions are satisfied. If we try to become president, okay, so the first one takes that PRO L K CPRO A was so first of all, like we mean by closing it and doing a request from, the first indication is PK and question given click. Stopped doing from the one who had signed that God 22 which she had understood means that means one finish okay and in the middle of that the latest song what is theirs to see who is it I seeker this is a little bit powerful someone It seems easy to do, okay, or let's see it again. Let's follow it a little bit and see what we have to understand. First of all, C came, meaning I have some chocolates with the name Active Rock. Okay, keep it, I closed it. Okay, so here. But I put one, came on the makers page, one drop has already happened, now the hospitality is coming, Narco Brain Beach, did a stranger ya-ya like fare one, but ya-ya like fare one, but ya-ya like fare one, but how many active troughs have become now, towards zero, rock one at that time. So there was one but now if we get zero knowledge then it will get messed up so for this let us keep an answer name kami ok what will we see every time we will see the mac of active drops and force about the answer - keep in mind it will force about the answer - keep in mind it will force about the answer - keep in mind it will not come now This will be understood, stay tuned, okay, you will understand, what should we do? First of all, active from wrestling started, meaning it became active, at that time, on one side, there is an active from, next, we have also given the answer to that, okay yes, the entry has been done. Now as we saw that the sequence is also because the explanation is backstroke which will now be reduced to zero but that McDermott Macram had done 1, so the match strength has been used till now, who knows how many from have been used with me. If a person from some time, which is the previous chapter, who is protecting the time, who is softening the answer, don't know how many frocks have been done, okay now I understand a little bit, now let's see again share seventh, it means by becoming an active rock. Now you have made it clear that the tears will remain only one pair, that exam is coming, its meaning is Pancholi, as seen, meaning Active Rock still opposes the answer depth, what to do in this return, we should return answer and We will know how many frocks are used minimum, how much is the minimum boxing time, how much is the part, smooth, this is the next word, which is the touch in it, how do we drive on it, what was PRP, give CR, try to fix the sins of CR COL. First of all, it is as strong as it has increased to two. If you do n't mute this answer, then its CR came from there. We saw that it is fine, it is well, that we saw that we reduced the tax to one, that now only There is active productive have significant network but it is shown broken type is showing right because 2 strokes have been used that from one C is a tattoo from the middle so one cannot be two Prabhu Ju have fixed now from here we have this rock line speed It was done under Part 21, till now you will find the answer, our piece means use in profit, minimum, some stories, so we have to understand that while taking something like this, we wait for the vaccine, we take it, we live for a minute and we take it black. Black live is for a black ink tank as it came increase the C two active productive rock above the head by closing it at this time meaning frustrated that what is like on Plus by decreasing on the frock place and chanting you anyone heard decide to open Do this, you have understood how to do it, you can take this or you can make all these differently. Subscribe August So this is simply gone, we have checked, we have this with us and we have ours and the answer is how to do this. So how will we do this? It means there should be CCR. If here we closed it, we will check which set of ROA is coming from this previous inside letter. If you have more CR here, then OK. This problem is told here, what do we have to check to do it as soon as possible, every time our interior is of my use, which is when we are making this whole group letter, after greasing the scene as it comes, we went to the forest as it is coming and invited us. Did that came that English a time what will we check like see here C came I increased C and I came from financial side that I increased one I will capture in every time that as I came what should I do what C is my It is visible that what should happen to everything is that C should become small in economic if CR becomes small but from this eight we will have to make a little C RS will have to become big, our answer is from or listen again our answer will be Kumbhaka by stopping if any. Condition when CR is smaller than Now we checked here, what is strange, sorry, this ad and then zero was found, yes, this condition is also gone, it is sensible, I checked the sequence of the palace, how am I checking that every time for every tractor, I will share that if my old one If it becomes smaller, then it will have to be increased by colors so that we should be bigger than our old one, life means speed will have to be increased, RC Arya will have to be bigger, so Se will have to be increased, like this, we will have to increase it, meaning turn off the mode every time, it is increasing. Okay, if I am bigger than the one with my hair, then it means that the peace is spoiled, this time I try again to explain that as CR is one and Bluetooth CR is Agro's chicken, now I increased myself and checked. So right now it means that we do not make the cross small, so here I have made my small, so its meaning must have come earlier somewhere, later its meaning but technically and correction form format is required, the first answer should be big but here. But what is happening here is the opposite, it has become smaller, it means that the before and after sequence has been messed up, let's shrink our time a bit, then I will try to go to the canteen, okay, let's come here, what I thought most of all. First of all, take one of these, please, first you can make 10 manipulations on the coin of this size, add one in one, click on the flower ban button on the third position of the fair, I am making it a little simple, CO Jiaulhak, take one mango. Take 10 12 Take that chicken is for a hole quot So let's go to the media SVR 11 Speaker Now what did I do Now I told a thing from a text Who just keeps crying and taking the answer - just keeps crying and taking the answer - just keeps crying and taking the answer - Suryavanshi's spelling What did I say now This is what I do to eat petrol, I sprinkle it on the green collector by making a loop and what will I do with it, she will laugh and change into an actor who has skin thought to rap and this has changed, now what switch case have I done? That it is fine on the tractor, if it is KC, then what will you do? Tell me, if KSP is coming, what will happen, if it is KC, then what do you do? Go to friendship, go to Plus, press OK and this means active box. Next, if the case is there then what to do and increase the cigarette simply and break. Next if everything is fine then what to do. Go and point it at the entry point. Okay. Yes, how about today, what should I do, increase it to one, increase it and delete it is true, it has become like a ride, it has become like crying, if it has been done, then what will I do, or should I not increase it? And on Safe Rock, you have to reach this thing in your mind that will you do it in the pot, okay, Swachh Bharat, come out of Swachh, now what should we do, as soon as you come, first of all update your answer, and whatever is your artist. Drops are there, I have given its marks, now I will tweet every drop, what should happen, if the seal day is healthy or all admin is done, Mr. Wait is not old, it is where the main laddus are, if any such condition happens, then you return - composition also. If the condition does not come then you return - composition also. If the condition does not come then you return - composition also. If the condition does not come then you can return your answer gift. Okay, so let's see a little what I did. In this again I will create a digital plus in the name of my C.R.O.L. digital plus in the name of my C.R.O.L. digital plus in the name of my C.R.O.L. Okay, I have given the answer properly and finally. Now you have What did you do Agasthiyar, so what all did I increase the white tips, now the accused driver is coming, but yes, it follows the code, let's drive a little, work on it, how much will the situation in the chamber come to you? If he has gone then it is good, okay, so because of being mixed from school, what is it that we accept now and Skin Malik, okay, he was a little child of CRC OA, what made you so angry, first of all we took one thing from each other and First of all, I used one drops, if any of these are not in condition then we will not do it, we will take back the potatoes, we have to work on it, ok, yes, similarly for all the world, we will check, understand the condition, we will do it every time. Will you send any such SMS towards festivals, I will tell you that it will be like that the previous one which is invalid will be seen as a cigarette or you are thinking this Robin, every time we do not write this within our loop here, Dalits should be tight because like if we check These people are doing CR. Okay, some are straight in the middle, okay, some are far behind him, if you keep checking tight, then you say and he will stay behind. Let me tell you, drawing on all the matches of the special test. 31 seats are still vacant, who can see, okay, half or as it came, now what are the items from ours, what are you, okay, crossed, I have crossed the one with eyes, okay, that one came, the other one is still on the side. Look, there are tools in these temples. If it is not there, then this - but it will not go. Understand not there, then this - but it will not go. Understand not there, then this - but it will not go. Understand here, it is important to check this thing every time. Okay, now it came and I closed it. Okay, similarly or one thing I do is that I have decreased the two drops, since then it is running smoothly here, you have come to the block with the permission, are you just tattoo labs one and a half, if it is seated, then why is it sleeping, when is Aaradhya art done, Oye came and to Pretty. What will be seen from the poll, this is not only and approved, now what happened, we have started again, so we can still take the spike, like this extra rebelled and the channel of YouTube heated the leaves and see, is it right that capsicum of stories A missing written statements from it's minute one more minute and we will vitamin that coming out A Shravan and everything see the situation of all these minutes of EP will it work right think a patra tell me what's going on Ajay to jhal 163 Tell me, whose is this not working, what can we say, is this an interested report or I hope the impartiality of the meter is Dixit, CR goes with this, it will depend on whether it is true, CR, LCR, so 16 you take from this experiment. CCR takes question answers, so for one, first of all, you closed C and you are not able to understand this, will you keep checking, isn't it like this, I have not seen it yet, now after that come Army, you do it. Now check and see that it is not from Parle, whether it has been opened or quoted, it is fine, but ours and our side have not received it, not only 1000 are active, and we have also given the answer because it is still going on. If it has happened then it means it has come in the last today, it has happened, then we will return the answer in this, we will not do it, we cannot do it, what will we do before doing, we will check if the actor is the problem, which is Neeraj, then I will return the answer otherwise. - I will button - I will button - I will button Ajay that the camp is more, now there was a problem here, now see what it is now means Organization Secretary and 400 250, if not then return tax 2 - But it means the 250, if not then return tax 2 - But it means the 250, if not then return tax 2 - But it means the whole problem has not been fixed, you will not get ringworm CR One, no one has come to like. Will you return it for a week? It will be a week, pictures are done, no, that like, pure sequence was done and it was closed, no, it is only done, now let us check here, is that lab photo zero, yes, it is in this condition of the waves, so the pension is not balanced. If you are not satisfied, if it is tight then it should have been bigger, but 50 is what it is left, it is what it is and if it is done, then you - first and if it is done, then you - first and if it is done, then you - first turn that all this is only in a tempered glass, so Chicken Chilli is checked. But for this, it is not being checked for getting tightened by the belt, there is no sequence, what should you do for inches quality tight, the experiment is leaving time in the end, the product itself is also getting tight, hug from any happened this. You will feature that if there is no active problem then the answer cannot be returned only because it was semolina, this question was Alka's enemy, what we had to do was that we had to tell the minimum provided, then what did I do by correcting the sequence point, you can replace it with five sizes. Ca n't even interior of Okay, I have different this variable C yes sorry CRO question will come C country meaning what to indicate do torch pack chicken but as many as 160 children have been there, first I took a video doing paan salaam to install them. It is ok but every time I will keep telling me that my case is valid and if anything is coming after that then it means invalid - but in the last case, invalid - but in the last case, invalid - but in the last case, complete the electronic form whether it is complete or not, the court also came to Kailash to do that. For this, I have come up with a suitable question for the person. You must have understood that this is a diet, now you can tell me in the comment section. Okay, now the next video is for 5 minutes, we have to do Bigg Boss or 100, see you in the next video. I have pranked you so much.
Minimum Number of Frogs Croaking
minimum-number-of-frogs-croaking
You are given the string `croakOfFrogs`, which represents a combination of the string `"croak "` from different frogs, that is, multiple frogs can croak at the same time, so multiple `"croak "` are mixed. _Return the minimum number of_ different _frogs to finish all the croaks in the given string._ A valid `"croak "` means a frog is printing five letters `'c'`, `'r'`, `'o'`, `'a'`, and `'k'` **sequentially**. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid `"croak "` return `-1`. **Example 1:** **Input:** croakOfFrogs = "croakcroak " **Output:** 1 **Explanation:** One frog yelling "croak **"** twice. **Example 2:** **Input:** croakOfFrogs = "crcoakroak " **Output:** 2 **Explanation:** The minimum number of frogs is two. The first frog could yell "**cr**c**oak**roak ". The second frog could yell later "cr**c**oak**roak** ". **Example 3:** **Input:** croakOfFrogs = "croakcrook " **Output:** -1 **Explanation:** The given string is an invalid combination of "croak **"** from different frogs. **Constraints:** * `1 <= croakOfFrogs.length <= 105` * `croakOfFrogs` is either `'c'`, `'r'`, `'o'`, `'a'`, or `'k'`.
null
null
Medium
null
1,646
hey everybody this is larry this is me going with q1 of the recent eco weekly contest 214. this actually ended up being the most uh well the one that i made the most mistakes with during this contest get maximum and generate it away so basically you have this generated array and i think it's just really hard like i need maybe two monitors or something to be honest where i just have to keep on going up and down so i kind of wrote this and this is just literally a copy and paste of this thing so i don't think there's anything tricky about this the for me i got two wrong answers though if because um because i was just using n in the array construction so i was not um so i was just going out balance because of silly reasons um but i think if i were to do it again i would maybe use a dictionary instead this would have been much cleaner to write i think to be honest um but and i wouldn't have to deal with our balance issues and then i had a second wrong answer because i was taking the max of the entire way which was our balance at a certain point uh and i think to be honest it's a little bit of a matter is just that i was trying to do this way too quick and i had silly mistakes and i usually test more thoroughly but for this case i was just rushing it i didn't i was watching it there's no nothing about it and for me sometimes when you watch it you just get silly and 10 minutes no matter how much i slowed down um you know i could have found all 100 test cases and it would be okay so that was just silliness on my part i really should have tested the big cases um yeah but otherwise it's just follow the instructions and then return to mac so i don't have any more here but let me know what you think let me know if you did this one quickly because it seems like a lot of people even in the top got wrong answers right so definitely already um a problem that a lot of people you know it's easy to get uh make mistakes so let me know how you did it let me know what you think and i will see y'all oh and you can watch me something live during the contest next so you could see how i made those silly mistakes and you'll be like ah larry come on anyway i will see y'all you know watch me stop it live next pretty slow hmm okay you oh i don't know if i get this way this is really weird to be honest really oh come on do we want to let's display it oh my god what a silly mistake bye five minutes and also f wow well this is not gonna be a good problem but uh expected 1 2 1. oh man i am just being dumb to be honest uh ah thanks for watching everybody remember to hit the like button hit the subscriber and join me on discord and we'll chat about stuff later bye
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
142
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel so that you get notified whenever i post a new video so without any further ado let's get started so the problem is linked list style 2 will be given head of a linked list and we need to return the node where the cycle begins if there is no cycle return null so we need to return the node where the cycle or you can say the loop is starting so if you see this linked list over here the loop or the cycle is starting from this node two so this in output we will return two so let's see how we'll approach this problem so let's see this is the link list given now see we will first discuss the brute force approach so output for this in the output we need to return this uh node two let's see how we'll do it so if you see we need to find where the loop or the cycle is starting right so if we start the traversal we see we go to three then we go to two we go to zero we go to minus four and from minus four we again go to two so the first node for which we are again traversing it we are first node which we are traversing two times that will be the starting of the loop i hope you agree on this that will be the starting of loop see 3 2 0 minus 4 and from minus 4 we again go to 2. so earlier we visited two and from minus four we again visited two so two we are wasting two times so the first node which we are listing two times will be the starting of the loop so if some uh like by doing something we can store how many times we are visiting each node like if we have visited two earlier or not then we can say that okay if 2 has been visited earlier and we are again visiting it so that is the starting point of the loop so i hope you just pause the video and think which data structure you can use to store the all the nodes which we have traversed so i hope you got it we'll be using a hash map so we will start reversal from three so we will go we will first uh when we are at three we will add three in the hash map you can add anything as value we are just we just need to store this key right then we go to two we store this in the hash map we go to zero we store this in hash map we go to minus four we store this in from minus four we go to two again we see 2 is already in the hashmap 2 was already in the hashmap so if 2 is already in hashmap don't again insert it just return 2 that this is us this is our starting of the loop this is the starting of the loop so this is one approach in this we are traversing the linked list so o of n will be the time complexity and space complexity as you can see will be o of n again it will be often it will be oven so the this is not optimized approach obviously now let's see the optimized approach so in the optimize approach which we'll be using here first of all we'll discuss the approach and i have already made a video in which i have explained uh how this approach is working so the uh i will uh like give the link of the disc of that video in the description you can check that once i highly recommend that you'll be able to understand why this approach is working so the name of that video is remove loop from linked list so whenever you know like whenever there is a loop or cycle we need to find the size starting point of the cycle or we need to remove the cycle this approach is used mostly so the approach is you is a using slow and fast point we'll be using slow and fast pointer let's see how this is working so we will take a pointer slow initialize it with head so head is this head is initially given to us at 3 is the head of the linked list so slow will be 3 and fast will be also three so both slow and fast will be initially initialized to head right and we know that every time slow will move by one step and fast will move by two steps if you know middle point when we have to find the middle of a linked list when we have to find middle of a linked list we do these same steps only and when slow and fast becomes equal no sorry not equal when slow when fast reaches the end of the linked list then wherever the slow is that is a middle point right so this is one application of slow and fast pointer to find the middle of the linked list here we have to find the starting of the cycle in the link list so let's see how we'll do that so let's see what we will be doing is we will move slow by one and fast by two steps so initially slow is here fast is here so slow will go here and fast will go by two steps one two so fast will be here then slow will again go by one step and fast will go by two steps so from zero to minus four and from minus four to two so fast will come here then slow will come here at minus four and fast will go by two steps so fast is at two so one two so fast will come here now see slow and fast becomes equal so when slow and fast are pointing at the same node then what we need to do is when this is done when this condition is reached we will move our fast pointer to the head of the linked list so we will initialize again our fast to head when this condition is reached we will again initialize our fast to head so fast will come here and slow is here right slow will be there only now what we will do is we will move both slower and fast by one position only by one position so slow will come minus four one position so it will come at two and fast also by one position so fast will come at two so see now again slow and fast becomes equal so when again slow and fast becomes equal this is the starting of the loop so this is the approach which we will be using if you want to know the reason and how this approach works i highly recommend just watch the video link will be in the description and it will come up in the i button so now let's see the code for this so see what we are doing is java link will be in the description uh first of all we are just checking whether we have an empty list so just return null then uh if we have empty list return null and if there is only one node in the linked list here heads next is null means only one node then also there is no cycle obviously one node does not have in cycle so just return that now we are taking three like we are taking three variables you can take two also but here what they are doing is what we did was we uh initialize fast again with head so you can do one more thing you can take a new variable and you can initialize that with it right and then you can move slow by one and that new pointer by one position so either way you can do it so i will uh i'll recommend to use another new pointer only because then if you use fast only then this will get affected so this we are running the loop and we have we are moving slow by one position and fast by two positions if they become equal then what we did was when they become equal we again initiate we took a let's take a new variable only we take a new variable which is entry it's all already initialized to head and we will run the loop until slow and entry are at same position so when see when slow this they become they come at same position that will be the starting point of the loop so we will return entry then otherwise just return null if we did not found any cycle so i hope you understood the approach and the code if you have any doubts let me know in the comments if you found the video helpful please like it subscribe to my channel and i'll see in the next video
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
745
hey what's up guys this is chung here again so this time uh today's daily challenge problem uh number 745 prefix and suffix search okay so you asked you're asked to design a special dictionary right which has like some words and allow you to search the words in it by both a freak fake a prefix and a suffix all right so that's it right i mean so basically you initialize like a word dictionaries with a list of words and then the so you need to search by both the prefix and suffix right so for example right i mean the letters we the word we have is our is apple you know and the search con the prefix is a the suffix is e that's why we need to return the apple oh and one more thing and once we find like uh a match right if there are like a multiple matches we find we need to return the one has the biggest index that of uh in the original words list okay so going back here so we have apple so a and e right we can search because a is a prefix is a suffix that's why we find this apple so similarly for like you know for a ap right so if we have the ap at the prefix and the le at the suffix this one should also give us like the apple okay and some like more like extreme examples you know so this prefix and suffix they can be intersect with each other so which means that if we add one more letters here you know if the prefix is app well let's do appe right and then the suffix is pple right this is a prefix this is suffix so this two should also give us sorry this is a ppl no right so this two this prefix and suffix should also give us like an apple right cool so that's basically the basic idea of this problem and obviously you know this one is like a try problem right which means that we should use a try structure uh the prefix tree right to solve this problem and an evil approach is what since we have a both the prefix and suffix we need to match um then a naive approach is that we have to uh build we need to build two sub prefix tree one uh one is from the uh from start to the end and the other one is from the end to the start okay and then while building this the pre that's the prefix tree right uh we're also gonna at each of the node we're gonna maintain like a list or a set of the uh of the index of the word index that has that prefix so the reason we need to maintain like an index sorry a list of index or set of index is because later on after building the both the prefix tree for the in the from left to right and from right to left once we have this prefix and suffix right we're gonna use this both the prefix and suffix to find like uh candidates right the indexes has this kind of prefix where it's going to be a list one right and then we're going to find like another with this suffix we're going to find like a bunch of other index result it's at least two right and we want to find the intersect of this two list and then among all of those kind of intersect we find the biggest value the biggest index that's how we may basically solve this problem in the naive uh prefix three uh solution right but as you guys can see this one is not very efficient you know not only we're gonna we need to maintain like two uh prefix three but also you know we have you know this intersect actually that the prefix tree is not like a big issue the big but the bottleneck is like this intersect you know because we might have like a know the words right so the words have like uh this 15 000. you know these two lists might be a might be pretty big and if we do intercept it's gonna be a n square time complexity right you know that's why we uh we're hoping we can find like a better solution you know instead of like doing uh two so that we can avoid doing this kind of intersect so i mean it's this kind of prefix plus suffix uh problem you know a common trick is that you know since if we like uh write two words let's say we have apple and if we have a like apple here you know these two apples you know we have if we have like anywhere separated in between like a hash like a pound sign here you know if you look at this kind of uh two letters you know from here to here right they're kind of like symmetric in a way that you know so this let's say we have like a prefix like uh a and the suffix is e so what does this one mean it means that you know if you look at this one so the e a palm sign a this is the string right basically if we have this string in the prefix tree then we know okay so this suffix e pound sign a it's a valid uh it's a valid combination for this apple right similarly if we have like ap you know apn what this is a le right this one is also going to be a valid one you know that's going to be what can be the le uh plus this uh separator plus a and p right and if we continue doing this you know let's uh keep this le uh the same and then if we keep it keep expanding the prefix tree i'm sorry the prefix gonna be app l and then l e right so this like what we have discussed this one should also give us like that the apple which in this case is what so we have le and then the tag le stays the same and then we have a separator here and then we have a p l right so from here to here right so now i think you might have already find the pattern so basically how can we use like one prefix tree to cover our kind of scenario we just basically need to concatenate this uh apple this word with this twice with separated by this uh pound sign here and then we're gonna add a word into this into the uh prefix tree as what as e pound ap ple and then the second word is le pound a p l e right this third one is the p l e same thing and then last one a p l e same so now this is one apple we're gonna add instead of one word we're gonna add this kind of five words into the prefix tree since with this kind of five words added into prefix tree you know basically we have covered all the possible uh prefix and suffix combination that's apple this word apple can never have because you know basically this e right so this e is the one of the suffix right so this word basically this one covers all the possible combinations you know with the suffix as e and the prefix could be anything prefix can be from a to apple right because you know for this kind of word you know when we add to the suffix tree we're going to add like e upon a e pawn a p and a e point a p l e and if the this is kind of a e as a suffix you know if the prefix is a then we will look for this e pound a and if the prefix is a ap and then we just keep going right we okay we find the ap okay that's going to be a another prefix right of this word and then so on so forth so appl abple basic right and similarly for this one so basically and then if we continue basically the second word covers other combinations with is suffix equals to le right and then the prefix also the same from a to appear le and then so on and so forth so the ple is the suffix and the ppl is also suffix and so on and so forth so now if we do this in this way you know even though we're storing a little bit more uh we get more like words into this kind of a prefix tree but we have we don't need to do this kind of intersect right yeah and that's going to be a common uh trick for this kind of prefix and suffix solution you know actually this kind of uh a tree can also be used it's very common with prefix suffix because as you guys can see if we concatenate this one two words together now if we look at uh starting from this kind of uh pound sign here you know the left side is all the suffix and the right side is all the prefix cool and yeah so let's start coding that right um for the prefix tree you know there are like a bunch of ways you can do it you know someone prefer using a dictionary so to me personally i maybe just one just my habit i still prefer to create like a class you know to represent the note in the tree you know you can use your own way it doesn't really matter and self dot children right and then oh and what and one more thing you know since we don't need to do this kind of intersect and instead of storing uh a list of index for this prefix we can simply store the max index for this for the same prefix node right and because you know since we're processing the words from the smallest index to the biggest one we can always update this max index okay all right so to do this kind of route so we have a node right that's going to be the root for everything and then for each of the word since we need to use the index i'm going to use enumerate right to the words and what else so i here you know there are a bunch of other ways you can in uh enumerate those kind of new words we want to add you know for me i'm just using like uh this one i'm creating a new word it's going to be a word plus this one plus word right that's going to be the new word we're trying to add and i'm starting from the first one you know basically we have apple right uh this one apple i'm starting from the from this index and that will stop from here right so for any for e for each of the iterations i would just uh loop through from this index to the end that's going to be the string we're trying to add into this prefix tree okay so it's for j it is in the range of length of word right this is the uh the first level iterations that's going to be the starting point of the new word right this is the starting point and then so for each of the new word we're gonna do this kind of thing right so the current one is always equal to the root and then so this is the starting point of the new word and then for each of the letters i have uh i have a k in the range of this is the starting point of the new word and we stop at the uh at the end of the new word okay so that's why i created a new word here because i want to use both of the length of the old all the word and the new word okay and this character is going to be the new word of k right and then below it's just like the regular prefix tree template so if c not in current.children so if c not in current.children so if c not in current.children right we have current.children.c right we have current.children.c right we have current.children.c is going to be the node actually you know what so if we use like the uh a default dictionary here instead of a instead of like a regular curly brackets maybe we can uh remove this section but you know i'll just keep the way it is i mean to avoid this track here but anyway and then we have a current equals to current.children.c current.children.c current.children.c right and then current.max index is right and then current.max index is right and then current.max index is going to be the i right that's how we update that oh and by the way i think uh in this case we don't need to consider this uh pound sign apple case because uh in the constraints it says the uh the prefix and suffix is at least one character that's why you know this one this condition is not valid right yeah i think that's it right so this is how we initiate the create this prefix tree and then for the search it's pretty it's very simple right we start from the uh the root and then for the search work for the search word we simply uh concatenate the suffix and the prefix right and then first c in the search word if c not in the current.children right if c not in the current.children right if c not in the current.children right we simply return -1 because we know we simply return -1 because we know we simply return -1 because we know we couldn't find that this combination otherwise keep going right so once we have reached the end of the search word we can simply return the current dot max index yep i think that's it run the code did i oh i think i'm missing like colon here okay accept it cool so yep so it passed right so the time complexity for this one is what uh let's take a look so first we have n right so let's say the n is the length of the words right so we have to initiate right so to initiate this one we have n times what times uh we have an acid for up here that's going to be the what this is going to be the length of the words right so let's say we have the length of the words basically the maximum length of the word is m we have m square right because we have for loop to do that and then for this kind of uh for the second part which is the query right plus what okay so there are like this number of costs right to make the function of course let's say this one is k this is k cos right so we have a k times what times a search word this is the amp right because we have we simply have like a photo here and this one is like also within the boundaries of the maximum length which is app yeah so that's going to be the total uh time complexity right and space complexity of course is the size of the prefix tree which is what which is the uh which is a n times m squared right that's going to be exactly this size of this nested for loop here yep so this is the space of this one cool i think that's it right i mean this is like a little bit of variation of a traditional prefix tree here and here we basically we uh we use a trick you know to handle this prefix and suffix right by concatenating uh the word twice and then we just add multiple words into the prefix tree to cover all the combinations of the prefix and suffix cool i think i'll stop here and thank you for watching this video guys stay tuned i'll see you guys soon bye
Prefix and Suffix Search
find-smallest-letter-greater-than-target
Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the `WordFilter` class: * `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary. * `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`. **Example 1:** **Input** \[ "WordFilter ", "f "\] \[\[\[ "apple "\]\], \[ "a ", "e "\]\] **Output** \[null, 0\] **Explanation** WordFilter wordFilter = new WordFilter(\[ "apple "\]); wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ". **Constraints:** * `1 <= words.length <= 104` * `1 <= words[i].length <= 7` * `1 <= pref.length, suff.length <= 7` * `words[i]`, `pref` and `suff` consist of lowercase English letters only. * At most `104` calls will be made to the function `f`.
Try to find whether each of 26 next letters are in the given string array.
Array,Binary Search
Easy
2269
1,835
hello everyone let's take a look at this problem find xor sum of all pure speed wise n okay so it's the last question in the weekly context although it's the last question uh it's not that hard this is a problem so um like if you haven't read this problem you can take some time to create it basically unfortunately implementation we can just uh we have a double for loop and double fold will construct a new array so we just get the xor of the element in this new array it's very naive and we know that time complexity can be pretty huge and it's a lan array one multiplier length or two and the length under one and the letter two can be ten to five so multiply them it can be ten two is ten so it will tear e so we should optimize it and is there a way to optimize c two like oh like len everyone plus line array 2 and let's think about single elements assuming we have array a 1 2 a n and we have an element v like how can we get the result of this formula assuming this is a bit representation like this is 32 bit of v and i omits the first 30 bits and we want to get the results okay let's just consider one single bit assuming this force is bit the value is zero in v and we know zero and any value is zero so v and a one is zero for this bit same for other like v n so it's all serial so the xor will be zero so if v is zero in this bit since a bit in result is also zero okay what if it's one if v is one then we know v and a one for this bit the value is determined by a1 okay so assuming um like the bit in a1 is once a bit in a2 is one then one excel one it becomes zero so we need to know like the total number of ones in this bit like from a1 to a n so if the number of bits in this position is an odd number then it's one if it's even number then this will be zero okay so uh it's first if we have all the um like bits information like forces away then it just take us like a one to get the answer actually it's all 32. so first we just for loop array 2 to get bits information for these bits then we know that in this position how many ones there okay when we have this basic information that we can get this result very easily this is our result finally we just return this result then we just follow every element in every one and for each element like i will get this result but we can get results in almost a one the temp is this result so my final resource just excel this temp okay then we just follow the 32 bits if the bit is one here in v then we just check the total bits if the total bits is like odd number then we know it will be one then we contribute this one to choose the correct bit position in this temp okay set it and the time complexity is overland everyone plus net array two you can also multiply 32 here i say almo but in all annotations same right okay that's it see you next time
Find XOR Sum of All Pairs Bitwise AND
decode-xored-permutation
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers. Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`. Return _the **XOR sum** of the aforementioned list_. **Example 1:** **Input:** arr1 = \[1,2,3\], arr2 = \[6,5\] **Output:** 0 **Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\]. The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0. **Example 2:** **Input:** arr1 = \[12\], arr2 = \[4\] **Output:** 4 **Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4. **Constraints:** * `1 <= arr1.length, arr2.length <= 105` * `0 <= arr1[i], arr2[j] <= 109`
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
Array,Bit Manipulation
Medium
null
1,425
Hello everyone welcome to my channel Quote Story with Mike So today we are going to do video number 71 of our Dynamic Programming playlist. Okay and please make sure that you also follow my DP Concept and Questions playlist if you want to learn from core to basic. If you want to understand DP, then it is okay, the things studied in this playlist or in the future are useful to you, like it will be useful in today's question also, okay, but it is not that if you have not seen it, then you will not understand, you will understand it from the core. We will build the solution. It is ok. Lead code number is 1425 hard marked but actually it is very easy. I will build the solution and show you the thought process. It will be based on already studied concept. It will be ok and very easy to build up. Solution is ok, so question. Its name is Constrained Subsequent Sum. First of all, do not get scared after reading the name of the question. Are you okay? Is this a variant of AIS? This will be seen later. How to start the thought process, I will tell you this when you do not understand the question at all. How to be mindful, today's one is going to be one of the most informative videos. Okay, Gal and Hyper Vaz asked this question, look at this question, what is the question trying to say that I have given you one integer and one integer. Ok, return the maximum sum of non-MT subsequences. Ok, return the of non-MT subsequences. Ok, return the of non-MT subsequences. Ok, return the maximum sum of non-MT subsequences. You have to send of that are maximum sum of non-MT subsequences. You have to send of that are maximum sum of non-MT subsequences. You have to send of that are true that for every two concatenate integers. Your subsequence will be there, not everyone of it, two any two concatenate subsequence integers. If you pick up any number of zeros, if you pick up any two numbers, then their index will be their index, it should always be followed that minus a must be lesson etc. Okay, now it will be clear from the example, let's see, pay attention to this example. Here I do the indexing 0 1 2 3 4 So it is said that the maximum subsequence should be even, but what is the constraint that what will be the elements of the subsequence, if you pick any two consecutive elements, then j - come, i should be k, let's see. What is he - come, i should be k, let's see. What is he - come, i should be k, let's see. What is he trying to say, as if he is saying that look, the first thing that comes to my mind is that if you want to find the maximum sum, then add all the positive elements, okay, you can add 10, two, five. 20 is fine now that means what am I saying subsequence 10 two 5 20 look at the indexing of these its index is zero its index is one its index is three its index is four any two f is fine pick up another two pick this 1 My 0 is equal to that is not correct let's pick it up 4 My 3 index lesson is equal to means this is our best sub sequence okay which is also satisfying this and its sum which is right see the maximum is 37 Maybe we could have also taken the subsequence 10 two this is also a subsequence but look at its sum is just right and look at its index zero and that is also 1 minus 0 lesson ect ke also but its sum is small I have the maximum sum And now let's see, now you could have taken either 10 and 15, sorry, 10 and 20 but could you have taken this, its index is zero, its index is four, minus the indices of both, so 4 minus 0. Is this lane equal? ​​Otherwise. This is Is this lane equal? ​​Otherwise. This is Is this lane equal? ​​Otherwise. This is not my sub-sequence correct, the same not my sub-sequence correct, the same not my sub-sequence correct, the same constraint is that whatever sequence you make, the index of any two elements and their difference must be equal to two. Okay, so see, first of all, my mind gets disturbed. Seeing this condition, it is okay, then my most important question is that how to build such a question, from the very basic, what I say, friend, look, we know many topics, already we know the graph, we know the stack. Why does link list come? Many things come. Sorting also comes. Whatever you know in data structure, think once about everything. Is there any use of sorting here? What is not useful? Why is it not useful? Because the index will change, so I will sort. Leave it aside, the question of the graph does n't seem to be a question of this stack and why right now I can't say why stacker would be used or not, the question of the link doesn't seem to be a question at all. It's okay when you don't understand anything, right when you do n't understand anything. When I understood, then look, I catch some things, first of all I saw that all the sequence is written, then you will remember that sequence was always used mostly in DP, so when DP flashed in my mind, then this is my thought process that I Somehow I try to relate which topic can it shine then I thought it could be DP because I have made a lot of sub sequence questions in DP, no Longest Increasing Subsequence is ok then Common Sub Common Longest Common Subsequence AIS LCS is there Shortest Common Subsequence, there are many questions in sequence, so let's see whether we can make it DP based or not. If this question is ok, then first of all you try to understand your approach and I said that always go from basic solution to the most basic one. The solution that comes to your mind, okay, so if you pay attention to this, the most basic solution, I know what is coming in my mind, I have to choose the sub-sequence, I have to choose the sub-sequence, I have to choose the sub-sequence, I have to make all the sequences, okay, so let's assume that I am standing here right now. Okay, so till now have I taken any element before this, have I not taken it? Index - 1, the not taken it? Index - 1, the not taken it? Index - 1, the index before this is -1, so I have index before this is -1, so I have index before this is -1, so I have not taken any element before this, so I have the option to look at the sub sequence that I am going to create. In that, either I take 10 or I don't take 10. Okay, if I take 10, then look, the even is my 10. Okay, now I move ahead. Here I came to 2. Okay, now look, did I put any number before 2? Yes, I have taken 10, okay, what is its index, zero and the current element aa, its index is one, so I can take, can I take 10, yes, because look, 1 minus 0, which is the index, len ect. Okay, this means I can take this index, okay, so if I can take this, okay if I can take this, then I still have two options that brother, either I take T in 10 or I don't want to take 10 out of 10, it's okay, there was one option, when I didn't take 10, then I have two options, whether I take 2 or don't take 2, so you are seeing this. You have the option and all the sequences are being created for you, look at this, 10 do 10 created for you, look at this, 10 do two MT, all the sequences are being created and all the sequences are created like this, take an element and exclude an element, take not take simple. So, can I make it simple by applying this approach? You can definitely make this question, this is my most basic approach, so let's see how we will build the solution with such an approach. And look, here you saw the option that I take And I am not taking it, meaning definitely I am going to write recurses and making recurses tree diagram, meaning this is actually my family method of recurses and memoization. Unfortunately, you can also go and see the official solution of lead code there. Solution is not given, I don't know why should it be given, friend, it is built with the most basic approach, we will build this, then we will improve that too, the solution should be made in this way, so let's start, okay, now I will do the indexing. 0 1 2 3 4 In the beginning I will start from index zero. Right now I do n't have a subsequence, it means I have not taken any element before this, so my previous index is -1. The previous index is -1. The previous index is -1. The current index is here. Okay, so if my previous index is -1. current index is here. Okay, so if my previous index is -1. current index is here. Okay, so if my previous index is -1. Then I have to take the element, otherwise my M sequence will remain MT. Okay, so I have two options now, either I take this 10 or I don't take it. Okay, if I take this 10, then here I will add 10 plus I will add whatever value comes from recursion. Okay, so when the next step comes, what will I be left with? 10 2 - 10 5 20 index aa mine is here left with? 10 2 - 10 5 20 index aa mine is here left with? 10 2 - 10 5 20 index aa mine is here but remember my previous index was earlier mive now. Look at my previous index, what happened, this happened or this happened because I have taken it last time, okay, it is clear till now and you must be remembering that I have taught you the longest increasing sequence, in that they used to do exactly the same thing. Na, if we have not taken any element in the previous index, then we used to take some element, it is ok or if we have taken any element in the current previous index, then we used to take the current element which can make increasing sequence, same here. Let's see, previously we had not taken any element, so we took 10. The first option is to take 10. Okay, so if we take 10, then my previous index became zero and the current index came and went to one. If we agree Let's not take it. Okay, if we don't take it then what will happen. Let's see. 10 2 - 10 5 see. 10 2 - 10 5 see. 10 2 - 10 5 20 Aa mine will come here but my previous one is still -1 because I have my previous one is still -1 because I have my previous one is still -1 because I have not taken 10 so till now I have not taken any element. Not taken in this option, okay, so you expand it, if I go to expand all, it will become very big, okay, I will just expand it and show it to you, okay, now look, I am on the I index, okay, so I have two options. It's like whether I take this or not, if I take this then it's okay, I've taken it plus then whatever element comes, I'll add it, then whatever result comes, okay if I take this, then let's see what happened 10 2 - then let's see what happened 10 2 - then let's see what happened 10 2 - 10 5 20 Okay Aa equal to two has come here but you pay attention to one thing why I could take Aa here Listen well I am saying very important thing because look what is the value of I so Aa is now pointing at one. And what was the element that I previously took was zero so 1 minus 0 is lesson equal to two k yes because my k is equal to two k okay so that's why I can take this right no that's why I can take this okay so I Took this, tried this option, now what other option do I have that I should not take it, if I don't take it then see what will happen 10 2 - 10 5 20 Come here it will come happen 10 2 - 10 5 20 Come here it will come happen 10 2 - 10 5 20 Come here it will come but remember the previous index should point to zero. If it was then the previous index will point to zero only because I have not taken the eighth element here. Okay, okay, you can expand this further, for the sake of your knowledge, I am just expanding it. Okay, come here. Look here, my previous index, what has happened to me now, p has happened, why because I had previously taken this two elements, it is clear till here, now look here, now I have two options, first, I should take the I index or So no but now when can I take the i index look pay attention 0 1 means what is the current index of mine aa is no and which is the previous index I have taken looking at the first one p1 is pointing to the index so Is 2 - 1 &lt; i k definitely so Is 2 - 1 &lt; i k definitely so Is 2 - 1 &lt; i k definitely datchi aayega plus further the result which will come I will get it from Mr. Karshan ok so if I proceed here then 10 2 - 10 if I proceed here then 10 2 - 10 if I proceed here then 10 2 - 10 52 ok so aa mine has come here na and previously I just took which one, if I took 10, then my previous index must be pointing to which one, it must be pointing to this 10. Okay, now you father expand this also, for my knowledge, I will only go to that branch where I can get the answer. Otherwise the tree becomes very long. Well, if I had not taken this 10 - 1, then let's see not taken this 10 - 1, then let's see not taken this 10 - 1, then let's see what my scene would have been. 210 - 10 520 Aa here it will definitely what my scene would have been. 210 - 10 520 Aa here it will definitely what my scene would have been. 210 - 10 520 Aa here it will definitely come but look I have taken -10. Otherwise, my previous index taken -10. Otherwise, my previous index taken -10. Otherwise, my previous index was at two, it remained at two, till now it is clear, now let's see, can I take this I element or can I not take it, I have both the options, so you can see. Can I take it or not, can I really take it? Let's see what is the current index 01 23. The one that is here is pointing to the third index and the one that is my previous index is pointing to the one. So let's see 3 - 1 Is the lesson So let's see 3 - 1 Is the lesson So let's see 3 - 1 Is the lesson equal to two, yes is the key value, then we can take it, we have the option to take it is okay, if we take it, then we will add five and whatever comes from the further recurs, I will add it, okay then 10 2 - 10 5 I will add it, okay then 10 2 - 10 5 I will add it, okay then 10 2 - 10 5 20 Okay, come here, I have come here and look, previously I had taken F, then this will be my previous index, it is clear till now, it is good, you must be understanding till now, if the value If you had not taken it, then 10 2 - 10 5 20 would have come here and the then 10 2 - 10 5 20 would have come here and the then 10 2 - 10 5 20 would have come here and the previous index would have remained at p because you had not taken this element. Last time the i th element had not been taken, hence the previous index would have remained the same. So you expand this also for your knowledge, I will just expand this from where I am getting the answer. Now look here, pay attention to this I index. Let's see if I can take it. Let's see what is the index. If four is p, what is 3 then 4 - 3 &lt; equ k is yes, then 4 - 3 &lt; equ k is yes, then 4 - 3 &lt; equ k is yes, can it mean no, just what I said, this is what is given in the question, which will be your element, any two correct elements, difference lesson of its index. It should be equal to k only then just before aa which element did I take p then that is what I am looking for i- p must be lesson equal to k looking for i- p must be lesson equal to k looking for i- p must be lesson equal to k is yes then I can take this if I take this then 20 Add will happen, whatever element comes further from the recursion, I will add it. Now look ahead, when I went 10 to - Now look ahead, when I went 10 to - Now look ahead, when I went 10 to - 10 5 20, then it is out of bound. If it is out of bound, then I will return zero, okay. So what did I do from here, I reduced the return to zero, so it became 20%, ok return to zero, so it became 20%, ok return to zero, so it became 20%, ok till now it is clear, now 20%, now let's see till now it is clear, now 20%, now let's see till now it is clear, now 20%, now let's see what will come to me from here, let's see 10 2 - 10 5 20, it is out of bounds. 10 2 - 10 5 20, it is out of bounds. 10 2 - 10 5 20, it is out of bounds. Okay and my p will remain the same because last time I had not taken the eighth element, so my p will remain the same. Okay, now see what we have to do in each branch. From that branch, we get the maximum result, we get the maximum sub sum. No, it's okay, I have to withdraw the maximum sum, so I am getting 20 from this branch, B.P. 0, whatever I get from this branch, I don't B.P. 0, whatever I get from this branch, I don't B.P. 0, whatever I get from this branch, I don't care, okay, assuming I get one, then what do I have to do, I have to choose the maximum from the two. Okay, so 20 more. Whatever is the maximum in one, I will return it. Due to value, 20 is the maximum, so out of these two, 20 went here, 20 went to this one, see how much it is, it became 25, okay and something came from this branch. Let's assume that y must have got 25 here. 25 came here. Seva came here. Let's assume that the maximum from both is 25. Okay, so look from here, I got 25. I am fine. And from here, let's assume that I must have got something. Jud must have got the maximum from both. What is 25? Okay, so out of these two, I returned 25. Here we get 25 P 2 27. From here we get 27. Let's assume from the right side, something must have come h. Any variable is fine. Some value will come. Maximum of both. Who is 27? So I returned 27 here. 27 + 10 37 is ok and maybe 27 + 10 37 is ok and maybe 27 + 10 37 is ok and maybe some value might have come from this branch. Let's assume the maximum from both of them. Our answer is the same. So 37 is our answer. It is very simple. This is exactly the code of L is exactly the same code. Why is there a little modification because the previous index which I will take is I and the current index which I am looking at is i - p must be lane looking at is i - p must be lane looking at is i - p must be lane = k. We have this constraint in this. No, = k. We have this constraint in this. No, = k. We have this constraint in this. No, it should not have increasing numbers like Longest Increasing Subsequence, it does not matter, we need maximum sum, just what is the constraint, j previous current index minus previous index lesson should be equal to k, then exactly the same code as Als is pasted and exactly the code of Ala will be that's it. The constraint will be that the distance between the previous index and the current index should be equal to the lesson. So let's quickly code the recursion and memoization. Okay and let's see if you are able to pass all the test cases. So let's quickly code it. From our very first approach i.e. from the traditional our very first approach i.e. from the traditional our very first approach i.e. from the traditional approach, isn't it recursion and memoization? First of all we define end and make numbers dot size k a global variable k = k. Here we keep int k a k = k. Here we keep int k a k = k. Here we keep int k a and here int a. Let's keep one. Okay, now it's simple. What did I say? I will write a recursion. Solve and my previous index is -1 because right now I am previous index is -1 because right now I am previous index is -1 because right now I am starting from zero index. Which index am I starting from? This is zero from zero index. My index is ok and the names have to be sent. I am clear till now. Now look simple let's write our solve function and solve int prv index is ok and my current index is aa ok and what am I passing vector Of int and numbers Okay, now look pay attention, first of all I had said that if my current index i.e. a becomes greater than equal to n, index i.e. a becomes greater than equal to n, index i.e. a becomes greater than equal to n, then now there is no option, my sum will be zero, isn't there any sum? I can't take out the elements, all of them are gone. Okay, now look, pay attention. If I have n't taken any element previously, I have n't taken the element previously, that is, the previous one is mine, so yes, I will take the current element. Okay, so I have two options with the current element, that is, I will take it. If I take it, I will call off the names and tell D+ take it, I will call off the names and tell D+ take it, I will call off the names and tell D+ Further Rickers to bring it for me. So see, if I take the current element, then The previous index will be ok and the next index will be there. I have sent the names here. If I have taken this or not, it is ok. Just give it. The code of s is like almost. If I have not taken this, then simply what will happen which is my previous index. Tha and the same will remain the same, Aa Pv will definitely happen and Nums is done, okay then we will store the result in a variable named maximum of take comma not under take, we will keep a variable outside int result e 0 is okay and if not like this Look, previously I have not taken any element, so I have two options, I can take it or not, if I had previously taken any element, then the value of previous will not be human. Okay, so in else, but I have to check when I can take the current element means when will I have the option to take the current element when I minus the previous index must be let equal to two I told you this right then I have the same option and if taken then names Off i do plus solve previous index aa will become next index aa pv and you are looking at the numbers, see the code is exactly the same, if you want you can clean it even more but why did I write completely different so that I can explain the tree diagram to you. What is the meaning of no previous i mive that I had not taken the claim previously? Okay, it has been taken int no underscore take what is the meaning of this that I have not taken it. Solve the current alum. If not taken then whatever was the previous index will remain as previous only. Ok and you will do psv and names are done here also ok here also result is equal to max of result sorry tech comma not under sco tech ok and in the last what do I have to do return result is s simple A, this was the only two options I had, either I should take it or I should not take it. Okay, now look, pay attention. Now this code and this code are exactly the same. Right, you can write it like this, the previous one should be -1 or else. If a minus previous le is equal to be -1 or else. If a minus previous le is equal to be -1 or else. If a minus previous le is equal to k, then I have to do the same thing in both, then it will burst from el. It is clear as simple as that, so this is our code completed. It was a very simple code, just pay attention to one thing in it. Let me show you a small example. Let's assume that your numbers are -2. your numbers are -2. your numbers are -2. Okay, so see when you come to this if condition, what will happen in the case of take. Numbers of a means -2. Plus names of aa is the Numbers of a means -2. Plus names of aa is the Numbers of a means -2. Plus names of aa is the first element my -2 na here is only first element my -2 na here is only first element my -2 na here is only one element in it -2 plus then one element in it -2 plus then one element in it -2 plus then when you call rec the index will be out of bounds and from here it will return zero so -2 and from here it will return zero so -2 and from here it will return zero so -2 p 0 what will become -2 And in the case of not take, p 0 what will become -2 And in the case of not take, p 0 what will become -2 And in the case of not take, see what will happen, you will go ahead in the regression, the index will go out of bounds and will come to zero, you know what you will do, look at the maximum in take and not take, then which is the maximum, it is zero, you will assign zero, okay and you From here you will make the return zero but here there is no such sub sequence whose sum is zero, okay then you will have to handle this thing that if my result is only zero out of zero, what does it mean that we did not get the answer right? We did not find any such subsequence whose maximum is even. Okay, let's say look at this example, look at the second one here, pick any such subsequence, everyone's sum, anyone's sum, you will not get a good one, all will be found in negative, so what is the best solution? That is, brother, send it to the one who has the biggest number out of all these poor guys, then send it to the one who is the biggest number, my wife, then what am I saying here, if the value that comes from the solve is fine, I am here. I will store it, if that value remains only zero of my zero, then tell me what will I assign in the value, maximum element, whatever is the maximum number in this number, I will assign it because that can be the best answer, it is okay for me if not. If this happens, we will return 12. Okay, see, when will the result value become zero of zero, when we have not found any subsequence whose sum is greater than zero, then it is okay, only then the result will remain zero of zero, neither is it zero. What does it mean to be zero ? The sum of the subsequence that ? The sum of the subsequence that ? The sum of the subsequence that we have calculated is zero, that means the subsequence is empty, I am okay, so what will happen in that case, whatever is the maximum element, I will take it, like this is a test case, okay, submit it. Let's try and see the test cases, all will pass but this time limit will be exceeded because I have not even memorized it. Look, the time limit has been exceeded. Why is this exposé important because on each index page I have two options, worst. In this case, it is okay, in each index, I will have two options, in the worst case, then the time completion is one doti 4 pa, then power 5 of 10, that is, the value of the previous can also be this much and both are indexes, neither can be this much max value. But it is so big that if you can't even define it will give you limited memory here, that will be a mess, so whenever I am unable to memoize, I take an unordered map and convert both of them into strings. I mean, what I'm saying is that I create a map of unordered string versus int and look here, which is previous and which is prev and i, I will make a key of the string key ect under string previous plustwo underscore string i Okay. If in my map m pad find key is not equal to m pad and means I have added the previous and corresponding time limit of this i, the time limit will be exceeded. The spelling of the string is wrong here. Let us see whether we are able to reduce the time by memoization or not. Are you able to get it accepted or not? Look at all the test cases. My time limit seed is also there in this one. What does it mean that it is searching for a better solution? It is okay with me, so now let's see whether if we build it from the bottom up then it will solve it. Otherwise, remember, this is exactly the same code as the LS one. Right, the bottom up will also be exactly like the LS one, so let's see the bottom up. Look, this is my bottom up approach. Now I am showing the approach to this. And the time complexity of the equation that I had solved using the tree diagram would be Y in the worst case because I have two possibilities on each index. Now look, let's see from the bottom up whether we can solve it, otherwise you will remember that the bottom In Up we always first define the state. Right then we define the state t of i. What will happen y? I write state definition state t aa what will happen maximum sub sum till index i how much is the maximum sequence sub sequence sum. And mine will be stored in TE, okay, similarly, this was the case in others also, maximum, sorry, longest increasing sequence till index, here I have to find the maximum subsequence, okay, then remember the value of all in the beginning, if I take only one element, then maximum. What will be the sum a tail index row? It will be 10 and suppose I have taken only two sub sequences, then my answer will be two till one. Okay, so to make it easy in the beginning, whatever my t will be, I will keep the value of all the same, like this is my t. To make it easier in the beginning, I will keep all the values ​​the same. 10 2 - 1 5 20. will keep all the values ​​the same. 10 2 - 1 5 20. will keep all the values ​​the same. 10 2 - 1 5 20. Okay, 0 1 2 3 4 because all this in itself is a sub sequence. 10 2 is a sub sequence in itself, so obviously C. The thing is, what will we do in the verse case, remember when I had this example - 1 -2 -3, when I had this example - 1 -2 -3, when I had this example - 1 -2 -3, then what did we do in that, we used to select the maximum element and send it, okay, so maximum means this is my. -1 okay, so maximum means this is my. -1 okay, so maximum means this is my. -1 can also be selected alone, so see what I did in T, I removed the number as it is 10 2 because they can also make a sub sequence by themselves 10 2 and so on, okay so till here So it is clear, now in the code with longest increasing sequence, remember what we used to do, I is here, okay, let us assume that I is here and J used to start from here. Is 10 which is smaller than five, yes if it is smaller then it is the longest? So this increasing sequence is not being formed. Okay, let's see if 2 is less than Of a means t of j, what will this give, the largest l aa ending at jth index, okay, we will do + 1 on that, jth index, okay, we will do + 1 on that, jth index, okay, we will do + 1 on that, okay, so what will be the value of already t or the value we got now at tji t + 1, got now at tji t + 1, got now at tji t + 1, whichever is the maximum. We used to store the value of t in the same way. You will remember that in others we used to solve it in the same way. Okay, but what do we have to find here? If we have to find the sum, then we will do it exactly the same way, but pay attention to one thing here, let us assume that this is 10. This is the index h, okay now, but look, this is the index h and this is 3, so 3 - 0, is this is the index h and this is 3, so 3 - 0, is this is the index h and this is 3, so 3 - 0, is this lesson equal to k, the value of k is given as two, no, it is not so why would I take this h, okay? So, let's do one thing, let's start j from here with i - 1. start j from here with i - 1. start j from here with i - 1. Okay, now see if j - i &lt; = k, yes, then I Okay, now see if j - i &lt; = k, yes, then I Okay, now see if j - i &lt; = k, yes, then I can try this too. Okay, then when j comes here, what will j - i &lt; i is k, yes, I when j comes here, what will j - i &lt; i is k, yes, I when j comes here, what will j - i &lt; i is k, yes, I can try to kill this also j When it comes here j - i &lt; i is k then it is obvious that comes here j - i &lt; i is k then it is obvious that comes here j - i &lt; i is k then it is obvious that j - le = k is not there then j - le = k is not there then j - le = k is not there then I will not go after this here and this also right because my If I want to take a subsequence, then the element I will take should be j - i &lt;= k. then the element I will take should be j - i &lt;= k. then the element I will take should be j - i &lt;= k. Right, let's take that approach and move ahead. Look, it is an obvious thing, index i starts from here, so where does j start? It will happen that if j starts from 'a' then start? It will happen that if j starts from 'a' then start? It will happen that if j starts from 'a' then it is not valid. If 'a' is out of bounds it is not valid. If 'a' is out of bounds it is not valid. If 'a' is out of bounds then it is obvious that 'a' will start from 'one'. then it is obvious that 'a' will start from 'one'. then it is obvious that 'a' will start from 'one'. Okay then where will 'ja' start Okay then where will 'ja' start Okay then where will 'ja' start from i-1. So first let's see that. from i-1. So first let's see that. What is the largest subsequence sum ending at What should I do? t of aa will be equal to the maximum of t of aa which would have been there before or the current element i.e. numbers of i plus current element i.e. numbers of i plus current element i.e. numbers of i plus t of j. I will add the maximum of both, ok but why should I add it? Found because look i - j why should I add it? Found because look i - j why should I add it? Found because look i - j is of lane equation. Okay, so we have to keep this condition. Okay, so this is the maximum I got. So look here, already the value of aa was two, but the number of aa means two plus t off. The largest sub-section ending at j was 10, two 10 12, largest sub-section ending at j was 10, two 10 12, largest sub-section ending at j was 10, two 10 12, what is the maximum of the two, it is 12, so by removing two, I made 12, okay here j, I can't go back further, so this for loop is my end now. Aa came forward, okay, then it will start from J, okay, so again we will see the same, first check that J is my aa le ek, yes, okay, again see the same, off aa already, what is the value of aa -1. Or let's add the sub sequence with -1. Let's -1. Or let's add the sub sequence with -1. Let's -1. Or let's add the sub sequence with -1. Let's see what is the sum of the largest sub sequence ending at 0. It is 12. Okay, so 12 becomes 12. Here Nam Sai Mive and this is 12. So 12 has become 11. Yes, it is like that, I have got a big value, right, I have got an 11 here. Okay, and if you assume that I had not taken it, then let's hit try here. I mean, what I am saying is that human So before this, I want to take only 10 or whatever sub sequence before 10 will be a part of it, 10 is okay, ending at 10, I want to have some sub sequence like this, I am okay, ending at 10. What is the largest subsequence? 10 means index number zero i.e. index number zero i.e. index number zero i.e. look at the value of the largest subsequence at index number j, it is 10, here tj is my 10, okay and currently my i value is minus, okay so -1 p. 10, how much is it, okay so -1 p. 10, how much is it, okay so -1 p. 10, how much is it, and the current value of t is 11, now it is a good value, it is not small, so I will not update, okay, so I am mine, my t is 11 out of 11, now I cannot go back, it is over. J's for loop is done, now let's move ahead. Okay, so now let's move ahead here, so we will give everyone a chance one by one. First, let's assume that whatever sub-sequence that ends here is First, let's assume that whatever sub-sequence that ends here is in index number two, can I add five to it? Let's see what is the biggest subsequence ending at 'h'. Look, what is the biggest subsequence ending at 'h'. Look, what is the biggest subsequence ending at 'h'. Look, if I add five to it, 11, then 11 5 16 will come, then I will get a good answer. I have written 16. Now I am saying that if here 'end' here 'end' here 'end' What was the largest subsequence to occur, look, it is 12 and if I 12 is 12 then why is it 12 because the largest sequence to occur here was the subsequence 10 two whose sum was 12, if five is added to it then how much will it become, it will be 17. Which is the bigger value, currently, so I removed 16 and made it 17. Okay, now let's give a chance to this 'h'. Okay, what is the now let's give a chance to this 'h'. Okay, what is the now let's give a chance to this 'h'. Okay, what is the biggest subsequence ending on this 'h'? Let's biggest subsequence ending on this 'h'? Let's biggest subsequence ending on this 'h'? Let's see the value of 10, why is it 10 because here it is The sub sequence is 10, okay, so if we add this five to that 10, we will get 10 5 15, then my sub sequence will be 10 and five, but 17 is already a very big value, I have it, okay, so I will not date you, now out of Bounded, okay, great, now it will go further, okay, so in which subsequence should I add this 20, in the subsequence ending here or here, we are checking the same thing every time at the end. What was the sum of the largest sub sequence that could happen? It was 17. Add 20 to 17, meaning if you add this element, you will get 37. So, if you got a good answer, then I cut off 20 and made it 37. Okay, now let's remove J here. This largest sub sequence was 11 p 20 how much will it become 31 which is smaller than 37 this here this largest sub sequence 12 and 10 12 and 20 32 is 32 which is smaller than 37 so will not update then h when here But here, the largest subsequence of Aa is 10, okay, 10 plus the numbers of Aa, that is, 20 will be 30, which is smaller than 37, the largest value is 37, after that my Aa will be out of bounds. Okay, so I will be out of bounds. Once the bound is reached, now I just have to see that brother, in which index the largest sequence sum was found. At index number four, the answer is 37, that is mine, that is, I will keep taking out the max element from it, in the last 37, my answer will come out till here. If it is clear, then see its code will be exactly the same as A, we used to do the same thing in A, first of all we defined t, put all the elements in it, like 10 2 -1, we like 10 2 -1, we like 10 2 -1, we put all the elements in t like that. After that the for loop is very simple, remember we started from i = 0 for loop is very simple, remember we started from i = 0 for loop is very simple, remember we started from i = 0 i &lt; n i + + ok but i &lt; n i + + ok but i &lt; n i + + ok but we observed that we cannot start i from 0 because j which is -1 i because j which is -1 i because j which is -1 i - 1. It will start, okay, so you - 1. It will start, okay, so you - 1. It will start, okay, so you start i from one, okay, now remember I told you that j which is i - will start from 1, told you that j which is i - will start from 1, told you that j which is i - will start from 1, how long will j go till &gt; = 0, how long will j go till &gt; = 0, how long will j go till &gt; = 0, one more thing should happen that j - sorry a one more thing should happen that j - sorry a one more thing should happen that j - sorry a i - j &lt; = k should be right and here j my i - j &lt; = k should be right and here j my i - j &lt; = k should be right and here j my minus is clear till now it is very simple so t i what did I say sorry t of i has to be found out is not equal to maximum of aa or current element names Off i has been added, the largest sub square sum ending at zth index is ok i.e. largest sub square sum ending at zth index is ok i.e. largest sub square sum ending at zth index is ok i.e. whichever is maximum among the two T of j will be assigned to vote of a ok and lastly we also update here. We will take a variable named result, okay result is equal to max maximum of result, comma t is coming off because in the end I have to extract the maximum element, whatever is found and remember it is not necessary that your last index is the maximum. The value will be OK, the maximum value in LS has to be chosen because the maximum subsequence at any index can have an end, not necessarily an end, OK, look at any example, you will also get such examples where But it is possible that if we assume that there were -5 and -20 here, then it is obvious that were -5 and -20 here, then it is obvious that were -5 and -20 here, then it is obvious that here a very small value would come here and there, it is okay and our big value would be somewhere behind in the index, it is okay, that is why I am taking out the maximum element. And in the last what I will do is I will return the result. Okay, as simple as that, look at the bottom up, we have done it here also, look at o of n * n is approximately o of n, this is the n * n is approximately o of n, this is the n * n is approximately o of n, this is the solution, so let's see if this is also acceptable. Will be able to submit quickly and let's see. So let's solve it from the bottom up. First of all, let's take n, the size of numbers, and let's take a deep array of my t. We have taken the vector of t and take n = numbers size. And look, and take n = numbers size. And look, and take n = numbers size. And look, in the beginning, I don't know what to do, i = 0 i &lt; n i+ what to do, i = 0 i &lt; n i+ what to do, i = 0 i &lt; n i+ P, then the largest subsequence ending at each index, I assume only the numbers of i, so now I have stored the same. Given t is ok in i and int max either take the result i is equal to two numbers of zero take it ok for now either take t of 0 the thing is the same whatever you have to take it for now and then Now we will find the max element int aa = 1 aa i lesson a aa will find the max element int aa = 1 aa i lesson a aa will find the max element int aa = 1 aa i lesson a aa pps then for int j = aa -1 pps then for int j = aa -1 pps then for int j = aa -1 j lesson sorry greater than must be equal to 0 end i - j must be &lt;= k end i - j must be &lt;= k end i - j must be &lt;= k remember then A j minus will definitely happen, okay, pay attention here, this thing has been understood, i started from i - 1 started from i - 1 started from i - 1 and are moving left side, so see, we are doing j - and are moving left side, so see, we are doing j - and are moving left side, so see, we are doing j - minus, okay and j is greater than zero. And i - j should always be le = k. And i - j should always be le = k. And i - j should always be le = k. Okay, so t i will be equal to the maximum of t i's already value or what I have added to the current element i at a t of j page j and all that is going to happen. I have added the sequence sum, okay, so if it is maximum, okay, maximum of result, comma t off i, then it will be updated in the result, okay, so in the last we have to return result, okay, after submitting, let's see the example test cases directly. So you will pass, if you have to give only teal, then he will give it. Look, even n square will not pass because look at the constraint, the power of 10 is 5, so if you square 5 to the power of 10, then the power of 10 becomes 10, which is a very big constant. Time is limited, which was bound to come, now let's see friend, now even the bottom up is not acceptable, so how to optimize it, then look, now the problem has arisen, now even the bottom up is not working for me. Remember the time complex of bottom up was off a in a i.e. n was square, so if a is in a i.e. n was square, so if a is in a i.e. n was square, so if a is not formed even from sk then it would definitely want you to either solve it in n log n or show it in o off n. If you solve it and show that if n is not possible then how will you be able to find the sum of all the sequences in a linear i.e. one traversal, the how will you be able to find the sum of all the sequences in a linear i.e. one traversal, the sum of the best sub sequences will have to be found somewhere in logarithmic form, so I am guessing that If off n is not made of s, then what can be the solution, but if you pay attention, why did off n s happen? You are looking for the hypothesis. Our bottom up approach was if you look carefully at the code I had written here, this is mine. There was a rectangle loop and inside it you are looking for the for loop. What is the problem? See, the I loop is off A, it will run A times, but pay attention to this, it repeatedly went back from I and repeatedly took out the maximum and its The only thing used to be done was to see if the guy with maximum could give an even bigger answer by joining Nam Sai or not, that's fine, he just used to find out the maximum and sum, right from where J = Aa - 1 to I used to from where J = Aa - 1 to I used to from where J = Aa - 1 to I used to find the biggest tj till 0 and after adding it to Nam Sai, I used to check whether a better answer can be found, otherwise if I look at the calculations, then due to this, one more off A was added, that's why n Okay, so I am writing that code again. Look here, I have written it again. This was the example. My k = 2 and This was the example. My k = 2 and This was the example. My k = 2 and I have written the same code again. Remember, this is my code. How to do it well, see it. If yes, then remember what was its function, I am writing here, its function was that it used to go from minus one to zero and when shown, it did not even go up to zero, it used to go till the maximum. Minus j g lesson should be equal to k, this was its job to go there and whenever it went here, it used to look in such a big window, it used to go from i -1 till the go from i -1 till the go from i -1 till the difference of lane equal to k. And in this it used to find the maximum TI, okay the maximum that can be combined with the TE, sorry numbers I, can give a good TI, so here it is, so why don't I store this thing in a data structure somewhere. But let's assume that I don't know what is the data structure, I have stored it there, okay, so what do I have to store here, see, it's like this, look at me here, I have to extract only the sum, right, going back to the constraint, subsequent sum, what did I extract? Look, I used to extract the sum and where was the sum stored in TJ, so I am saying that why should I not store those sums in the data structure, okay and since I wanted the maximum, then I should take such a data structure which Give me maximum na o of one, that means give it very fast, then you remember max heap can do this work for me. Okay, so in max heap I will store the old TJ but there I will also store which index. This sum was t j i j also have to be stored. Let me assume j = stored. Let me assume j = stored. Let me assume j = 2 but my sum was 15 so I will store 15 two. Okay meaning what am I storing here I am storing t j kma j now. Look, what will be the benefit, first of all, I am on the eve, okay, so I will come, what is the priority, first of all, I will see the element which is at the top, okay, which one is it, then first of all I will see its index, brother, what is the index? I will check whether i minus h is less than equal to or not, only then I will take it, if it is not then I will remove it, I will look at some other element which I might have stored there, ok, look at its index. I will assume here that this is the oldest, so come on, if the lesson is this, then it is okay and this is at the top of the max heap, then obviously the highest value will be the same, right? There is no need because there is a max heap, okay, so what am I saying, I remove the entire code, this code and replace it with max heap, the same thing, okay, so look, I am removing this completely. Now I will show the complete dry run with Max Hip, after that I will do the code. Watch the video, even if it gets long, there is a lot to learn in it because in this we also saw a recurse memo. Bottom up also showed and how AIS is derived from the code. Did the recurs memo and the bottom up and now we are going to read how to optimize it, then let's understand from a dry run, so see what I said that I am taking the max hip, okay and in the bottom up, I remember It was said here that what will I store in the map, t plus j means even and index also, we have made t in the bottom up. If you remember, then I have also made t and kept it in the beginning. In the beginning, everyone's value was kept the same. 5 and 20, this is the maximum in the beginning, it is fine for each index, now let's see, let's start, see, this is an obvious thing, I know that the index number ending at zero till index number row is the maximum. Big Constraint Sorry Constraint Subsequent Sum What will be 10 so I put in the map that brother 10 is the sum till where is the zero index till this is what I said na t j means sum maximum sub sequence sum ants j which is the index till j till then and first Okay, now remember in the bottom up, I told you that we did not start with index equal to always. Okay, so come from here, I started. Okay, now look at what we used to do in the bottom up. J-1. They used to start from the beginning and then J-1. They used to start from the beginning and then J-1. They used to start from the beginning and then go back and forth, they will not do this time, first I will simply see which element is at the top of the max heap, this is the current one, what is my index number one, which index is at the top of the max heap. Right, that is, let's say its name is Pk, then what is the p of the top, what is the pair, then look at the second element of the pair, that is the index of my dot second. Okay, so what is the index of my top, so what is the row of the top? Is 1 - 0 &lt;= k my top, so what is the row of the top? Is 1 - 0 &lt;= k my top, so what is the row of the top? Is 1 - 0 &lt;= k yes so I can take this and since this priority is on top of q then this will be maximum I don't need to go back further j Okay so already what is the value of t of aa is two And now what will I get, look at the top of numbers of i 2 plus priority a, 10 is 2 + 10 12, so it is obvious that look at the top of numbers of i 2 plus priority a, 10 is 2 + 10 12, so it is obvious that look at the top of numbers of i 2 plus priority a, 10 is 2 + 10 12, so it is obvious that t of a is greater than a, so by cutting it by two, I made it 12 here, okay, it is clear till now. And I will also keep updating the maximum result. In the beginning of the result, my first element was started with the value of 10, now I got 12, so I cut it to 12, till now it is clear, after this, see that the sum that I got now is 12. The sum came out and the index came out at number one, I have to put it in the priority list because I have to store the past results, okay and I want quick access, so I put here that my sum was just 12, isn't it and which one? Came on the index, came on the index number one, okay and since this is the maximum element, then priority will be on the top because Okay, now let's see, now it came here, okay, so first of all, let's see that which is on the top of the priority. Index is i.e. what is that is which is on the top of the priority. Index is i.e. what is that is which is on the top of the priority. Index is i.e. what is that is one and currently I am on i2 so 2 - one and currently I am on i2 so 2 - one and currently I am on i2 so 2 - 1 &lt; = k yes so I can take the top element 1 &lt; = k yes so I can take the top element 1 &lt; = k yes so I can take the top element ok if I take the top element then what is currently my element is -1 If you look at the plus top element, it is -1 If you look at the plus top element, it is -1 If you look at the plus top element, it is 12, the sum is 12 11, and if you look at the sum at the current t, it is -1, then if you got a better answer, then I is -1, then if you got a better answer, then I is -1, then if you got a better answer, then I stored 11, okay, and when I stored 11, I have to put here that the sum is There was 11 and which index was the index number two but since this is max seep then it will be rearranged 12 one will come up and 11 two will come down 12 one came here it is clear till here it is good and I will keep updating the result So butt result now is 12 so the turn maximum will be 12 ok now come i next came three but now let's see on the top of the stack is the index number one on the top of the stack see no so this is one and currently i = If there is 3 then 3 - 1 is f is i = If there is 3 then 3 - 1 is f is i = If there is 3 then 3 - 1 is f is fine we can take this okay so the current element is f plus we have to add it to the sub sequence which was the maximum so see this is 12 right at the top I got 12 so 12 times 17 Gaya which is bigger than off aa here is already five so I made it 17 here okay now look I will update the result I updated it with 17 okay and since is the biggest value so here on the top of the stack is 17 Wrote down that index number three is 17. Okay, now come look here, index number four is okay and look at the top of the stack, which index is it? At the top of the stack is 3, so what? 4 - 3 &lt; = k. Yes. So, 4 - 3 &lt; = k. Yes. So, 4 - 3 &lt; = k. Yes. So, I can take this top element, see, if I could not take it, I would pop it, okay, if I could not take it, then I would pop this also, so you have to keep in mind that I can take only those elements which are at the bottom of my window. Come inside means j i - j &lt; = k should be ok so means j i - j &lt; = k should be ok so means j i - j &lt; = k should be ok so I will keep popping until I find that element. Here I have found the first element on the top which is 4 - 3 &lt; found the first element on the top which is 4 - 3 &lt; found the first element on the top which is 4 - 3 &lt; = 1 so I can take this. So if = 1 so I can take this. So if = 1 so I can take this. So if I take this then the current element is 20 + 17 how much is 37 which is a very 20 + 17 how much is 37 which is a very 20 + 17 how much is 37 which is a very good answer see already here it was 20 so the better answer is 37 I updated the result itself 37 is fine and here But I put 37 at index number four, okay, now the index is out of bounds, so I stopped my for loop right here, okay and my answer is already stored in the result, okay and if you have seen me carefully, all You must remember the videos, you know where I actually taught you this is nothing but actually this is the question of sliding window maximum, this is the exact code. If you watch my video of sliding window maximum, I have told the same thing there. Maximum heap has been used here, right? If you want, here I can also use this monotonic d. What to do with monotonic d? It is okay to always maintain it in decreasing order. Here, I have taken priority in that already decreasing order. You can also take d, so I taught you about sliding window maximum, there I taught you monotonic d, and this is actually the same thing, so if you see my code of sliding window maximum. I have also mentioned there that this one is exactly the code of the sliding window maximum. Okay, so remember that the index of Culprits p cud top is in second and the current index is i minus and the index lesson is equal to two. Ok then it's fine but if it becomes greater day then what I said pop the pk pop the top element it is of no use to me but the pk should not become MT so I will check not off Pkd mt only then you can do this, okay after this it was very simple, I had said that t will be equal to maximum of already which is present t and remember what earlier we used to do numbers of aa plus tj and t J used to be obtained with great effort, had to traverse back, this time TJ, there is no need to work hard, simply clicked top dot first element, this will be fine for you and your result will be equal to maximum of result committee of aa this is the same line. What I had written there is that I will return the result in the last as a simple at, so look here, A is taken off A and look here, I am keeping the maximum size, priority K, maximum size, so Pcdot Pop, what I am doing is The operation of log off is fine and here what I am doing is 'puck push', I have to and here what I am doing is 'puck push', I have to and here what I am doing is 'puck push', I have to push in priority 'K' also, right push in priority 'K' also, right push in priority 'K' also, right here 'Priority k dot push', what all do we here 'Priority k dot push', what all do we here 'Priority k dot push', what all do we put 't i comma Ix i', if we are doing this then put 't i comma Ix i', if we are doing this then put 't i comma Ix i', if we are doing this then this Also log off k operation will be k what is the maximum size of the priority q so now look at my time complexity what has become n * l of k as simple as that is ok so let's become n * l of k as simple as that is ok so let's become n * l of k as simple as that is ok so let's quickly finish it and code it then see the same below. I will convert only this approach into my priority one approach. Okay, so everything should be the same, only these culprits are going to be heaped, so let's turn off the priority one. What is the meaning of pair of int comma int? Let me give here pair of int comma int okay s simple as that so this became my max heap and in the beginning itself I had pushed p kdot the first element off 0 and till zero index because I am from y index number one. I am starting, okay, now see, the extra for loop that was here, I removed it, simple not off, p'd mt, ok, end and p'd top, second, ok, if this happens in the lesson of mine, then say it like this. Minus this is the index, if it becomes greater than that, okay, then what I will do is pop the dot. Okay, now don't take this to mean that there is another while loop inside the for. Do n't look at it like this. See how many times you push any element in priority and pop it, then pay attention here. You will push each element in priority only once and pop it only once, not multiple times, okay. So your quadratic time complex will not be here. Okay, now let's see here off a will be equal to maximum of t off a comma names of a plus p cud top dot first s simple at p cud pushed off a here. And on which index was it? It's ok and keep updating the result. Maximum of Result Comma T of I is ok. Till now it is clear. Let's submit it once and see. Let's see indeed yes. Look, we have passed all the test cases. Any doubt raise in the comment section I will try to help out see you in the next video thank you
Constrained Subsequence Sum
weather-type-in-each-country
Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied. A _subsequence_ of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. **Example 1:** **Input:** nums = \[10,2,-10,5,20\], k = 2 **Output:** 37 **Explanation:** The subsequence is \[10, 2, 5, 20\]. **Example 2:** **Input:** nums = \[-1,-2,-3\], k = 1 **Output:** -1 **Explanation:** The subsequence must be non-empty, so we choose the largest number. **Example 3:** **Input:** nums = \[10,-2,-10,-5,20\], k = 2 **Output:** 23 **Explanation:** The subsequence is \[10, -2, -5, 20\]. **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Database
Easy
null
52
here's me 52 and Queens to the N Queens puzzle is the problem of placing and Queens on it and by and chess boys I've done no two queens attack each other coming in that your end we turned a number of distinct solutions to the end Queen puzzle oh there's huh this is one of those things where you do backpacking and or backtracking and then you end up just returning in there way too full for quicker submissions timers I'm like that Wow 10 a day good luck but yeah I think can someone cheat a little bit for me and tell me what the maximum and this quest you know beyond a certain and I mean okay if in fact tracking is enough that's fine cuz my I guess my question is because I don't tell you what the N is because I'm just like well event is like 20 you know you're not gonna do it fair enough it was up to Josh no I solved it got it pretty quick I mean I did you find your garden and we have to I think about it but yeah okay so yeah I mean if fact tracking I mean I uh when I first see it identifies backtracking I think the only thing died you know question is whether you know one in time depending on n that's not your prize to need some you know some optimizations but uh I've been zero actually like I think we literally just got nothing I don't remember cuz I think it was because if we did it in Java and Java is really fast on mid code oh yeah what poem was it again what which one did we just - I forget what it which one did we just - I forget what it which one did we just - I forget what it was call actually sort colors it's loading yeah so yeah touch my can yeah cool yeah that's a disgust it's not a when chopper I don't know job was just really fast Miko for whatever reasons I don't know what to make of it you take that as you will I don't think it's meant you know like if you're doing Python I'd be much snow yeah alright let's do this just to this back tracking 152 and Queens to Dan Queens Plaza is upon voicing and queens and Emma and chance for such a no Queens at a kitchen go ninja and returned in them with distinct solutions to end Queens Plaza okay so I mean I think this is just backtracking as I said I think the only thing that I'm worried about its kind of because they would tell you to n if n is too big then you know you're like mop it is what it is and I think there are I think one thing that I'm trying to think about is do a easy way to take a friend each of which McCoy like mirrored much more core it like me report so that you could half the time just from dad because you know but maybe that's an optimization I can make later and I just start of something beginning yeah so let's go with okay so that's so first we should set this up how do we want to start to some well let's represent the Queens so let's just say columns as you go to max N and let's just say max n is probably gonna be less then we just say 20 because if it's more than 20 then maybe gets improbable anyway yeah so you have to use to what you record I forget what the equivalent cost seven more is this fancy name but yeah I don't know if I can off my head and then so those are the columns which identify then we're just keep track of reduced so these are actually the columns that the row I physically used and then just use so that we could can look it up in constant time and then also what I just say this is used columns and also used diagnose do I want to do I need both diagonals I guess huh yeah okay fine one because I'm not creative - oh so I'm one because I'm not creative - oh so I'm one because I'm not creative - oh so I'm your my C background I'm still used in some stuff for Ian's but I should use JavaScript oh yeah now we're just so let's just clear some stuff up I wouldn't see your C++ now I am in C++ wouldn't see your C++ now I am in C++ wouldn't see your C++ now I am in C++ groups and you see I'm doing mostly in C anyway for this one it seems like so yeah it's a lot of typing right now you could also replace these with for loops if you like to make it you know actually not destroy your computer if you have the title because I think someone said them said considered harmful and you use them and said yeah usually I mean there's some stuff with some interaction if you do things crazily like notably if you use like standard in from two different methods or ways then it will be a little sad but yeah let's just can't keep track of counts factorial I guess I won't go that I owe a factor is contact big I don't know what an overflow in I guess we're over folds and then we overlay don't too much map so that's just keeping it mint and then we just know yeah I guess I have to keep track and here yeah I got destroyed by this once and you don't need code because I know okay so this is the convo that's late we got then oh hey thanks for follow Bonnie about their bubble no Italy hope that's a good connotation right okay so this is now we just call it two diagonals or the columns and it is and if the column is not used and let's do it that's considerate well but not just quite yet what we also want to consider is the diagonal is a diagnosed I always forget how I do them papers so one of the diagonals is I guess very consistent it's okay where is the diagonal just one giving this eye a row and I well that's just what kind of readability let's change this to come so just absolute value of course cool this is it actually doesn't need absolute value but also because of this technically we actually want to diagnose course for an n-by-n want to diagnose course for an n-by-n want to diagnose course for an n-by-n border to two x and minus one diagonals or something right okay yeah okay and the other diagonal which is technically wrong time to carve but then and we actually don't even one after like I don't know I was considering it what we actually want is well just this in theory but I'll give you negative numbers which in some language maybe that's okay but in here we actually want to offset it by say max then let me get the negative thing probably hopefully if not then we're I'm off by one but that's the case then that said Jesus is used and what else well the important part which is the recursion yeah and also in this is just drag recursion so we need to unset stuff afterwards and also we need to actually remembered I guess we don't technically need to remember but maybe for debugging they'll be helpful so that's not don't know dad yeah you just have to know Donna we don't clean things up yeah fine maybe we should what's over today then the show is zero which we you know overload the meaning so something to consider okay fine adjust to just not I want to we have some yeah and now because we're using Cabo Wabo instead of being responsible counts in you want to be friends you could do pre income and I'm okay maybe that's okay let's take a quick look maybe have some typos I always forget that uh so this is kind of a bad habit in a sense that I come from a time where there were no void functions in C so and nowadays it's actually a warning and I have to forget remember data I have to it's not a common problem I assure you but for me anyway I yeah that's I still bite in functions and then I have to change them to avoid because now the compiler actually come points so which is not a problem that most people have but I keep on doing it okay what is the answer pretend anyway no only sound 24 I didn't realize it was that small so maybe it could be bigger let's take a quick look because otherwise my and maybe to smoke and this is why I hate that they don't give you an end but uh but okay so it just happy to see to be tried 20 so maybe it's for twenty years too small too big I mean but it is you know gives us a chance to play around of it I don't know what there are I don't know how fast is this close I mean it goes and factorial in the worst case but maybe there's some like innate he thinks wow I guess even fifteen is too slow sorry that I've been doing something weird but dagger knows so even thirties play optimistic i Shep just like I did like us to a binary search but I really test every number except for you love and I should resided there but uh okay I mean after there's I'm just go somewhere in ninety case I actually didn't look at the running time summary version it's no the running time and the judging is so slow okay so one second to take twelve and thirteen that's not so bad and actually their solution even timed out for the seven for the thirteen case so I can't imagine that you actually do it okay cool that's uh some minute then I guess I should have tested one kit alright that's testing one cases there's zero case maybe I should test to still a case but uh oh well yeah cool um what is it tailored to say about it I think some of this is look so you just put all the numbers that movies zone yeah so yeah that's a cash no cover way is also even better but you know I think I actually might have and I talk about enemy maybe that was flippin prom I don't remember I talked about it on this one I'm it might even a different well but yeah I cashing a separate strategy especially for more complicated stuff now and if you like that's say maybe I didn't have a couple of DS optimization maybe I only did columns and had to do like a for loop to check the diagonals for whatever reason because I wasn't familiar with chess or just like quits and genoise and that was too slow and I time out on 10 is equal to 11 then you're right like caching would solve it offline and then just kind of I said the best I don't know but yeah I would solve an offline and then just like you know put it in a cache and wait as a restyle so yeah that big pre calculation is especially for n is less than 15 or whatever like you could just write code to generate you know that answer really easily yeah so nice to see your poster but it's been a while but yeah what is there to say about is what I think this is one of those problems that uh and I talk about this a bit with a buddy of mine who is getting into lead code recently and I don't really have great tips on this one a backtracking obviously like you know that it's just like a little bit recursion and stuff like this so like it's very standard you need to know where and special n-queens if you like where and special n-queens if you like where and special n-queens if you like it's a standard anyone as well so you do also and like doubly recommend that you should know it but that said and I haven't I don't remember thinking about this farm in a long time so I'm actually to be honest a little happy that I got it right on the first time and that my optimizations are correct but that said because this is a good poem and I've done enough quick problems in the past it does allow me to actually I think I messed up here I should take this should return how does this not a oh I guess hmm that's interesting actually I kind of have a like I guess this could be better if I read this should return so what happens is data this actually goes for a loop and this is not true because all the cons are used so there's no way that could be true so you I could have been a factor of n times faster for some of these things anyway that's with the angular is that a boy yeah so Dogu you can also do something similarly but I think so Dogu I also recommend in general the dancing length spike neuf DLX I think it's the shorthand and just Google and we do our code is actually very fascinating I mean still backtracking and still like the same issue framework but it's ordering it in a way that is very more efficient I wonder if there's a dancing Lynx equivalent for an korean sign i mean it's not slow enough for it to matter as for N equals eight but yeah I think my experience with kind of being able to do this fast and I did this in about 15 minutes but I think I chat a bit about it right so and some of that's because I've seen recently a good amount of quit problems so definitely that's where practice comes in is that like well one like doing at the table well practice gives you know problems especially for common problems like okay well if someone asked me and Queens then I could solve it very quickly because it's exactly the same problem that you've seen but solving the same type of problems like grid problems like it allows you to food practice and learning in general just figure out the properties that a great problem would have without you having like and you have confidence to be like oh this is a good problem I knew these things and then I could you know like having implicit row usage like and just going down the road that way and like all these stuff like if you've never done it before it's gonna be a hard interview for you sadly but it is what it is because squid is so he's kind of quits don't when you come up that much I want to say but by you know chess is people like chess so I would definitely practices a little bit this number I mean I think for this poem I want to say that I there's not that much I want to add because this is a very standard problem this is almost textbook backtracking to be honest like literally like backtracking this is the exam with that I think I learned on like many years ago I could be well but so definitely like you know it's fundamental enough that I would consider you know and I think well the only difference I was saying is that uh when you're taking now goomer's crying they talk about backtracking they talk about chess well definitely you know there is a distinction between knowing the algorithm and actually able to implement album and that's something done like I always have a case even if you think you know the solution make sure you know how to code it which is not quite the same as you kind of saw me earlier binary search but I need an album immediately I still struggle on open before five one arrow is inside like that way so I so definitely that's my advice and for this race I mean it is not I don't think it is my way of saying it but even though it's a hard poem is very straight forward in the sense that it is literally in the textbook so you're expected to kind of be proficient in it right like if it's on the test you have to know it's not my like where there's easy or hard it makes no difference in that we caught well yeah that's why I put
N-Queens II
n-queens-ii
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_. **Example 1:** **Input:** n = 4 **Output:** 2 **Explanation:** There are two distinct solutions to the 4-queens puzzle as shown. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 9`
null
Backtracking
Hard
51
91
hey guys in today's video we're going to look at a lead code problem and the problem's name is decode ways so we are given a string is containing only digits we have to return the number of ways to decode it so to decode it we're going to use the letters in the alphabet to the digit mapping so a is 1 B is 2 through Z is 26 because there are total 26 letters in the alphabet so to decode a encoded message all digits must be grouped together then ma back into letters so if you're given the string as input so this is a again this entire thing is J and this entire thing is f so this is one way of mapping it and here you can see you can map like this which will give you k you can map 10 to J and map 6 to F we can map this to K you can map this to a but you cannot map the entire thing 06 because 06 doesn't have any encoding 06 is different from six and you cannot map a single zero because there is no encoding for zero so let's take this examples and see how we can develop the logic so let's take these three examples and see how we are getting the output so first example s is equal to 12 so we start with the first character this can be formed to a now we take the last two character this will be formed to L because 12 is so this is coming from one and this is coming from 12 now I took the first character and added the second added two to it so it became AB so I'm using this previous value to form the current value so we can form a DP array which will be of the same length as s length is two so this will also be two and always the first character inside the DP AR will be one because there is one way to encode A Single Character so if the ranges of that character is between 1 through 9 we will get 1 it can also be from 0 to 9 so in the first case before starting our checks we will check if the first character is a zero like in this case immediately we will return false so from the next check we'll be sure that the first character will be from the range 1- 9 so since this is 1 and now we start 1- 9 so since this is 1 and now we start 1- 9 so since this is 1 and now we start a iteration from I is equal to 1 so this is 0 1 I is 1 we check the current value and previous value since this whole thing is between the range 0 to 26 there is are encoding add one to that and it will become two so total there are two encoding so two is the answer for this question let's take the second example as is equal to 226 now let's form the DP array which will be of the same length as s the first character is going to be one because we already checked this condition we start a iteration from here I is equal to 1 it is a two so we combine this so two will be added with two and 22 has a encoding so 22 is equal to V it will take the previous value 1 plus whole thing is V so this is one so 2 is B the whole thing it will become V if I add two to this it will become b v and if I take the combined thing it will become V now I will append six to these two characters so BB and V will be there and 6 is equal to F so I will add F here and now I can take the entire 26 and add it to B so this will become B and enti 26 will become Z because Z is equal to 26 so I will take the two characters from here from one and this will become three so I'm adding this one plus this two will give me three and I'll return the last character so three will be the output and in this case the entire thing is false because it is starting with zero now we have to handle few edge cases we are treating only the last character or the second last character combined we are not taking last three characters because there are encodings only from 1 to 26 and 26 is a two-digit number there is no and 26 is a two-digit number there is no and 26 is a two-digit number there is no point of taking a three-digit number and point of taking a three-digit number and point of taking a three-digit number and check for mappings there won't be any mappings for that three digigit number so we have to deal with one digit or twood digit number now we have to check the edge cases for this two digit number if this is a zero and this is a zero so this is one case if this is a zero and this is not a zero this is second case third case this is not a zero but this is a zero four cases both are not zeros like in this case 26 both are not zeros now we have to handle these four edge cases inside if statements so I write down this four cases and see how we can handle that using examples now this is the first case this is the second case this is the third case and this is the fourth case let's take a case where last character is zero and last second character is also zero so here last second last character is zero and last character is also zero now let's form the DP array so this will be of the same length the first character is not a zero so it will have a value of one the second character is two as so we stter iteration from here I is one so this case will be satisfied so it will check last two characters is not zero means we'll check if the value 22 is greater than equal to 26 yes so it will take DP of i - 1 plus 26 yes so it will take DP of i - 1 plus 26 yes so it will take DP of i - 1 plus DP of i - 2 i - 1 is 1 DP of i - 2 is DP of i - 2 i - 1 is 1 DP of i - 2 is DP of i - 2 i - 1 is 1 DP of i - 2 is not there so it will take 1 so this will become two so till here there are two encodings now it will check I here it will check this two characters it is 26 so again this condition will be executed since this was absent in the previous case we replace the whole thing with 1 DP of i - 1 was 1 and this is 1 + 1 DP of i - 1 was 1 and this is 1 + 1 DP of i - 1 was 1 and this is 1 + 1 will become two now I is at 6 it will take that character and the character before it is 26 which is z so the encodings are b z now it will check 22 and 6 is VF and now it will check 2 6 which is BBF so this will give you three and now we are going to check this character I is here and it will check these two characters and IUS one is this so it will check for this case second last character is non zero last character is zero so second last character is non zero and this is zero this entire thing is 60 which doesn't have an encoding so we set DP of I to Z the current value is zero so till here it means of length four there is zero encodings because 2260 will not have any encodings this is I this is IUS one so this condition will be passed where both are zeros if both are zeros again DP of I will be Z because 0 does doesn't have any encoding so set this to zero and finally last step is to return DP of last and output is zero so obviously 22 6 0 can be mapped to Z encoding so Z is our output because the entire thing doesn't have any value now just the last character and make this two so we saw how we are processing till here now I is here it will check I and IUS one again this 2 is 60 doesn't have any encoding since 60 doesn't have any encoding weide DP of it to Z Now move I further so this is I and this is IUS one so this case is satisfied so we set DP of I to DP of IUS one because 02 does not have any value together whatever value is there for this will be added to this so this is zero and finally again this will be returned as the output so for this there is zero encodings because the whole thing does not make any sense now again let's take a new example let's take this so we are at I and this is i - take this so we are at I and this is i - take this so we are at I and this is i - 1 this whole thing is 62 again 62 so this case is non Zer and this is non zero so 62 is greater than equal to 26 this condition will be passing so we set DP of I to DP of i - one this will be DP of I to DP of i - one this will be DP of I to DP of i - one this will be three now move further now I is here and IUS one is this so it will check these two characters and this condition is satisfying because last second character is a two since this is a two the whole value is 20 and 20 has a mapping of T so if that is the case then DP of I is equal to DP of i - 2 so I - 2 is this so equal to DP of i - 2 so I - 2 is this so equal to DP of i - 2 so I - 2 is this so This value will be picked up here an important case is that if we are doing i- 2 and if the length of the input i- 2 and if the length of the input i- 2 and if the length of the input array was only two and it will check IUS 2 which will give DP of minus one so this is out of bounds right so we have to check if I is greater than equal to 2 only then we have to process DP of IUS 2 that I'll show you during coding and finally for this example the output is three now we check this case I is here I - 1 is this combined it is the 62 is - 1 is this combined it is the 62 is - 1 is this combined it is the 62 is greater than equal to 26 so this will be satisfied so this value will be picked and three will be added here now move further I is here and IUS one is here entire thing is 23 and this case satisfies because both are non zero and 23 is less than or equal to 2 6 so this is satisfied and if statement we have to add DP of I -1 + DP of i - 2 so we have add DP of I -1 + DP of i - 2 so we have add DP of I -1 + DP of i - 2 so we have to add i - 1 is this and this so 3 + 3 to add i - 1 is this and this so 3 + 3 to add i - 1 is this and this so 3 + 3 is equal to 6 so 6 is our output for this question so make sure you're forming the outputs so 22 6 and 23 or 22 6 2 comma 3 so these two outputs and important thing is that you have to take only the last character or last two characters because you handle only one digit number or two digits number there's no need to check three digigit number because they won't have any encodings because encodings are only present from 1 to 26 which are Max 2it number coming to the function given to us this is the function name and this is the string s and the return type is an integer representing the number of ways so I have written the same steps which I've explained so let's follow these steps and code them up so first base check is that we have to check if the first character in s is Z then we have to return zero like in example three here so here as you can see s is 06 since it is starting with zero it doesn't have an encoding so you return zero so that is the first step so if the first character is a zero then return zero now we have to create a DP array of size length of s and the third step you have to assign the zero index as one inside the DP array so d of 0 is one if there is only one character there is one way of decoding it and we already checked that Single Character is not a zero so if it is a single digit number from 1 through 9 it will have a encoding of one because there is one way of decoding it because 1 through 9 is a to I now we have to start our iteration from I is equal to 1 because we already dealt with a single digit character now inside this for Loop now in inside this for Loop there are four cases if the second last character is zero and last character is a zero if both are zero the second last character is a zero and the last character is a zero then we assign DP of i as zero now coming to the second case if the second last character is a zero but the last character is not a zero then we assign DP of I is equal to DP of i - 1 assign DP of I is equal to DP of i - 1 assign DP of I is equal to DP of i - 1 so let me copy this condition and change the last character to non zero then DP of I is equal to DP of IUS 1 I'll make this Els if now again in the third case second last character is not zero and last character is zero so let me copy this and make the second last character as non zero and last character as zero so if this is the case now we have to do another check if the second last character is a one or a two because if it is greater than three then the value will be 30 through 990 because last character is zero we checking for the second last character if it is one or two only it will have encoding right because here if last character is zero there is only two options J or T J is 10 and T is 20 if second last character is 3 or greater it will become values 30 to 90 and 30 to 90 don't have encodings so that will come in the else block so I copy this so if second last character is a one or second last character is a 2 then DP of I is equal to DP of i - 2 else DP of I is equal to DP of i - 2 else DP of I is equal to DP of i - 2 else DP of I is equal to Z because there is no range for 30 to 90 it will have DP of 0 now coming to the fourth case we can directly put it in the else block because we process the three condition the last condition is going to be if second last character is non zero and last character is also non zero if both are non zero there are 26 possibilities right if both are non zero so we need to check if the value is less than or equal to 26 so I'm going to substring the last two characters s do substring of I -1 to I + 1 we doing I do substring of I -1 to I + 1 we doing I do substring of I -1 to I + 1 we doing I + 1 because this will be ignored in + 1 because this will be ignored in + 1 because this will be ignored in substring and it will return I so IUS 1 is the last second last character and I will be returned for this which is the last character it will form a substring we need to check if this value is less than or equal to 26 since 26 is an integer value and this is a string value I need to convert the string value into integer using parcent method so integer. parcent and I place the substring inside this will convert that sub substring into a integer now we have to check if it is less than or equal to 26 we have encodings for that here so DP of I is equal to DP of I -1 plus DP of IUS 2 is equal to DP of I -1 plus DP of IUS 2 is equal to DP of I -1 plus DP of IUS 2 and in the else block it means that the value is greater than 26 then we only take DP of IUS 1 and finally we have to return the last element so this for Loop will happen for all the characters inside the string s and the DP will be filled and our answer is present in the end of the DP so return the last element inside the DP now we finished all the steps but there is one more step we have to check so whenever you are doing DP of i - 2 if so whenever you are doing DP of i - 2 if so whenever you are doing DP of i - 2 if the length of the entire array is 2 if the length of the string is 2 and if I is pointing at the last index I is equal to 1 right if I is equal to 1 - 2 will to 1 right if I is equal to 1 - 2 will to 1 right if I is equal to 1 - 2 will give you DP of minus1 will go out of bounds so we will execute this only if there is a length is suppored so we have to check if I is greater than or equal to 2 I is greater than equal to 2 only then we take DP of i - 2 if it is only then we take DP of i - 2 if it is only then we take DP of i - 2 if it is going out of bounds we will set DP of i as one because there is only one encoding which is possible and similarly here too we have to do the same so I copy this whole thing and replace it with this now our code is complete now let's run the code our test cases are being accepted let's submit the code and a solution has been accepted so time complexity of this approach is O of n because we are iterating through the input string from starting to end so n is the length of the string s and the space complexity is also of n because we're using 1D DP AR to form our output that's it guys thank you for watching and I'll see you in the next video
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
1,909
foreign so the problem is given that we need to make an array strictly increasing so we have given a zero index integer array and it will return true if the array is strictly increasing otherwise it will return false now they have also given one condition that we can remove exactly one element also to make it strictly increasing so let's say so let's see in this example one they have given one two ten five seven so by removing 10 uh it will be one two five seven so that is strictly increasing so what is the strictly increasing if num I minus 1 is less than num I then it is strictly increasing it means uh the previous number is lesser than duck the current number right so that is strictly increasing if it is less than equal to then it is increasing only right so that is important here another example two three one two now here if you will remove any element it will not be strictly increasing array so the output should be false now one here also our elements are same right they are not increasing so this is like a straight line elements so that is why the answer should be false so let's see how we can proceed so before writing the code I would like to see the possible cases so let's take our examples so the first example was one two ten five seven so the condition is array I minus 1 should be less than array I this is the condition for strictly increasing right now here let's start from this position because then only we can go to I minus 1 right this is I now 1 is less than 2 so no problem let's move ahead let's increase our counter then 10 is greater than 2 or 2 less than 10 and anyway you can check it out so this is also true let's move ahead now here 5 is the problematic right because 5 is less than 10 so it is not strictly increasing so here 5 is less than 10 so which element we should remove 5 or 10 we should remove then it will be strictly increasing so what we are doing we are here at five okay our counter was a pointer was at 5 and we are removing previous element remove previous element okay in that case so 5 is less than 10 we can write it like this also array I current element is less than equal to we can we should take equal to also I will tell you here right now array I minus 1. so if array I is less than equal to array I minus 1 then we should remove previous element let me just change the color okay so this is the condition right why I'm taking equal to because even if it is 10 if it is not 5 it was 10 then also it will not be strictly increasing right so that is why I am taking this condition less than equal to now let's move ahead so what happened now we have removed from 10 and now our array is 1 2 5 7. so the counter will move to 7 now and it will compare itself with five so since 7 is greater than 5 no problem it is a strictly increasing array right now let me tell you one more example now this example is not given in that but we should take this into also consideration so let's take the same example above one two ten one and here let's take 17. okay I'm changing two values five and seven with one and Seventeen now here let's start our count pointer from here 2 is greater than one no problem pointer will increment to 10 is greater than 2 no problem now here it come at one is less than 10 right it is a problematic right now as per are above condition what we will do we will remove the previous element so we'll remove 10 but if we will remove 10 then do you think this array will be strictly increasing no right because I remember 10 it will be 1 to 117 it will not be strictly increasing so but you can see that if we remove one then it will be strictly increasing 1 2 10 17 right so why it is happening here so here we need to check one more condition if array I is less than array I minus 2. if we need to check the element the current element with both the previous element and the element before the previous element we need to check with them with the booth okay now here it is less than both the elements okay first we have checked this condition and then we are going to this condition okay this is not a separate condition I am checking inside it first this is the if statement and inside this if statement and checking this condition so here it is satisfying this array I is less than equal to array I minus 2 and whenever these two if conditions true then we should remove current element so under rule current element the it will be 1 2 10 17. right so it is a strictly increasing error so now there can be one more scenario like uh we need to keep check that because we have given this condition that we can only remove one element so we need to keep track of that also right so how we can we do how can we do that so let's take count equal to 0. okay and here if this condition satisfied then we will do count plus okay now what do you think should we do count plus here also or not what do you think okay I'm again repeating first I am checking this if condition and this if condition is inside the first if condition okay it is nested if condition now tell me discount should be incremented here also or not okay let me tell you see we are giving getting problem getting the secretive condition in this example okay now here one is the culprit element now one is less than 10 right one is less than 10 so that condition is already checked here so the count is already incremented now if you will increment it again then it will be it will make it two and later when we will check so if our count is greater than 1 we will return false else we will return true so if you will increment count in both the condition then in the second example also the count will be 2 and we will return false right while the answer should be true because there will be only one element one right so we will not be doing count plus here but we need to remove current element now right we need to remove current element y because this 17 because our counter will be incrementing by one every time and this 17 will then be compared with one so we need to remove somehow one right so either you can just remove the element current element I just I said remove current element using slice or slice any method or rather I suggest I prefer to replace it with that element 10 why because if this one will be 10 then the 17 will be compared with 10 only okay and this is exactly same as we are removing one okay so what I will do here I will current element is replaced by the previous element this condition I will apply you can do that also remove current element okay using splice or slice check it out I currently I'm not sure which one will not mutate your array I think it is slice you should use splice which will not mutate your current array that also you can do uh but I prefer the second technique here also in the first just a second in the first condition we are removing the previous element let me check the color now so we are removing the first element right that we will remove the previous element so here also you do not need to explicitly do this removal why because you are saying that you will remove this 10 element right but anyhow the counter is incrementing once it is comparing 5 to 10 once 5 is compared with ten right the counter is incremented discount with discount variable is incrementing right and our I variable is also increasing in so now a current element is 7 and the previous element will be 5 so the only these two will be compared right 10 will not be in the picture so you can either remove it or you cannot review you do not remove it's your choice right that will not be a problematic so let now let us implement it let's go to this code okay so first let us take account variable okay let's name it proper let delete count equal to 0 and let's store let I equal to 0 I less than array dot length I plus okay now check if current element is less than this element if array I is less than array I minus 1. so what we'll do in that case we will increment account right also like I said we can remove the previous element also so that right now I'm not doing or also it should be less than equal to okay now let's check inside this or itself we will check and if current elements is less than element before or we can say second previous element so we can check if array I less than equal to array I minus 2. so in that case we will just replace the current element like that we will replace the current element with the previous element and you will not implement the count variable array I is equal to array I minus 1. right so that's it now let us come out of this for Loop let's check if count is greater than 1 okay let me write like this return false return so let's double check one more time if there is a typo alien GTH okay just keep just at least once check if you're making any mistakes because it will show you these errors also so okay seems good the first condition we're checking the current element is less than the previous element and we're incrementing counter right so we do not need to remove the previous element and then we are checking inside that if statement we are checking the current element is less than second previous element so there we are replacing that element with the previous element right so it is just like as removing and then count with them are written false okay then let's run code line 10 it is giving adder why okay there's no count let me write it count only that is why I was rechecking it but still I made a mistake okay so it is accepting let's submit it so the answer is that it is accepted successfully Okay so let me know if you have any doubt Okay so that's it thank you
Remove One Element to Make the Array Strictly Increasing
buildings-with-an-ocean-view
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).` **Example 1:** **Input:** nums = \[1,2,10,5,7\] **Output:** true **Explanation:** By removing 10 at index 2 from nums, it becomes \[1,2,5,7\]. \[1,2,5,7\] is strictly increasing, so return true. **Example 2:** **Input:** nums = \[2,3,1,2\] **Output:** false **Explanation:** \[3,1,2\] is the result of removing the element at index 0. \[2,1,2\] is the result of removing the element at index 1. \[2,3,2\] is the result of removing the element at index 2. \[2,3,1\] is the result of removing the element at index 3. No resulting array is strictly increasing, so return false. **Example 3:** **Input:** nums = \[1,1,1\] **Output:** false **Explanation:** The result of removing any element is \[1,1\]. \[1,1\] is not strictly increasing, so return false. **Constraints:** * `2 <= nums.length <= 1000` * `1 <= nums[i] <= 1000`
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Array,Stack,Monotonic Stack
Medium
1305
1,670
Hello Hi Everyone Welcome To My Channel It's All The Problem Design Front Middle And Back Why Soave Design Accurate Support And Cooperation In Front And Middle And Take Off The Give Some Wasted In This Class Front Neck Back Why This Constructor Festival Why Image Push Front Floral Middle And Pushed Back Soviet Russia Post E Will Give Value In Two Different Mediums And In Case Of Mother In Front And Back Subscribe Position Operations For The Position Me Two Options Elements And Will Take More Than 100 Years Paper Half Middle Elements Who Know Will Have To Medium Elements and 420 is 2.3 picos Medium Elements and 420 is 2.3 picos Medium Elements and 420 is 2.3 picos per buried top front middle element problem solve how will implement it soft designing decide values ​​in soft designing decide values ​​in soft designing decide values ​​in english support intimate scenes adding and removing gift for the fountain in the middle of values ​​and in building a 154 circle of finish line Soyenge sab kuch points wich uses your daughter handed over to this method business news why daughter end and first show first Monday of methoded in our leaves that is what first is that similarly for wedding meetha middle elements for wedding hindi me element biwi news q.no Been supplied in the biwi news q.no Been supplied in the biwi news q.no Been supplied in the recent activity cute size divide similarly here you don't know you will return to remove first things first subscribe also remove first class fifth own last elements to remove last for middle element no we need to front with ou will do Do We Need to Take Left Side Me Left Leg subscribe to The Amazing David Warner Patience and List This is the Liberation of Management and See What They Are Expecting Element 1313 Floor Subscribe to This Actress What is the Time Complexity of Dissolution So Way Can See All The Front Row Like And First Remove First And Last 501 Operation In English Oil Vishwa Like A Difficult And Take Off Times Index Of Others Like This
Design Front Middle Back Queue
patients-with-a-condition
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
Database
Easy
null
692
hi friends welcome back today we are going to solve lean code problem 471 top k frequent words so this is a medium complexity problem um so uh i often create lead code and lean code uh coding solution videos as well as java j2e related helpful uh videos for helping the uh interviews uh so you know please check out my playlist on my channel and subscribe to my channel has a playlist for a lot of coding solutions as well as theoretical interview questions like telephonic as well as you know screening like initial screening interview questions listed on my channel please go through them uh those are like frequently asked questions that will definitely help you if you are preparing for jobs job interviews so please check them out so let's look at this problem statement given a list of words and an integer k written top k frequent words in the list you should order the words by the frequency of them in the written list the most frequent one comes first if two words has same frequency the one with lower alphabetical order comes first so we have been given a list of words and we have to find out the most frequently occurring words in this list right and they have given us conditions where if the words have same frequency then they should go with alphabetical order right so let's take one example over here to so i can explain you how we are going to solve this problem so uh we are going to solve this problem with the help of hashmap and priority queue so uh if you are a java developer you will definitely be aware of hash map and priority queue so let's look at the um so what first we will do is we will go through this list of words and we will prepare a hash map of word and its frequency right so let's just go one by one so yes so we will just put one frequency here lint uh is one code is one yes is now we will update one to two because this is occurring second time here now code is again we will appear like make it two because it second now baby is appearing once here and you is appearing once here and baby is again appearing so we'll just make it to here now and then lint is appearing and code is appearing so lint we will make two now here and again code is appearing so code we will make three so uh as you can see the frequent cy's code is most frequent word right its frequency is three so uh what we will do after we have prepared the hashmap is uh we have uh like i'll just show you my code also at the same time when we are discussing the solution so we will be um we implemented a word frequency class it has a word and count right so we will create word frequency objects and we will put those objects in a priority queue now right so let's just go ahead and let's just put the objects in priority queue okay so let's just uh go one by one so let's just consider that this is a priority queue that we have right and we will just uh create the objects and put it here so as you can see so first object in the priority queue whatever we objects put priority queue always will put the max we will implement a comparator in this way so our priority queue let me show you this so it has a comparator here now our priority queue is holding word frequency right the word frequency that i just showed you here and uh we are comparing a and b objects such that a dot count is equal to b dot count means both frequency if they are same then we are going to go with the alphabetical order right that's what we are doing here otherwise we will go with the maximum frequency first so that's how we have created priority queue so we will just like uh as you can see here so first our code word will be there right code word is there and it's prior it its frequency is three so it will appear first then after that uh baby lint and yes all has a two frequency so uh the baby will go first actually right in that case let's just yeah so baby is appearing alphabetically first so baby we'll go first so let's just create a baby object here it has frequency 2 and after that lint will go because alphabetical order right so lint is again has a same frequency too so lint will be there and after that yes will be there right yes is because we are going alphabetically because these three words has the same frequency and at the end you will see you right you has only one frequency so you will go at the end with one frequency so this is how our priority queue will look like so this is our priority queue right pq and this is our front direction so this is where we will remove the element and this is our rear end so whenever we fall uh in the priority queue first element we will get it's this code right so once we have populated priority queue we will what we will do we will poll elements k times that's what they want right only first k element so as you can see once when we pull the first element we will get code when we do the again call the second one then we will get baby so we have to just written code and baby in this case so that is what uh the approach is to solve the problem so first we will i'll just go through the code quickly now i already explained in detail so this is the hash map of string and integer word and frequency and we are going to go through the array of words and we are going to populate the hashmap uh with the frequency right so this is the word and this will be the frequency so initially it will be zero and we will keep incrementing the frequency by using gate or default method right and after that we have defined our priority queue of word frequency and i already explained you how the comparator is defined here right so if both counts are same for both words then we will go with the alphabetical order here that's what we are doing or if the counts are not same we will go with the maximum count first right in the priority queue and after that we will just use maps key set method and we will just create word frequency objects here right with the word and its frequency by using map.gatekey and we are offering using map.gatekey and we are offering using map.gatekey and we are offering all those objects into our priority queue offer means we will be adding those objects into priority queue and priority queue will make sure that the objects will be in the order that is defined in this comparator right so after that is done then what we are going to do we just created a string array of the same size of k and we are going to pull the elements here right k times we are going to do that and we are going to form our result array and we are just returning our result array so um this is the one that example let's just take the example that they have given us here so let's just take this example and then just to make sure and k is equal to 3 in this case so let's run this example quickly oh actually we have to format the input right we cannot put input like this so we have to format the input because uh it should be on the one line only i think let's just format it quickly okay so now it should work yeah so now as you can see we are getting correct result right code lint and baby code linked and baby in this case code appear maximum times one two three and four right so code came first lint appear three times i think here one then year two and here three so lead came second and baby appeared two times i think one here and one here right so only two times baby appear so that's how we are actually retrieving the words based on their frequency so maximum frequency is coming first so we'll just submit our code now so our code got accepted with a 73 percent faster submission rate so which is pretty decent uh so this is uh how you can like uh solve this problem of finding top k frequent elements with the help of priority queue and hashmap so hashmap we are just putting the words right so basically it's just order of one and when we are the space wise it is just order of n when order of n right the length where n is the length of words right if there are n words we can say that space complexity will be o n in this case and uh for the offer as well as for the paul the time complexity for the priority queue is order of log n so this solution is kind of you can say k log n right so uh that's what they want so um i think that's how you can solve top key frequent words with the help of priority queue uh you know practice some examples with priority queue and hash map you know then you will get a good hold of how to write the comparators this writing comparator is very important in case of priority queue because this is how the comparator defines how the ordering will work inside the priority queue right and that ordering is very important when we are calling out the elements uh later right so take a look at my playlist you know i have a lot of lead code and linked code solutions already discussed with examples in java as well as there are interview related lot of videos that discusses conceptual videos like dfs videos as well as dynamic programming different data structures of java as well as the most frequently asked telephonic interview questions so check it out and you know that will be helpful if you are practicing or giving interviews also please subscribe to the channel the subscription to the channel will really help the channel to reach out to more people like you so please do subscribe to the channel thanks for watching the video
Top K Frequent Words
top-k-frequent-words
Given an array of strings `words` and an integer `k`, return _the_ `k` _most frequent strings_. Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order**. **Example 1:** **Input:** words = \[ "i ", "love ", "leetcode ", "i ", "love ", "coding "\], k = 2 **Output:** \[ "i ", "love "\] **Explanation:** "i " and "love " are the two most frequent words. Note that "i " comes before "love " due to a lower alphabetical order. **Example 2:** **Input:** words = \[ "the ", "day ", "is ", "sunny ", "the ", "the ", "the ", "sunny ", "is ", "is "\], k = 4 **Output:** \[ "the ", "is ", "sunny ", "day "\] **Explanation:** "the ", "is ", "sunny " and "day " are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. **Constraints:** * `1 <= words.length <= 500` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * `k` is in the range `[1, The number of **unique** words[i]]` **Follow-up:** Could you solve it in `O(n log(k))` time and `O(n)` extra space?
null
Hash Table,String,Trie,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,1014,1919
87
oh you guys mess you daily table problem ASCII code can be straight given the string of one email isn't it a binary by partitioning it to two nonempty substance because if you know edge one possibility to the addition of last month so then they are we will enter in the creek bi-weekly now yeah they will the creek bi-weekly now yeah they will the creek bi-weekly now yeah they will go take that given us but northern be substrate we can say defensively so we have to pick up on these things all right get your right away together creating a custom program so first I get the noise and stir them one on one wavelength as you got length want to have the object if and equally and or not air fiction if it's not then I have you gone for if one is equal to 0 RT than you if s1 dot equals I still don't we go to otherwise I have an int array how we will be new in a sense it followed linkage cracker let us for n I is equal to 0 is holiday day and I asked us what I'm justyou is found as the x1 dot connector of I minus a and I can make such love and see God's going to give us a - a and see God's going to give us a - a and see God's going to give us a - a mouse - now for and I will be good video mouse - now for and I will be good video mouse - now for and I will be good video is monitor and I got snus are this chick is not equal to zero then he done for otherwise for a high obesity veto I monitor on I slash I have a whole treatment it is humble as one not something we go to i from us ask you your campaign GUI and good let me talk of your excellent from I 2 then s to provide one that is knows them to copy for normal excellent visual one and on - for normal excellent visual one and on - for normal excellent visual one and on - one on my wife so basically I'm saying like do - I should not work a lot I a like do - I should not work a lot I a like do - I should not work a lot I a moment and maybe I you know the vehicle I'm I unloaded basically my remainder remaining characteristic mark address - come again characteristic mark address - come again characteristic mark address - come again - gone through and choose our pause but - gone through and choose our pause but - gone through and choose our pause but it looked on this load okay this works like some of the code okay something went wrong okay maybe on the air that all flow ah okay this won't be beyond qp1 now to Russ does like to fly Thank You Otto
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: 1. If the length of the string is 1, stop. 2. If the length of the string is > 1, do the following: * Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`. * **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`. * Apply step 1 recursively on each of the two substrings `x` and `y`. Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`. **Example 1:** **Input:** s1 = "great ", s2 = "rgeat " **Output:** true **Explanation:** One possible scenario applied on s1 is: "great " --> "gr/eat " // divide at random index. "gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order. "gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them. "g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ". "r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is "rgeat " which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. **Example 2:** **Input:** s1 = "abcde ", s2 = "caebd " **Output:** false **Example 3:** **Input:** s1 = "a ", s2 = "a " **Output:** true **Constraints:** * `s1.length == s2.length` * `1 <= s1.length <= 30` * `s1` and `s2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
null
118
good afternoon friends this is hes from python Academy so today I will back with some another problem statement which is based on Python Programming okay so here is the first problem statement from lead code so this is a pascal triangle so we have to write a code where we have to print the Pascal triangle and in Pascal triangle we have given the number of rows so how many number of rows we want to print a pascal triangle and it will return the first num rows as a pascal triangle okay so what is given to you that will be see so in paral Triangle each number is a sum of the two number whatever number we have that is already sum of the previous two number that is given below here so see that is one so previously there is only single number but this is one this is two so two has two is a sum of previously two number that is 1 + 1 here three is number that is 1 + 1 here three is number that is 1 + 1 here three is a sum of previously two number 1 + 2 a sum of previously two number 1 + 2 a sum of previously two number 1 + 2 here also 3 so 3 is a sum of 2 + 1 here also 3 so 3 is a sum of 2 + 1 here also 3 so 3 is a sum of 2 + 1 here this number we will be sum of 1 + 2 that this number we will be sum of 1 + 2 that this number we will be sum of 1 + 2 that is 4 this number will be sum of previous two number that is 3 + 3 6 this number two number that is 3 + 3 6 this number two number that is 3 + 3 6 this number will be sum of 3 + 1 that is 4 so at the will be sum of 3 + 1 that is 4 so at the will be sum of 3 + 1 that is 4 so at the last R it will print 1 4 6 4 1 at the previous it will print the prev sum of the previous two uh number that is three so it will print 1 3 31 and the second row third row sorry it is a me between the number at is two is a sum of the previous two number that is 1 + one so likewise we have to print the 1 + one so likewise we have to print the 1 + one so likewise we have to print the write a code which will return the number of sum of all the number according to the number of rules it will print the okay so see here if I had passing number of row as five so it will gives you five number of list okay that is actually a nested list if I'm passing only one row so it will print only single number because they have previous they have don't have any previous number okay and the constant is given to you so number of rows is not more than 30 and it is greater than only one so number of rows is always lies between 1 to 30 okay so we will try to write so basically here we will try to write our coding uh based on class so first we will write class keyword after the class keyword suppose I have to pass the class name as a solution followed by colon in between the class we have various types of methods so variously or method or function so I have creating a one method while using Define keyword and where I have to give the name of the method is a generate so generate is a name of the function or method which is followed by the uh input parameter or parameter so I have passing first by default parameter that is a self after that how many rows we want to enter that parameter is given to you that is a num rows and in the num rows it is actually the we are passing the numos in a form of integer so for that we have to write here uh in and what in according to the uh number of row we are creating list so for that we will write here list Constructor list of list that is a nested list okay so list of it will going to uh return nested list so we see in the output they had shown you the nested list element so for that we are creating the list within list and in between the list we have the integer type of value which was followed by the colum okay so likewise we have created this method so now if the we have if we are uh trying to find out if the number of rows are only zero so that time what it will return so that time it will return only empty list okay if the number of rows is one so that time it will return only single element in within the list that is one if we have more than uh more than one rows in there so that time for that we will write we will try to apply uh for Loop so we will write 4 I in range of 1 comma num rows + one so we range of 1 comma num rows + one so we range of 1 comma num rows + one so we will write here num uh sorry 1 2 3 4 5 yeah so num rows so if I had passing five so Loop is going to uh starting print with one and rest of the four times will Loop will run Okay so first row in the first row we are passing only one element within the list after that we are iterating according to column so for that we will pass another loop within the loop that is a nested Loop so that is a for J in range of I + 1 so I is a for J in range of I + 1 so I is a for J in range of I + 1 so I is nothing but a uh index value of row okay sorry uh 1 comma I yeah so uh it will going to print the element in column wise okay so from here we had passing the uh row as a list suppose we want to add any element within the list so for that we will WR use append function and within the append function we trying to pass the first element that is one and nexted list one which were assigning to the variable triangle so for that we will write here triangle So within the triangle we are passing some element where that is a IUS one whatever the row number is there that element should be printed according to the less than one uh row okay next column it will going to print uh identify the column number that is the index value of J is actually the index value of column okay next it will going to pass nested list within the list so for that we will write here I - 1 I - 1 I - 1 and current element of the F that column that for that we will write here J so here we will trying to append all the element within the initial L that is a triangle dot so sorry first we will try to openend all the element within the row okay so for that we will write here first row append one so previously one whatever the number of rows is there the first element is always one so for that we will pass here one as element and all the rows are appending into the triangle column triangle variable so for that we will write append row now it will return the triangle whatever the value of the triangle is there return triangle so it will return the all the elements uh within the list which is stored in Triangle variable so now we had uh created our class now it's time to um pass the object pass the uh argument with the help of object and object is always associated with the class so for that first we have to pass the number of rows so I had pass here uh they had given you the number of rows is five so I had passing the uh element for the number of rows is five next we will create the object of the class so what is the S is object of the class solution okay so likewise we have created object so now with the help of object that is as we can use any method of the class okay and that method of the class will be assigning to the result variable so s dot with the help of dot operator s is that is object of the class is able to access any method of the class so name of the method within the class is generate okay so we will write here generate So within the argument we have to pass the num rows so it will going to pass the number of rows is five now we will try to print the what is the nested value within the list of five number of rows so let's see whether we will get uh expected output or not so we are passing the element for the number of rows five so see we will get expected or not there is a error I think some error is there Let's see we will run actually error is there return is outside the function yeah so we you have to keep this uh problem uh always there may be a chances you will get the identation error so for that we are getting the error so return is always align within the inner loop okay so likewise we had created so once again I will try to explain you so our Moto is we have to pass the number of row according to the number of row it will print the Pascal uh Pascal value and actually what is the Pascal triangle sorry Pascal triangle so actually Pascal triangle is a number which is the sum of previous two number okay likewise we have created the generate that is a method of the class solution which we are passing as a argument of number of row which is integer type and that integer value is always formed within the element of the list that is nested list okay list Within list okay so if the number of rows is zero so it will always return empty list okay suppose I had uh passing here for example zero so see what will what they will show you okay so it will give you empty list so likewise we had written if the number of rows is entered by user is z Z so it will return always empty list okay if the number of rows I had pass one so that time it will return only one element within the list as a triangle variable that is one so see what we will get only one element okay only one element likewise if I had passing the number of element five so that time it will print Five Element of the list starting with 1 2 is a sum of previous two okay 3 is a sum of previous 2 3 is a sum of previous one 4 is a sum of 1 + sum of previous one 4 is a sum of 1 + sum of previous one 4 is a sum of 1 + 3 okay 6 is a sum of 3 + 3 4 is a sum of 3 okay 6 is a sum of 3 + 3 4 is a sum of 3 okay 6 is a sum of 3 + 3 4 is a sum of 3 + 1 if I had passing for example 3 + 1 if I had passing for example 3 + 1 if I had passing for example six so that time it will print one more list within the list 1 5 10 see we will see 1 5 10 5 1 yeah see 1 5 10 5 1 okay so likewise it will return so basically Pascal triangle is nothing but element which is a sum of the previous two element okay middle some of the previous two middle element likewise we had trying to write the code to print the Pascal triangle and it is very simple but you have to apply the logic you have to keep in mind for this logic so I suggest you before moving to this problem set you have to go through the pattern printing Triangle Printing uh Pro uh code which were already existed in our uh playlist that is a python interview hack on ANUK python Academy YouTube channel so once you go through the that those problem statement then you have to practice this one so it will gives you some idea about the how we will use nestate for Loop how will be print the value for that okay so likewise we had trying to solve this problem statement so if you have any doubt regarding this session or this problem statement so feel free to ask do comment us subscribe the channel okay thank you and in description I will provide you solution also for this code also okay thank you this is for today have a nice day
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
937
Loot hello welcome to my channel also appoint Russian life is the problem the problems are seen from different energy lock subscribe in which of the first number on The link for detail view hai vivarvar aur digital de to absolut hadith 220 saaf lock pattern lock and digital of its Guaranteed Money Playlist One Word For Telling Is To Visit To Riyadh Lakh Soft Dough To Write Letter Come Before In Trans Now Half Minute Alphabet And Lexicography Ignoring Pimple Or Pimple Kaise That Digit Target Also Put In Were Original Shiv Vishnu Want To Change If Its due to give its natural color button lock natural color button lock natural color button lock and sonu bhaiya auto aa vriddhi lakhan lal ab box first digit love oo similar problem dark * example similar problem dark * example similar problem dark * example inducer devgan for loss the first world immigration and withdrawal zip and no 21 a ki Your extra grab digestible and tweet that your gathered is bad that fasting Pintu defined a comeback recession that red subscribe The subscribe to that January 11 news meaning video man and a space sweater on cancer president unlocked dry award remember based on the Space the first tarf fennel butt district governor subscribe to that asim's chain two under loop wear checking the lock first character certificate and diploma wash vid flirt 's juice MB title love to see Arvind Singh 's juice MB title love to see Arvind Singh 's juice MB title love to see Arvind Singh club scam id difficult youtube sad ni thee whose it was Posted in vigilance baking bottle boxer letter box a's bottle option letter love affair shopping box for goals we also a share setting the corpse and administration and this bottle letter from veervrat subscribe button on this side that this intelligence luxor digit seed available but in were Video of doing just ki pindak ki number returning chero ki and isi people ne this letter love not listed under love you show me a shopping cigarette share with thank you
Reorder Data in Log Files
online-stock-span
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
Stack,Design,Monotonic Stack,Data Stream
Medium
739
1,470
hello friends welcome to coding interface channel hope you are doing great if you haven't subscribed to the channel yet please go ahead and subscribe I have created a bunch of playlists to cover various categories of the problem such as dynamic programming BFS DFS and also there are several playlists to cover basic data structures such as trees link lists graphs and so on please check them out I have uploaded the code for this particular problem to the github repository you can get the link from the description section of this video let's jump in today's problem shuffle the array given the added nums considering of two and elements in the form X 1 X 2 so on until xn y 1 y 2 so on until Y n so written the array in the form x 1 y 1 x 2 y 2 so on x and y on so basically this is a something called interleaving method so basically we are given with 2 n elements right so when it is 2 and right so then the length of the array will be always even right so you'll be able to cut that array into two equal halves right so when 2 n elements the array will be of even length right so now we are asked to interleave those elements in first set of n elements with second set of n elements right so let's go ahead and look at the simple example this problem will be very simple and it will be a most likely a brute-force method right so here we are brute-force method right so here we are brute-force method right so here we are given with the six elements where n is equal to 3 alright so when it is 6 that means n is equal to 3 obviously right so we are already said there is 2 n elements so 2 n is equal to 6 that means obviously n is equal to 3 all right so now the elements are the first half is x1 to xn right and the second half is y1 to yn so that's why I have like divided with the space here so 2 5 1 will be X part and 3 4 7 believe y part so now what we are supposed to return is 2 3 right 2 3 and next 5 4 right and seven right so this is what the output is so basically this is the example that I got from the example one so the output that we have suppose written is two three five four one seven so that's what we got hurt right so this is just basic interleaving that's what we call right so for this particular purpose what we are going to do is like basically it's a simple step approach there's no big logic in oil here in this particular problem we'll just go with the brute force method right so for this purpose what we are going to do is we'll just declare an array which is equal to the length of the two n elements right so that's one I'm going to declare and then what I'm going to do is declare two indices so one index will point into the zero that is where X 1 is pointing to so this is where X 1 starts right and there will be another index called J where y 1 starts right so that's what I am going to declare so I ain't I is equal to 0 and J is equal to n right so normally in several languages the indexing starts with zero that's why we will go from 0 to n minus 1 so that's the reason why the next that means y 1 where it starts it set index n so it will go on till 2n minus 1 right so 0 to n minus 1 will be X set and n 2 to n minus 1 will be Y set right so that's why I'm calling x1 is starting at 0 and y1 is starting at n right so now that we know ok this is going to be the start points for x and y right so now what we're going to do is interleave right so to take an element from exit and take an element from Y set and keep them together right take an X element from exit and take an element from why is it keep them to that so that's what we are going to do right so this is the answer everybody clear so we are going to fill up this answer array while going through this so I have declared another variable called index which is equal to 0 to start with so the index is initialized to 0 so first thing is we have to get the X 1 and then Y 1 right so what we are going to do is answer if index plus is equal to num of I so get the I that means get the X first and then get the why right so that's why you just repeat those things by putting the elements from the nums array that is the input array into the answer array right and keep on incrementing the index as well as the I and J right the I and J indexes right so initially when I is equal to 0 that is X 1 I is equal to 1 means X 2 is equal to 3 min 2 means X 3 look like Y sir you'll be incrementing through I plus and J plus was also incrementing with y 1 y 2 and so on and finally the answer will be populated with the interleaved fashion right so we will return the answer right so that's how we are able to solve this problem very easily right it's just an interleaving problem that's what we call so let's go ahead and look at the time and space complexity for this right time and space so how much time we are essentially doing here so these are anyway declarations so it will be taken constant amount of time and this while loop we are going from 0 to and right so our I we are doing with AI starting from 0 right till and right so correct so we are going n times basically so that means even though array has 2 n elements we are able to solve this problem in order of n time right so the time complexity taken for this particular problem will be order of n so and the space complexity so are we using any extra space here yes we are declaring the answer array which is equal to the length of the 2 and right so that means we need the space for the this as 2 n are we using an extra space we are using these variables but these will be constant amount of time when you compare with and right so that's the reason why we are not going to add any more space for these three variables so the space complexity is order of two n so we are going to remove the constants such as 1 2 3 4 and all when we generalize the Big O notation so we will say order of n is the time complexity for this particular problem so the space complexity is order of n and also the time complexity is also or and so this will be a brute-force based and so this will be a brute-force based and so this will be a brute-force based approach right so it solves the purpose basically in the order of endtime and order and space right so if you have any further questions please post them in the comment section below this video I will get back to you as soon as I can I have posted this cover to the github repository you can get the link from the description section of this video below if you haven't subscribed to the channel yet please go ahead and subscribe and share among your friends as much as you can please click on the bell icon so that you will be notified about my future videos thank you for watching I will be back with another problem very soon till then stay safe good bye
Shuffle the Array
tweet-counts-per-frequency
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\]. **Example 2:** **Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4 **Output:** \[1,4,2,3,3,2,4,1\] **Example 3:** **Input:** nums = \[1,1,2,2\], n = 2 **Output:** \[1,2,1,2\] **Constraints:** * `1 <= n <= 500` * `nums.length == 2n` * `1 <= nums[i] <= 10^3`
null
Hash Table,Binary Search,Design,Sorting,Ordered Set
Medium
null