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
149
so today we're going to be going over our max points while I initially I thought this problem was kind of easy but we can start with the definition given endpoints on a 2d plane find the maximum number of points that lie on the same straight line like I said initially I thought this problem was sort of easy and the theory behind that is we could just hash the slope and the intercept of each line and then see if each point is on any specific line and then at the end we can just return the line then as the maximum a number of points that was assigned to it but in practice this problem is actually a little bit harder and it stems from how we compute floating point numbers in program in any in a computer basically so if you remember the equation of a line y equals MX plus B where m is the difference in Y over the difference in X we can see that as numbers become very large we get very similar floating point numbers and in this case it actually is okay right because the difference occurs in the fifth position and we definitely have fifth digit precision in floating point numbers in our computers today but as these numbers become very large still in maybe double or long range right we can imagine that this floating point number actually becomes an approximation around him right and if the last digit happens to round to the same number we can get the same slope even though the numbers or even though the lines are different so for example in this case you know if we happen to stop right here we would get the same slope and that's actually the same concept behind much larger number depending on where you stop you may get the same slope so we can't compute em as an actual division of two integers in this case so we can try storing em in an exact form and an exact form is let's just imagine we can just store the numerator in the denominator we don't need to reduce this fraction to a floating-point number and the way we a floating-point number and the way we a floating-point number and the way we can tell if two slopes are equal is by reducing their fractions and checking that their reduced fractions are equal so how do we reduce a fraction well we can divide both the numerator and the denominator by the GCD as seen here so if we compute the slopes of the blue and teal line the blue line you know that I picked an arbitrary point ordering based on perhaps how they're ordered in the original array 0.2 and point 1 for the original array 0.2 and point 1 for the original array 0.2 and point 1 for the blue line is are here on point 2 for the teal line and point 1 for the T line are there so you can see the slopes computed here 10-0 the difference in Y over 10 here 10-0 the difference in Y over 10 here 10-0 the difference in Y over 10 minus zero the difference in X is 10 over 10 and then the teal line is negative 10 over negative 10 and initially we can't really compare these two numbers because they're different but if we divide by the GCD like I was saying and reduce these fractions we would get 1 over 1 and then 1 over 1 but we still need to consider the B intercept right because these two lines are parallel they have they do have in fact have the same slope but they don't have the same B intercept so they're not the same line so we can solve for B and basically we pick any point in the pair on the line that we're trying to determine and that will give us a whiner next and from there we can use the M that we computed previously so we can solve for B in an exact form as well the problem with you know reducing something like this would be we're not computing m in an exact form or in an approximate form in a floating point so we can't actually solve for this equation because we haven't really solved for mms2 terms at this point so we can solve for B in an exact form so if B equals y minus MX and M is Delta Y over Delta X we can multiply Y by Delta x over Delta X which is just 1 so we're finding that and then we can combine these two terms because they now have the same denominator into Delta X Y minus Delta YX over Delta X and the good thing about this problem is all of the points are integers so we are left with an integer denominator and an integer numerator at the end and then we can divide both the numerator and the denominator by the GCD as well so that will give us a an exact form for be in exact form for M and then all we have to do is hash these values and count the number of points so if we let M equals a B and B equals CD we can store ABCD as a tuple in Python obviously and you I'm sure there are couple equivalents in other languages and just a reminder we've computed M and this would be 1 over 1 and M 2 is 1 over 1 and then B we can compute with the equation just seen ten times with the y-value times Delta X ten times with the y-value times Delta X ten times with the y-value times Delta X which is on the bottom - the x-value which is on the bottom - the x-value which is on the bottom - the x-value times Delta Y on the top divided by Delta X so that will give us 10 minus 10 which is 0 over 1 and then we divide the GCD and just a small note the GCD of 0 and it's just n so we do the same thing for the second intercept for the T line that we were looking at and we could see that the B intercept is just a different number so we can hash these two things even though the 1 are the same the 0 1 and the negative 10 1 are different so one small caveat to this problem is that there are there could be multiple points on the same coordinate position so you can see here with this plot the Green Point has well the Green coordinate it has four points on it and the blue coordinate has six points on it so all we need to do is hash the coordinates to reflect how many points are stacked there and then when we go to determine if we determine that a point is on a given line we can add the number of points on that coordinate sorry if we determine a coordinate is on a given line we can add the number of points to that lines sum and then at the end we just return the highest sum that we've seen and that's it so now we can go over the code and then I'll explain that so first I want to go over the naive solution which actually doesn't need the tupple as described earlier in this way we can just store a slope and the reason is we can start out by hashing the points as normal as described and if the lengths of the points hash is 1 it means we've only found one and we can just return the values value for that coordinate otherwise we can check every pair of points and compute the Delta X and Delta Y is described and then we can check every other point and then we can check and see if for that point if the slope between that point and let's say the ith coordinate point here is the same as the slope between I and J and it should make sense because if you draw a set of three points if you check the slope between the first and second and you find it's some value and then you check the slope between the first and third and you find it's that same value then you know that all three of those points are on the same line so that's the logic behind this solution and because we check every point cross every point again it's gonna be basically end and cubed where n is the number of distinct coordinates right because we're hashing the coordinates in the beginning so we're not technically checking every single point but in the worst case every point is unique and we are checking every single point so it would be n cubed now the optimal solution starts off the same we hash all the points and we return immediately if we've only found one coordinate but we go through and instead of checking having that third kind of loop we store the tupple as described where we store the B intercept as well so we don't need to determine whether or not any given point is on another line that some other pair determined or some other pair was computed for all I need to do is compute every pair see what line that pair generates by storing M and B and then count the number of times that and B occur by adding the number of points for that specific coordinate so starts off the same right for every coordinate IJ compute the M Delta X and Delta Y and actually there is a small edge case where if the line is vertical or horizontal we just need to hash that line right because the X a vertical line may not have a B intercept so we shouldn't try to compute the B intercept there and the y intercept obviously or horizontal line obviously has it be intercept it's just the Y value itself but we don't really need to worry about that we can just store basically a wildcard and in this case and remember that we've seen that horizontal or vertical line otherwise we compute the B value as described where we store the exact couple of the Delta X Delta Y and then the numerator of the B and denominator would be and then we just go through and count and if we've seen the slope or sorry if we have not seen it we're gonna add both the number of points for coordinate 1 and coordinate 2 if we have seen it however we need a little bit we need to be a little bit smarter about how we add points so for any coordinate I J it's possible that we've already seen I coordinate I as part of the same line that coordinate I and J create so as a result we don't want to re-add I to the result we don't want to re-add I to the result we don't want to re-add I to the same line that we just computed now we only want to add J right because if I maybe is generates a line between I and M and it has the st. is on the same line as J we only want to add J to that so that's what this sort of block of code does it just checks and then at the end we checked see if the value which is updated is greater than our current max and at the end we return the current max so hopefully this was clear I've commented everything is on the github this code the diagram that you saw and thank you for watching and if you have interviews coming up make sure you try to remember what you know and don't try to cram everything in and hopefully this problem can help you in your interviews it's always a great feeling when you see a problem that you studied or something very similar to it so thanks again and good luck
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
289
hey everyone welcome back and let's write some more neat code today so today let's solve the problem game of life so as you can see this problem is quite an essay so i'm going to try to break it down simple just using this below example drawing so we're given an n by m grid and each position of the grid is either gonna be a zero or a one a zero means it's a dead cell a one means that it's a living cell so we're given the initial state of the board and we want to return the next state of the board and we're given a few rules on how to do that so the first rule we're given is related to living cells aka the one values so let's take a look at this one so what we're told is that for any particular cell whether it's living or if it's dead it has up to nine neighbors so of course we have the neighbor to the left to the right below and above but in this case we actually do count diagonal neighbors so the top right the top left bottom right so it has up to i think i said nine neighbors but i guess it's actually a if you take the entire three by three minus the middle so it has up to eight neighbors right of course for a cell like this one it has one two three neighbors because all of the other neighbors would be out of bounds so considering all the living cells any living cell like this one or a living cell like this one that has fewer than two living neighbors is going to die in the next state so let's take a look at this cell it has one neighbor which is dead another neighbor which is dead one neighbor that's living and then another neighbor that's dead and another neighbor that said and the other ones to the left are out of bounds so it only has one living neighbor so any cell with less than two living neighbors is going to die so let's take a look at it in our output right when you see from the initial state to the output state it's dead so it had to become a zero so that's one rule let's consider this living cell another rule that we're given rule number two is that any living cell with two or three living neighbors will be alive in the next generation or the next state so let's take a look this has a dead neighbor one living neighbor a dead a second living neighbor and a third living neighbor and so it has three living neighbors two or three living neighbors means it's going to live in the next state so any living cell like this one is going to live in the next state because it has three neighbors now any living cell with greater than three neighbors so meaning it has four neighbors five neighbors or more like anything greater than three is going to die now i don't think we have any neighbors or any living cells in the initial state that actually had more than three neighbors living neighbors so i can't really show an example for that but you know for example if this one had uh you know multiple like five living neighbors or something then in the output it would become a zero so just to summarize any one will and any initial one will stay alive if it has two or three neighbors else it will die two or three neighbors that are ones and for zeros the rule is actually very simple it will become alive if it has exactly three living neighbors else it is going to stay dead right else die basically it's going to stay a zero if it has exactly three neighbors then it's going to become alive let's take a look at this example right it's a zero initially how many living neighbors does it have it has one living neighbor another living neighbor this is not a loving neighbor it has a third living neighbor and then this is not a living neighbor and that's all the neighbors it has three of them are living so when you see this uh when you take a look at this in the output it is now alive right now you can read the description you can read that essay above if you want to know the story behind it but basically if you're writing the code these are the two things that you need to know so once you kind of break the problem down like i just did the it's pretty easy to kind of code it out right like for this uh this cell you just look at all nine of the neighbors now that's you could code it up a couple different ways i'll show you how i'm going to code it in a bit but it's pretty straightforward right for every single cell you look at up to eight different neighbors you count you know okay is this a zero okay then we're going to do this portion right does it have three neighbors if it does let's change it into a one in the output if it has if it doesn't have three neighbors living neighbors then we leave it as a zero and basically repeat that for a one we'll execute this portion of the code and keep doing that right and we'll build that output in a separate piece of memory right because they want us to modify the array in place so what we can do is use extra memory that memory we're going to use is o of n by m and then take that memory and put it back into the original this is going to be the memory complexity the time complexity is going to be about 8 times n times m but that's still going to be n times m right so this is the time and memory complexity but their challenge to us is can we actually solve this in o of one memory without using extra memory but updating this array only in place and the answer is yes we can do that but it's a little tricky on how to figure it out i'm gonna explain to you why it's tricky and then i'm gonna explain to you the actual way that we can solve it what if we ended up changing a one to a zero right we changed a couple ones to zeros right we maybe would change a bunch of them right so then for this one we're gonna say okay it only has a single neighbor that's a one therefore in the output it needs to be changed to a zero but that's not actually the case because when we're updating a particular cell we want to use the values from the neighbors that are the original values we don't want to use the updated values for every single cell we need to remember what was the original value of each neighbor cell but we also need to update it in place which is why i had to use extra memory in the first solution so how the heck for every single cell can we remember the original state and the new state how could we possibly do that well let's let me just draw a table for one second and after i do that i bet you'll be able to figure it out yourself how exactly we can do that so if the original value was a zero the output value could have also been a zero right the new value could have also been a zero if the original value was a one it could have been turned into a zero right but we also know there's a couple more cases a zero an original value zero could have been turned into a one and the fourth and final case is a one value originally one could have stayed as a one in the new position now if you know like truth tables this is not exactly a truth table right like this would be a truth table if we read it regularly right a zero a one a two and a three this is not quite like that so we're gonna be mapping this to a zero this to a one this to a two and this to a three so this makes sense these two are backwards so that might be a little bit confusing but it needs to be like this right in binary this is a two and binary this is a one it needs to be like this so basically what we're going to be doing you'll understand in a bit is if we get to a zero right and we see that okay it doesn't have exactly three neighbors that means in the output it's also gonna be a zero so okay a zero that originally started a zero and turned into a zero stays as a zero so that means the this is the value we're gonna put in the array and a one value that turns into a zero for example this one turned into a zero in our output actually in our array it's gonna stay as a one so this would stay as a one according to this value and the reason it's staying as a one is because when we get to a neighbor now like this neighbor right when we look up to the top left we want to know what was the original value here and that's what this tells us the original value was a one this tells us that the original value was a zero if we ever got to a two we would know that the original value was a zero and if we ever got to a three we would know that the original value was a one if instead in this position the original value zero new value one we actually didn't have a two we had a one that would be very confusing because then we know that ones initially mean okay the original value is a one but if a one also meant that the original value was a zero we have a contradiction that's why i'm doing the truth table like this so i hope you get the idea but once you kind of figure out this table then it's pretty straightforward let me just continue the algorithm from here so in this position this zero actually has three neighbors that are ones what does that tell us okay a zero that turned into a one is now going to be a two so we're actually going to put a two value over here and this zero is going to stay a zero because it has more than three neighbors so it stays zero this one has exactly three neighbors so what do we do with an original one that turn that stays as a one in the new state well we turn it into a three so this one is actually going to be turned into a three similarly this uh one we're going to count how many neighbors of it are ones well this is not this is a zero this is a one this is a zero this is a two how do so does a two mean that it's a living neighbor or a dead neighbor let's take a look 2 means that the original state was 0 so okay we're going to know that this does not count as a living neighbor this one only has a single living neighbor that means it's going to die in the next state what do we do with ones that turn into zeros we leave them as ones right so that means when we actually build our output state in the final step of this algorithm we're going to transform all ones into zeros but threes are going to stay as ones now this one has one two three living neighbors so we're going to turn this into a three as well this one also has two living neighbors right a three means that originally it was living so this is also gonna stay as a three this zero has two living neighbors but it needs three living neighbors for it to turn to life so it doesn't this zero has one two three living neighbors so it's going to turn from zero into a one therefore that means it's going to become a two so let's transform it into a two and this zero is going to stay zero because it only has two living neighbors but it needed three living neighbors so now we have some twos and threes in here but we know that we wanted our output to just be zeros and ones so now we're gonna go through every position in here and we're gonna map it so from here so from this column over here we're gonna map all zeros into zeros we're going to map all ones into zeros we're going to map all twos to ones and map all threes to ones as well so zero stays zero one turns into zero stays zero two turns into one so you can see that's the case in the output zero stays zero three turns into a one you can see that's the case in the output one turns into zero you can see that's the case threes both of these threes are going to turn into ones zero stays zero two turns into a one and zero stays zero so this is going to be the output so we did this without any extra memory we just needed a couple we needed an extra bit basically to store the additional information right we had an original column and a new column so we basically have two bits right it's still zeros and ones but it's two bits that's kind of why we need zero one two three so with that being said let's jump into the code now okay so now let's get into the code so remember we do want to update the board in place we don't have to return anything so i just wrote a little bit of pre-code just to speed things up a pre-code just to speed things up a pre-code just to speed things up a little bit so the first thing you can see this is kind of the table that we're going to follow this is the logic we're going to follow and i got the dimensions of the board and now we're iterating through the entire board and so for every single cell we're definitely need gonna need to count the number of neighbors that it has regardless of whether it's a zero or a one so for every particular position let's count the number of neighbors now i'm gonna put all of this logic for counting the neighbors in a helper function because i don't want to focus on that now we know it's going to be pretty easy just checking the eight directions so now we're going to check okay is this position itself in the board that we're looking at row column is this a one or is it a zero because the logic is going to be different so is this equal to a one or we can just leave it like this or else is it equal to a zero so if this position is originally a one you can see and so now if the number of neighbors remember if count of neighbors is equal to two or three in other words in python you can say if it's in two or three then what are we gonna do if a one original one in the output state if it's also a one then we're going to change it to a three so let's do exactly that if it's if it has two or three neighbors let's change this one into a three otherwise if it originally was a one and it turns into a zero it's going to stay as a one right so in the else case we actually don't even have to do anything we don't even have to execute this statement right okay but so now let's take care of original state zeros so remember if the number of neighbors for a zero is exactly equal to three then it's going to turn to life right so what do we do when an original zero turns into a one well we change it to a two so let's do that the board at this position is gonna be equal to two if it's if it was originally zero and it stayed zero well then we can just leave it as zero so we don't have to do anything in the else case and since we're doing this logic we could actually uh so we could shorten this else case up into this fix that okay so else if neighbors is exactly equal to three then we change it to a two otherwise it stays and so remember the last thing we're going to do uh other than creating our helper function count neighbors we're also going to go through the entire thing one more time and remember we're going to be taking each uh output state and mapping it to what the actual new state is so zeros stay zero ones will turn into zeros and twos will turn into ones and threes will also turn into one so let's do that so if this board whatever the value of this board happens to be is equal to one is one case the other case is else if the board is in the array two or three meaning it's either two or three that's going to be the other case so if it's equal to one in our out in our uh comment you can see ones will turn into zeros so let's uh transform this into a zero and if it was two or three then the output is going to be a one so we can instead change that into a one if it was just originally a zero as you can see a zero was going to stay a zero so we don't have to do anything for that so that's pretty much the entire code let me just copy and paste the count neighbors function because i think that's kind of the might be the annoying part to code in this problem but it's kind of the least important because you can do it many different ways you can choose to do it how you want you can basically iterate through the eight different neighboring directions what i'm doing here is i'm actually starting at the top left corner and basically doing a nested loop going through the nine positions from the top left corner of a particular cell this row uh column cell i'm going from the top left neighbor all the way to the bottom right neighbor and i'm skipping all the positions that are out of bounds so if the position was out of bounds then we're gonna skip this iteration of the loop or if the position was the original position itself because if we are iterating through that three by three square centered around that input position we don't want to count that position itself so we're going to skip that as well but all the other eight neighbors we're gonna check if that neighbor value is either equal to one or three why are we checking if it's equal to 3 well because if it's a 1 that means it was originally a 1. if it's a 3 that also means it was originally a 3. so we want to count the number of living neighbors so we're going to count what the original value was if it's one or three we're going to increment the number of neighbors and then once this loop is done executing we'll have gone through all eight neighbors we'll count the number of living neighbors and return it so that's what our account neighbors function is going to do so this is kind of the diagram that you can follow for the logic of this problem and let me just show you the entire code and so as you can see the solution does work it's efficient we don't use any extra memory so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
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
1,094
Main college absolutely channel ko d sunny and today am going clear the like problem telescope change bnd do it is the problem ne pragya ok shop yes quality solve this problem 333 likes 75 wrong and software police mistake is the prevention quality connect birth details like Is now when the routine the time of this 150 hundred according to this problem statement this prank winner car and disaster maximum capacity OK and the subscribe like go is also supplied to give us like strips of is going to have three parameters blackstone information number of passengers For This A Particular Traffic From This Correct Co Tuition Another Quality So That Problem Tourism Destination Source Tourism Destination And Will Have To Find Out Where They Can Be Equal To Transfer All The Avengers From The Giver Suggestion Particular Distribution [Praise] Subscribe Like [Praise] Subscribe Like And Subscribe Click on the button here to find the solution Subscribe To Hua Hai [Praise] [Praise] [Praise] A New Year Set Shopping Today's Episode 2 - That's Given To Us Like Today's Episode 2 - That's Given To Us Like Today's Episode 2 - That's Given To Us Like Lecture Song Reply And Patidev Storing Free Details The First One Girl With Account Of Passengers For This Particular Depend White Visors Position Final Destination Position For The Very Cool Tricks To Solve Such Problems Is Like Plus Make Some Lines On Street Life And Accepted This Write-up Street Life And Accepted This Write-up Street Life And Accepted This Write-up Cutting And Electrification Of Passengers Is From This Position To This Position Packs Abs For Maths Capacity A I maths capacity as camp saunf and particular maximum capacity for any time the total number of passengers from district election will listen or equal to this maximum capacity like west macrame capacity spoil sarkari can hold 1358 most passengers at any time pocket soft particular deposit CSAT disposition and say this amount of passengers avoid scholar and its position in the amount of episodes passengers subscribe and not withdraw tiffin already subscribe apne pati sudhar dry fruits and this note arrange back to be difficult for any step exactly passengers amount passengers co * inter its Every Day It's All This Development Should Always * inter its Every Day It's All This Development Should Always * inter its Every Day It's All This Development Should Always Possible Battery Maximum Paper City Office Kark Avoid All The Best For It's Okay So What They Want To Is Like It Seen Status Amazed At This Quality Debit Passengers Ko *Inter 24 Minutes Ago Are Of Maximum Size Maximum Appealed to Can See The Types of Width 2018 201 Medium Size of Worth Maximum and This Clutter 2018 Company Position From 020 Thin Burke in This Amount of Passengers to * * Thin Burke in This Amount of Passengers to * * Thin Burke in This Amount of Passengers to * * * Describe the Quiet Late Se * Describe the Quiet Late Se * Describe the Quiet Late Se Coordinator Text Message to The Amazing Limit Tenth Position Porn Video subscribe to the Page if you liked The Video then Kaun Tomato Passengers A's Song Sune Helper Soft Anytime With Check Start The Total Number Of Passengers Pet Most Maximum Capacity Till Now 800 Will Develop Traffic System And This American A specific Sampanna Disha Married and Research Institute that is in position at any candidate sum of I that is going to be strictly greater than max capacity that is not possible because not want to traverse back to the going to the west side S Chakra Feeling WhatsApp Message Send A code to the east side effect not give veer vs us debit the best student 100 wicket out palt any position after month wise add this great cricketer tenth maths paper city of this is not forget not going to have several questions page all passenger morning quality Its Ships Puck Software Co Institute For This Point To That Is Mr Ganpat Coding For Its Ticket Main Aapke Show But I Will Duplex Flat Saver Seventh Month Two Man First Accepts All In This Will Explain Much Better Sweater Left In A Website Twitter Trend For Every Like Water Ripple Samseer Vardhak Soen Decorate Co-ordinator Waste Co-ordinator Waste Co-ordinator Waste Increment 800 Model Passengers And This Is Not To President Will Believe Dakadash Quiet Situ 100ml Different One And Visited To Death At Any Time At Every Quite Difficult Volume Of The Question Is The Capital City Of The Scientific Directly Maximum Capacity Jewelers Notification For Admit Chapter Maximum Elements Present In The Summit Update Found Questions Equal To The Capital City That We Can Do The Draupadi Kant's According To Nature Replace System Vector Visum Map Also Like Pyun Its Objective Of This Difficult Pinpointed 201 Tag Yadav Maximum Coordinators Will Not Admit To Return Them With Hips Or Chapter And Exams [ __ ] And Exams [ __ ] And Exams [ __ ] That This To Question Seem To Be Like And District For Finally Bigg Boss To Improve The Time Of The Formation Frequency Is Using The Map Handle Any Time Capacity And Just Found Intoxicate Are the capacity daily up-to-date information on the capacity daily up-to-date information on the capacity daily up-to-date information on the rise in the true sense objects on this viewpoint oo have some Next Cooler Problems for the Black Explanations Previous Smart Problems Advisors should note this Smart Problem Second 100 Sacrifice for Watching This Video Should Like Share and Subscribe it and stay tuned for the latest list of problems thank you for watching c
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
2,000
To Ajay that if this was made then I have a question reverse fix of world to question come give that index trim world and academicians f-16 is given academicians f-16 is given academicians f-16 is given end character in word is given reverse the secret of world day get started 10 and set IT INDEX OF THE FOREST OFFICER So we have to reverse which I string must also have been stressed which I word mission which must have been auditioned in we have to reverse it and we have to reverse it completely and we do not have to reverse it completely we have to say reverse we have to do zero From where this CHC character comes, we have to reverse it, the character given in this pack character 1098 China groom search, if Bigg Boss does not do it, then we do not have to do anything, if we have to do the stringer attitude in A. If we were using this as an example, then we understand that if the example is the word B, A, B, C, D, E, then I am the character, Bhindi, what do we have to do, there are 2D in this, one given, but the first operation will also be first lady, is this so much for us? We have to reverse this much, we don't have to reverse it, so let's understand it a little more, loot, so if we give this to someone, this is a poor devil in the street, there is profit in the street, that builder dot reversal, then we can do this, but what about that? What happened is that this whole one correct will be completely reversed meaning this David's tree like this print wounded us do I only have to do so much so what we will do so much we will do this much in a different films and we will do so much in submitting so it Na, in a moment, we will reverse and edit this, we will add it to this dress, so we will make it successful for us, submit, how is this cream made, I know the name of the first one is front, I give a substance of pics medical 251 dot sub screen. Where is that from where to do 006 is from zero index to where is where the index is P character so loot index I picture from you the index of CH plus one that it will start from here to even And if you are thinking that it started from zero, it can be set from one. If you are thinking like this, then you do not ask this question, leave one, you need a lot, still let me tell you that first Like in this also it was zero intex turbo zero 12345 6 in its length which is the behavior and those six channels if not then again we loot score looter you word skin tour till here you are all right in it we suffix it another name something You can't even, it's up to you, so now we leave the rest in it, comma till here, then from here till here, we will add it completely, so what is Word or Anxious Calendar, loot, we will show it in it, now we withdrawal. By reversing the function and making it fast, making a history builder is for the fix, A Strange Picture, A Victim, the name of the builders is changed to SB, There is a loot video in schools, A History is completely different, this is the function, there is a way to fix it, Now we have to reverse it, SBI, which is simple, we can do a series by using SB don't use SB, what will happen now, it will reverse, now this dot will reverse now and it will be written from DC also, then we We add all the fees back, curious how to do that and speed for tap and left means adding according to this on this I'm in touch with this is done now this value where is this value in this here this is done and what Will do it, we will butter it, we will return that SBI dot posted that you remove it, let's see, let's run it, the word WhatsApp is Singh's, it is government's loot that we should get the award, loot is here also that one Its index word should not be conductor, we had mixed it here, it was correct, accepted it, now we can be the second test case, thank you so much, now apply it to you.
Reverse Prefix of Word
minimum-speed-to-arrive-on-time
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`. Return _the resulting string_. **Example 1:** **Input:** word = "abcdefd ", ch = "d " **Output:** "dcbaefd " **Explanation:** The first occurrence of "d " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd ". **Example 2:** **Input:** word = "xyxzxe ", ch = "z " **Output:** "zxyxxe " **Explanation:** The first and only occurrence of "z " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe ". **Example 3:** **Input:** word = "abcd ", ch = "z " **Output:** "abcd " **Explanation:** "z " does not exist in word. You should not do any reverse operation, the resulting string is "abcd ". **Constraints:** * `1 <= word.length <= 250` * `word` consists of lowercase English letters. * `ch` is a lowercase English letter.
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Array,Binary Search
Medium
1335,2013,2294
254
all right so are we back hopefully so let me see here welcome hello so here we are um let's go ahead and keep solving some problems um this time around factor combinations let's see if we can solve this one a little faster the last problem i spent about an hour on let's even go faster let's see how fast we do how quickly numbers can be regarded as product of its factors for example 2 by 2 is 8. 2 by 4 is also 8. write a function that takes an integer n and return all possible combinations of its factors may assume that n is always positive factors should be greater than one and less than n excuse me oh boy for one no factors 37 no factors 12 2 and 6 2 and 3 and 4. put 32 2 and 16 2 and 8 2 and 4 two and two four and eight oh no well this is a hard question this is an interesting question um basically it boils down to yeah this is tricky not hard but it's tricky one um doing it efficiently is also really tricky so first things first um factorizing just finding the prime factors of a number in the first place is challenging uh it's very challenging yeah prime factorization is a challenging thing just to begin with um so i don't expect there to be a particularly efficient algorithm for this like i don't know what numbers they're going to give us but i'm assuming the number n is relatively small this gets very hard depending on how large the value of n is um so pretty much for each divisor of n and there's square root of n pairs of these divisors for each divisor of n that you could have you can recurse um and combine for all the different ways you can set up the factors for n so as an example take 32 right and you say okay there's a few different divisors two three doesn't divide six thirty two four and eight um five six seven eight i think but the square root of 32 is uh there's only six is only five yeah so it's actually done right here right two four sixteen and eight and what you do is you say okay take two and sixteen take four and eight recurse on 16 recurse on 8. for 16 you get 2 right square root of 16 is 4 2 and 8. four and four right eight we said and obviously we can memoize the solutions as well so it's slightly more efficient square root of eight is uh i think it's like less than three right it's gotta be less than three so two and four and then obviously three that's really it's just two and four right um so you would take all the solutions for 18 and you would basically append two to the front or append those solutions to 16 on onto a vector containing two and you're not really done yet though for 16 right because 16 then goes to 2 and the solutions for 8 and then 4 and the solutions for four and the solutions for eight are two and four also right which this is just two and two so eight you get um so 8 you get 2 4 as well as 2 to 2 right obviously the number itself um counts so there's a helper here uh it's not quite the recursion exactly the help of recursion is useful because the number itself is not going to be returned but in these recursions the number itself does get returned as a possibility so here you go for eight you get two four and two to two um and so for 16 you get 2 4 2 and then 4 and 4 is uh we said 4 is 2 4 and 2. and then finally 16 we said is so it gets a little confusing but so we have 16 and we have 8 is 2 two and two four and two yeah we'll just yeah two to two and two four and sixteen is two four that's eight there's two of these right and then four two and four um and then we said two in front of 16. so all of these and four in front of eight after all these so 32 gives you one two three four five and then these can be boiled down to you remove all the duplicates plus these other ones 216 and 48. something like this you have five for 32. i missed one two eight right yeah i missed that two and eight for 16. i missed that two and eight and four right so it gets a little funky but uh but that's pretty much it um you want to use sets so that way you would remove any duplicates and then you just dump all these sets into a vector this set of sets we'll say um yeah can you do a set of sets i don't know if that works let's see what happens here yeah okay it works it'll remove the duplicate sets so let's try this and we're going to have x say f standard square root if i if x modulo i zero now we have a divisor now we say four divisor for each divisor you're going to and we have memoize too memorization as well um okay do okay so this is kind of funky but you're gonna do is for each divisor you're going to add your new set that divisor and then you're going to take f of x divided by d and that returns a set of sets that for each set in the that set of sets you're going to um you actually do the other way around do it to create this new set insert d you do it this way really it's done this way now here's a tricky thing it's actually a set of vectors if you do a set of sets the problem with the set of sets is that you can't have duplicates in this set so 2 is not going to work um no that's a mistake so actually i can't just use sets to get rid of duplicates can we do sets of vectors hold on wow all right what do we get here if we do this oh so i was missing something here it wasn't here that was there okay so you can do this it's just oh no oh yeah you can do this um yeah okay all right we're okay we're fine we're just a little uncertain we have to just sort of vectors that's all um okay something like this yeah um so for each divisor we're going to take f of x divided by the divisor need this vector which is a copy of s which is really just a v we'll call it new v i guess and then we push back into new v and we sort that new vector and we insert that new vector into a return set all right and then we return that at the end here um this is going to be a set of vectors of integers and um there's one thing here tricky thing here which is we could probably do this in one we don't need to break this up into two pieces i could probably just you know make this loop here put that loop here um combine these two loops but also something to consider is this should contain this vector should be in this set as well before you return um it's tricky thing but i just want to see if this compiles before we combine this with this i just want to see uh um i don't really need that anymore do we oops okay all right now so this is going to be for each set really could just be you say for um yeah that should be fine what does this look like if we do this all right i thought maybe there was some error there oh okay um what no matching call on oh gotcha forgot okay it compiles it seems to work so we do 10 what do we get two five ten oh yeah okay it looks it works looks like it even works amazing that's what we do is auto result equals recurse of n reverse and then we say result dot remove or delete erase and you just remove that one value at the end that should be it oh um okay let's see if that works here we go um one 132 37 12. let's go see what we do got him all right great um the one thing we need now is we can do this whoops for d in divisors let me just say i don't need these divisors anymore can just say put that if statement right there and repair something um right so yeah um okay i think we just go for it um yeah because it's not going to be efficient no matter what this approach that's interesting okay hey okay doesn't i guess it doesn't have to be efficient but kind of yeah kind of awkward um a little awkward i'll say definitely peg that is rather awkward uses a bit of memory uses recursion uses sets to remove duplicates pretty inefficient thing though pretty inefficient algorithm it'll always be inefficient though that's the thing is like i just happen to know that factorizing numbers is just naturally inefficient so that's got to be just inefficient so sweet done very good on to the next thing here so we'll go ahead and uh and end stream here and say thank you for watching those of you that did um see how long did that take uh yeah half an hour okay it's kind of a good amount of time a fair amount of time yeah that stuff
Factor Combinations
factor-combinations
Numbers can be regarded as the product of their factors. * For example, `8 = 2 x 2 x 2 = 2 x 4`. Given an integer `n`, return _all possible combinations of its factors_. You may return the answer in **any order**. **Note** that the factors should be in the range `[2, n - 1]`. **Example 1:** **Input:** n = 1 **Output:** \[\] **Example 2:** **Input:** n = 12 **Output:** \[\[2,6\],\[3,4\],\[2,2,3\]\] **Example 3:** **Input:** n = 37 **Output:** \[\] **Constraints:** * `1 <= n <= 107`
null
Array,Backtracking
Medium
39
545
guys welcome back right this is horus right here and we just cracked one of the questions that i failed numerous times lead code 545 boundary of binary tree right i've seen this question for the first time it was definitely a couple of months ago it was i think it was even earlier than that was back in you know i think july and then you know and i think i've maybe seen it you know a long time ago definitely this question and um i attempted july this year august again this year failed you know i didn't look at the solution i just you know i just try to crack it you know sort of on my own sometimes for some questions i'll like i'll look a solution to learn but this question i guess i don't know why what i was thinking i was left there i guess as a sort of little test to see like if i'm getting better or am i getting better at you know just data structures and algorithms in general and finally i took an attempt today the whole process took 45 minutes i started with zero code because and then i coded up 45 minutes i was finally able to get the code accepted and beating a single sixty percent of the javascript people which is not bad right um i'll go through my thinking process what's the offer for this question and um i guess just what we could learn you know not just myself you know i think even though they're you know i've learned i think heaps from this one question but maybe for some of the other people watching you know because there i've just found that you know i do have a couple of audience that you know watches my videos so lovely and you know for you to take away what to learn right so without just you know going through any useless stuff and look at the number of likes and dislikes you can also realize this question was not easy right so i think the description is a little bit interesting the boundary of a banner of binary trees companionated roots the left boundary the leaves and the reverse order of the right boundary and they give you a definition of the left boundary is the set of nodes defined by the following then the roots the left children um is in the life boundary if the root does not have enough children then the left boundary is empty so like in this case here this one does not have any left boundary right you might be thinking like does i does the three belong to the left boundary no three and four because they have no children they're actually the leaps and two is the right boundary one's a root if that makes sense right um as we go through right i'll be explaining i guess you know what sort of things you should look out for right so this is i guess just a broad definition right if we look at this one because how we define like each of these nodes um is going to be important i just want to make sure that i'm actually recording yeah i am cool because there are a couple of times definitely that i have not recorded but either way okay let's continue right so we have this for this case right this one's root this two is the left boundary right this four is the leaf seven's the leaf eight is the leave nine's the lead tens elite six and three ah right boundary right five we do not include he's useless right we do not want to return him as the solution and let me tell you guys about it um later on some of the trees that they were throwing at you like this tree right here just you know visualize like what sort of test case they're running is you know overly ridiculous right and i'll be explaining to you all like what this tree has to offer like look at this monstrous tree right like yeah this is a beast of a tree and you know where i picked up essentially right on this test case so let's just keep going so we found the definition the initial attempt um i did in i think it was in july or something was i tried to do with bfs and guess what i failed i completely failed this question i don't even i think it's definitely doable but it's very hard there are a lot of things right and if we look at the i guess tag it does not have bfs right brass for search so it's not really for brass research even though it may seem like it but um like just you know this big tree like you know it's not made for breast first search right and um in terms of i guess dfs right how are we going to be approaching this question just in dfs manner well if we think about it right the question like after you've got to read through this character actually truly understand what a left boundary is because a lot of hate in the comments saying that this question is so bad like i used to hide it as well and i'm definitely gonna leave it like this right you know i'm you know whatever but you know we need to understand right and going through these examples like i think is helpful but you know they are definitely a lot more complicated examples right so intuitively we know that if we traverse the trees three times right first of all we fetch out all the leaves right we add it into a list and then we'll add the left boundary in front of the leads right and we add the right boundary behind the leaves we should be good right if you wanted to add in front of the uh array or list or whatever array list i think i use linklist in this case but you know you can use arraylist as well you can add to the start of a link list right and you can add to the end so i guess this is why i've essentially chosen this data structure so cool this is this was my sort of you know thinking this time going into i've decided to take this approach where i'm going to traverse the trees three times right i believe you can only you can do one past but you need to i don't know you could be pretty smart to come up with that like you need to be thanks smart right i don't think i'm dumb and yet i definitely struggle with this question right so let's keep going so everything so far i think is pretty understandable right so we use a obviously a backtracking sort of algorithm and doesn't return anything is that you know when the nodes left children and right children are both new that's gonna be um we're gonna be adding it to the list right and we wanted to do this in an order where it goes from left to right so this i think essentially if we check i think if we just go in the order of node.left order of node.left order of node.left and then note the right i think this guarantees a um a left to right sort of order because if we think about it you know we obviously and by the way what you feed into the fine leave i think is his note right so basically first of all you'll go to the left when there's nothing exist and you'll go back into the call stack and you'll keep going left and just through and you're not saying this then you go right essentially this guarantees i guess the leaves are in 478 910 right so this is what we have so far right so i guess cool but the return like you know we have this so far we've got to add one um one two right but one's a root will deal with it last right so essentially what we have on our left of for example two on the left boundary is really the two so the leave is the easiest find left right so i guess again you know the way i did it and i'm not saying this is a good way right this is one way and i think it's not that hard to come up with it right like i legit came up with a like on the thought right is that um because we're inserting in front of what we have right so if we have more than one right then first of all we insert this two and we insert anything that's sort of we insert two right at the beginning of the list and we insert anything that sort of goes after two for example if this four has whatever children we would insert this four after this two this requires an index right an extra little thing right you know because we cannot just you know append the start otherwise it'll become two and two four right we want it'll become four two we won't we want two four right so this is pretty straightforward this part you know if you think about it right so again and this flag so what does this flag do right flag is a global parameter if we look i'll have two flags now i'll explain what each flag does also we have a um duplicates hash set to make sure because essentially we can say you know four technically is part of the left boundary as well but since we've added the leaves in first so if we i guess if we encounter this four again you know he's already in it i guess he will be you know he will be yeah basically this just basically prevents duplicate right if we think about it you know this three technically we could consider it as a lap boundary i guess some sort but it's also leaf so once it's added into the answer list we also add it into the hash set so that i guess we prevent duplicate right this part is also not too bad i think so um let's keep going right what am i up to here okay let's okay go okay that's you know let's move this out of the way so far left essentially we wanted what we want okay what is useful to us in this case like you know and is we actually we just want this part here right because essentially what you could do is if there is no left children from the root you don't even pass in anything there's nothing on the left right you just consider that as you know nothing and you would always you know like for this tree here you know we'll deal with this whole lot in the you know right so to find right leaf sort of thing but you know for now let's say we put in a tree you know the live children are root into this function right essentially what is useful to us believe it or not is this little pass here right from the two to four that's the only useful one to us you know the rest you know are like i don't know these and these are useless to us right we actually don't need them so i guess how we're gonna be doing it is we want to find all the notes as essentially you know the first sort of leaf note we reach that's most towards the left right we want essentially every node on that pass you know unless it's being duplicated before right as in it's a leaf so we want every node along this pass because the tree what happens you know just in case right while we have this flag or whatever is in case let's say you know um how would i be able to say it like i don't know just it's hard to describe but um just in case i guess if you have some sort of weird saying to it right um because if you know to the left children if it has it doesn't have this four right it has to go searching the right and if this four does not exist then i guess we would be returning two five seven if you get what i mean as a left boundary right because this four doesn't exist so in the case of this right essentially i guess the first sort of leaf node or in this case is this four because this four does exist right the first leap node we reach that's most towards the left right we'll flip the flag so in case because we will traverse through the whole tree you know it's a dfs right it will traverse through the whole tree and we don't want to be adding stuff like the five into it right so it's before this flag before we reach this floor everything will add in after we flip the flag we will traverse through the whole tree right i mean unless you have a way of just you know not traversing but i guess you have you know in this case i this code i've written traverses through the whole thing right but we don't want to be adding i guess essentially the five or these seven or the you know we don't be adding any anything else right these are not relevant to us i mean if we don't have this four that's this five and seven is relevant but in the in this case we do then we do not want to be adding this five or the seven you know it's not good so after we flip the flag i guess then we don't add anything else so this is what this part does is because we're going from top down right so once we've sort of reached the leave now that's most towards the left you know essentially we already have a pass and then after that you know basically anything else we ignore right we don't add and that's it you know yeah i guess yeah and of course the way we add his answer is a linked list and we will be adding to the index of you know because again it's like you know if we wanted to add if there's four has you know two children's right the way we visit is gonna be we're gonna be visiting two first and then visiting four but if we just add to the start right you the scene will become four two you know blah but we want two four right as i mentioned previously so through you know every time i guess next time you call it'll be index plus one so i think that's really about it yep clear all drawings right let's move on so this is essentially fine that this is not i guess the worst part comes in fine right you cannot do what we just did for fun lab imagine oh fight lab we do this fight right because this is the irritating part of this question right is that they want for the right they want the reversal so i guess we have a couple of choices it's either we put we create a new stack for the right i would push everything to the stack and we pop it out right that's one way but i guess we're using you know i think there's a better way at least i was thinking of this better way we could have done that's definitely totally valid and i definitely like that approach as well we're using a stack definitely utilizing the data structure but you know the way we do if let's just say if we did it exactly the same as we did for this right it would have worked if you think about it and later on in that big tree case i'll tell you like why it didn't work because i was lazy i tried to copy you know fine laughter and just modify a little bit doesn't work right first of all the order of traversing is different right because this time we wanted to find i guess the most right essentially instead of you know visiting i guess calling recursion on the left part first we're going to be calling it on the right part that's you know the difference and if you look at this one it returns a boolean so it's not a backtracking it's not top down it's bottom up um let me tell you about it right so essentially i guess the strategy will be utilizing right is because by this stage we would have added everything on the left and all the leaves right we would have to all we need is pretty much these nodes and we deal with the root loss right so we don't care about the root all we have are these notes right if we look at that i guess just humongous tree right that tree was huge let's have a look at it right essentially we've added i guess you know everything on the left and all these i guess all these little children and um however many we have and you know i mean if we look at it this is sort of the right sort of sub tree right essentially we wanted to be add adding stuff that's in the right subtree but in reverse order and we certainly don't want to be adding like cases like this 27 here if you're thinking about one way i was doing before was i was saying that you know if the parent um if it has no right children then the black children is the sort of the right boundary right you know because we're feeding in the right sub tree right so essentially we're in this function right here we're feeding in um if you look later on right we're feeding in this i should have picked a white pen let's go with this we're feeding this whole thing right and with my logic was i the pirate's parents level it would know and i was trying to pass in like you know a couple of flags if it has you know a right children then this note would definitely not be you know yes will not be part of the right boundary if that makes sense right it's only this one here but then why it failed on you know just this case was if we look at you know this one here right it's 27 it has nothing on the right but it's not a leave and it's not the right boundary right 11 is and we have you know 60 that's on the same level that's two words or right of it and we have 74 right this but it doesn't know that it has all these right it doesn't know it you know like it's apparent you know i think essentially you know doesn't know it's grandparent do you know but the grandparent needs the information passed all the way so this is a tricky part right so you cannot approach it like this right you instead you've got to do bottom up pure recursion you know bottom up dfs essentially so i'll be going through is how we did it right is you know we still have the same sort of flag right but when do we flip the flag if we think about it right remember how we're able to because you know how we're able to know if you know i guess because the dfs will again like i would do with a tree right the dfs was running on here right essentially it how it's gonna traverse is it's gonna go like this and then it's gonna go like this right once we've reached sort of the leaf node the leaf level right the most you know bottom sort of thing right and then we flip the flag right we flip the flag and we return true right and for the second sort of leaf we have right since the flag has already been flipped it will return false and how would we know if a node is you know on the is you know part of the past of the most right sort of track right how would the six now right if any of his children guys if we think about it right it has two children right so if any of his children returns are true it must be part of the past right and if three has you know two children if any of his children you know is you know i think then it will return you know it will be true as well and it will go all the way up to where the top is right this is exactly how this approach did it right this first of all we set both of these i guess flags to false and um you know we call this recursion it will return value because after running through the bottom it will go back up um and um we utilize these values i guess and i'm obviously depending on you know i guess we only add it if you know either his left children or his right children returns are true or try to end you know it's it doesn't contain right then we i guess we return true and we return back to our parents you know based on the value that we got from our two child you know whether or not you know we are part of the most of the right parts and the parent you know obviously he reports to his parents and vice versa and how yeah and then at the end we add the root lost so yep that is all there is to it to this question right so essentially the code is yeah it's not short and we would have to do it like this right i believe um the official solution right is did it yeah some sort of using pre-order traversal accepted of using pre-order traversal accepted of using pre-order traversal accepted right yeah they essentially if you look you know live left child flag right child flag pre-order traversal this and that flag pre-order traversal this and that flag pre-order traversal this and that you know it's a very similar approach i think to in terms of thinking wise to what we did is just we did you know three you know sort of traversals on the whole tree right yeah and that is all there is to it and they probably try to go for one traversal with all sorts of different flags and imagine you know obviously you know like priorities over each other like if the scene is also left boundary but it's also i guess a what up what would i call a leaf nut right then i guess it is you know it is a leaf note over a um sort of black boundary or right boundary and if you're not seeing is a lab boundary meanwhile it's also right boundary meanwhile it's also a link leave note it takes over the priority right so this is i think this is essentially what the official solution is trying to do but you know either way this is i guess my attempt to this question and um yeah this is my solution and i think there is definitely a lot to learn in this question is that just you know the ordering of you know return you know i guess essentially forces me to either use a stack or to use a completely different type of recursion rights this void doesn't return anything but this one you know we have to based on what the children you know give back and we'll have to muck around with that but um either way yep this is my solution to it i think it's a pretty damn good solution and um yep i do indeed thank you very much for watching and um i'll probably do another video of something similar to this um yeah later on right but yeah thank you for watching
Boundary of Binary Tree
boundary-of-binary-tree
The **boundary** of a binary tree is the concatenation of the **root**, the **left boundary**, the **leaves** ordered from left-to-right, and the **reverse order** of the **right boundary**. The **left boundary** is the set of nodes defined by the following: * The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is **empty**. * If a node in the left boundary and has a left child, then the left child is in the left boundary. * If a node is in the left boundary, has **no** left child, but has a right child, then the right child is in the left boundary. * The leftmost leaf is **not** in the left boundary. The **right boundary** is similar to the **left boundary**, except it is the right side of the root's right subtree. Again, the leaf is **not** part of the **right boundary**, and the **right boundary** is empty if the root does not have a right child. The **leaves** are nodes that do not have any children. For this problem, the root is **not** a leaf. Given the `root` of a binary tree, return _the values of its **boundary**_. **Example 1:** **Input:** root = \[1,null,2,3,4\] **Output:** \[1,3,4,2\] **Explanation:** - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root's right child 2 -> 4. 4 is a leaf, so the right boundary is \[2\]. - The leaves from left to right are \[3,4\]. Concatenating everything results in \[1\] + \[\] + \[3,4\] + \[2\] = \[1,3,4,2\]. **Example 2:** **Input:** root = \[1,2,3,4,5,6,null,null,null,7,8,9,10\] **Output:** \[1,2,4,7,8,9,10,6,3\] **Explanation:** - The left boundary follows the path starting from the root's left child 2 -> 4. 4 is a leaf, so the left boundary is \[2\]. - The right boundary follows the path starting from the root's right child 3 -> 6 -> 10. 10 is a leaf, so the right boundary is \[3,6\], and in reverse order is \[6,3\]. - The leaves from left to right are \[4,7,8,9,10\]. Concatenating everything results in \[1\] + \[2\] + \[4,7,8,9,10\] + \[6,3\] = \[1,2,4,7,8,9,10,6,3\]. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
199
752
That a Hello Everyone Welcome to Taste Voter List Challenge and Asked Questions Open the Lock in These Questions Were Giving Unlock the Train List from Wishes Staff and Jewels in Both Directions from November 1999 That All Should They Give in Few States of the Will You Can't Movie On Date Of The Free Riders Tube School Me To The Number Of The Stones Now Input 1 In Odis The Great Spring That From The Missions 2000 Going After The Target And In It's Not Possible Vitamin - Target And In It's Not Possible Vitamin - Target And In It's Not Possible Vitamin - Mind Withdrawal Point But Don't Worry It Will Reduce Problem Very Simple Us Zor Will Also Be Noted Subscribe That Let's Get Started Unlimited Slideshow Pick Up In The Air A Liquid 752 Open The Lock The Events For Going After Dasha Chal Problem Police Tried To Simplify Ramna Lock Which Only Rs.1 Starting State Of The Lock Which Only Rs.1 Starting State Of The Lock Which Only Rs.1 Starting State Of The Box Victims Were Identified Kaliyuga subscribe Video This Three Do Subscribe Our Video 45 subscribe and subscribe An excerpt Let's start hydration using face approach What they want you will create you are you will win that things spread into the set that aunty etc all the wells setting off The first president of element from both directions are void within next two drops loot lo that and welcomes one hai to dushman this post level and that two elements in your life will create withdrawal that sacrifice with oo a plus continue to practice now hown exactly the opposite Money from acute and reddy to end 05 2012 are next will blow out elements in 100 billion are two states one in against sexual election in law of attraction at will be i am now rohan notification wa peeth video body part tweet set follow rates e want you sticks From middle of wave updated on one part stomach and next level which comes to have one unique two elements till time you and same list opinion and generate next this elements unless you to will generate ten posts 153 a 153 lift subscribe to the recent Interpress Brigade 80 From Different Directions Given In 98100 President Ki Sudarshan Jain And Hold To 8 Se Z F Ki Naav Heart's Weakness Line That's Only One Element Solute Element 70 60 More Profit 2016 Video Subscribe Ek Seal Artwork Pintu Dedh-Dedh Comes for Ek Seal Artwork Pintu Dedh-Dedh Comes for Ek Seal Artwork Pintu Dedh-Dedh Comes for that now dena jholi one element and will not sit back and with that I just love 86 from acute and six cold and flu in both directions for negative subscribe Video subscribe our so come I discovered this creative and now going back to the question that So many explanations for monitoring all together in the spirit of single horoscope cases from 0 1 0 that the possibility is good b0 p0 l0 subscribe 19 90 within the next b0 last week 1000 note so I hop 2030 generation logic therefore to your music teachings. Updating 10 Direction Speaker Dr I just by extending the previous logic to give this extension and will be able to arrive at solution so let's talk about how will I get distracted from all 000 to 11005 120 to 1201 0210 to 202 Let's Who Is This Logics Creative And Its Something Still Unclear Tips Understanding Food In Section Or How To Turn His Need For Tourists Reporting Lagao Song Define Visit Set Details To All The States Of The Longest Aged Fast And Check Weather Target Is Note 800 Se 1000 Video Subscribe You All Subscribe To Connect With Different You Website Generate Spring And Finally Bigg Boss Looted In This Zoom Develop Into A Few Vs Wild The Video then subscribe to the Video then subscribe to subscribe our Who Is The 10 Conditions Mention That Means Of Brinjal Target Vol Interested In This Will Give Winners And Ajit Bhai Ay Jatt All The Next Step From Current State Of The Lord Will Talk To Avoid All Possible Efforts In President With Us That Art Mighty And Daughter And Current Will Return Update Midnight's Contract Fear Of This Billu and Intermediate Level Dust and Acid - Intermediate Level Dust and Acid - Intermediate Level Dust and Acid - Subscribe Ka Idea 60 Are Converted Amazon Elections and Intellect Are Abductive Virwal Ko E Want Is Extracted Current Character Calculated Virval To 9 Idi Is Vansh Do I A Bid To Correct The Log In to my new lots of hearts eggs similar thing drops anti clockwise traction this remedy character i'll go to 9 inch york and subscribe * lots of co * lots of co * lots of co arrest system hai to clips a train from a distance that accepted that MP watching the video Open John David Please Don't Forget To Like Share And Subscribe Channel Agni Hai
Open the Lock
ip-to-cidr
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot. The lock initially starts at `'0000'`, a string representing the state of the 4 wheels. You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. **Example 1:** **Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 " **Output:** 6 **Explanation:** A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ". Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102 ". **Example 2:** **Input:** deadends = \[ "8888 "\], target = "0009 " **Output:** 1 **Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ". **Example 3:** **Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 " **Output:** -1 **Explanation:** We cannot reach the target without getting stuck. **Constraints:** * `1 <= deadends.length <= 500` * `deadends[i].length == 4` * `target.length == 4` * target **will not be** in the list `deadends`. * `target` and `deadends[i]` consist of digits only.
Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n.
String,Bit Manipulation
Medium
93,468
766
hey what's up guys John here again so today let's take a look at another lead called the problem number 766 top please matrix and a matrix is top please if every diagonal from top left to bottom right has the same element all right so for example this one 1 right 1 2 3 5 and yeah this is select pretty straight okay I'm gonna give it my own ball to make it forty trees here so basically there are two ways of doing this problem right so you know for a diagonal one thing you guys need to know that is the I minor straight it's the same across all the values on the same diagonal right because 0 2 &amp; 4 that we can use a because 0 2 &amp; 4 that we can use a because 0 2 &amp; 4 that we can use a hash map and then use a hash map to store for every time right every time when we see a new CI NJ we compare the values with stores in the hash map right if the hash map if the vital stores in the hash map is the same I minus J it's not the same as a current value then we know ok so this is not a valid one right but if to do that which we also need to do a the to look through everything right and the time complexity for that for this is like Oh M times n right and the space compressed is the same right because we also need to I'm times n place to store everything for hash map right and so another easier ways that if you notice here even notice that so we if you're on the second roll here right and you see so you can simply compare the current one which the user one on the previous row right you compare this one with the previous or while the previous column we you could also compare this 2 with this 2 right same thing for 3 &amp; 3 and this and then same thing for 3 &amp; 3 and this and then same thing for 3 &amp; 3 and this and then when you like the third role here the same thing right you compare this file is the previous one 5 1 2 &amp; 2 file is the previous one 5 1 2 &amp; 2 file is the previous one 5 1 2 &amp; 2 so you can just simply compare row by row ok so that's how I'm gonna implement this problem today so let's take a look here so first I'm gonna do a matrix right so pretty straightforward and for I in range so 1m right so why because we want to start with the second row right with the first row there's nothing we can compare that's why we want to start with a at the second row and for each row we also want to start with the second column right because the first column we don't care right on a new row we always want to start with the second column so that we can trigger go back to the previous row and previous column and we simple do a check here if the matrix right if the current value if it's not does not equal to the first row and the previous column value I'm sorry I minus 1 I minus J minus 1 right then we simply return false right and if everything is fine we will just return true okay right let's run it core so the work so even though it's a easy problem the reason I want to talk about this today is about these two follow-ups here today is about these two follow-ups here today is about these two follow-ups here you know so they are they're likely to interesting follow-up questions so the interesting follow-up questions so the interesting follow-up questions so the first one is the if the metric is stored on the disk and the memory is limited such that you can only load at most one row of the matrix into the memory at once so how what I going to do right let's think about this one and I would talk about the follow-up and I would talk about the follow-up and I would talk about the follow-up number to later on so basically since as you can see as you guys can see here we are relying on basically we're relying on at least two rows to do the comparison right but the limitation is that you can only load at most one row to the 2dr to the memory right so that basically if you load the first row into the memories and when you add the second row here you don't have the reference for the previous row right then how can we solve it right so for the follow-up we solve it right so for the follow-up we solve it right so for the follow-up one what I think one way out is DL we load half of the first row and half of the second row right because even though we know for the second row here you know first half a row first offset second half of the second row sorry the half of the first row and half of second row so that we can compare this half Rho for the third we can basically do the comparison half by half right we load those two halves and we do the comparison and then we compare this half again even though we have to maybe to think about some corner cases like the ones finishing comparisons we have to store this like the last element of the first half Rho 2 a like global variable somewhere so that when we start a comparisons we of the second half we can use that global variables to start with the comparison right okay so that's that right basically if only allow to allow the windrow we reload half of the first row and half of second row and we keep loading it until we have load everything all right and then the second one is this it's very second follow-up it's very second follow-up it's very second follow-up it's very interesting so if even if you can even load on one row at a time right if the metric is so large that you can only load up a partial Rho into the memory at once so how can you do that right basically see it seems to like it ask you to process the role piece by piece right so how can you do that right so in order to do that we can use like a concept called rolling mat hash rolling hash so the rolling hash what it does is yeah it's every time you can you see the new car new values here right you use the previously hashed value plus the current value to make a new hash value so basically what this one does is like you we also we start basing we have two pointers here pointer one here for the first row and pointer to pointer two for the second one since the table since the road is too large we cannot store everything that's why we use a hash basically we hash everything we have seen so far and then every time we got a new hash we compare alright so basically let's say for example for the first row and second row here so that the first hash map the first hashing values is one so first it's one and we reach to the hash tomato is one plus two and we reach two three we use the old hash from and then the second pointer is on second or is here and here right basically every time we use the second hash second and set the new heights from second row to compare is the old hash of the first row all right and both rows and will also will be there will be both using the rolling hash to compare the only difference that is we correctly calculates the new rolling hash on it for a second row first and then before compared before computing the first row strolling new rolling hash we use the new rolling highest for the second row to compare is the old rolling hash from the first row alright so and then we keep going forward until we finish everything right and since the rolling hash is just like a hash values it won't takes up no matter how long this how big how long this like this the row is it doesn't really matter because we're only storing the current rolling hash for two rows right that's how you can solve the second follow-up question can solve the second follow-up question can solve the second follow-up question okay I think that yeah that's does everything want to talk about for this so please matrix problem your problem is pretty interesting yeah you guys if you guys are interested in the rolling hash implementations you can find some wiki page and take a look at your own interest you know basically this is this rolling hash it's just a like an efficient way of doing the string comparison while storing saving some extra space cool I think that's it all right thanks so much for in the video and stay tuned I'll be seeing you guys soon bye
Toeplitz Matrix
flatten-a-multilevel-doubly-linked-list
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Linked List,Depth-First Search,Doubly-Linked List
Medium
114,1796
95
hi everyone in today's challenge we are going to solve this problem the problem in unique binary search tree part 2 and the problem number is nine five all right guys so first of all what we are going to do we are going to clearly understand the problem statement after understanding the problem statement then we will move to the logic bar in the logic part we are going to see how we can solve this problem but in the logic we are going to use to solve this problem so after understanding the logic part then we will move to the implementation part and in the implementation part we are going to implement the logic in Python C plus Java and JavaScript programming language fine guys and guys if you want to have a look on the solution which I am going to write in this video for python C plus Javan JavaScript program language I will share the link in the description you can go through that particular link and you can find all the solution right fine now let's see what this problem say so let's understand the problem statement right so problem says given the integer n written all the structurally unique DSP means binary search stream which is exactly unknown of unique value from 1 to n written the answer in any order Simple Thing guys we are given first of all and only we are given one input into one input that is integer and that is nothing but have available name and right now we need to find pool then unique binary system which we can which let me just first of all show you here so we need to find first of all the unique bonus HD which contain nodes from 1 to n that makes sense right which contain nodes from 1 to n means if there is any three that means we need to find all the unique bonuses to be where we can have one node two more and three node right there should be exactly node with one two and three value right means range of one to N I hope it makes sense right after that we need to run all these unique binary simple right but I know you may not get this particular statement so let's understand with the example so in the first example we have nothing but n is three right you can see in the first example so they have written as five bonuses today so we can make five unique bonuses uh binary with exactly three node and where nodes are coming like one two and three so you can see the example the first way of making a unique one SST is nothing 1 at the root node third is the right node and then two is the left of third right and the second way nothing one is the root node again but two now this time on the right node and three also right of two right you can see this is right so if you don't know let me just tell you one more thing if you don't know what is your binary system means a root node if you have a root node then left side always will be less than this node and right side will always be greater than this rule right so hey if you will see the structure in this first three example uh Dynam we can see that two if we are taking two as root node so left side is always a less than of two and right side is always a greater than two right same in for example you can see three if we consider three as a root node so left hand side should be also always less than this three right so you can see two Which is less than three then one which is less than two right and we are considering again a three node and then you can see we have taken a left node one so that means nothing we cannot write to here right because now 2 will be greater than one so we have right in the right side of course you can see if you will focus it too which is greater than one but it is a less than three right so that means it come on the left part of three but it should not come with left one it should be common right so we find five possibilities right we find five unit minus St where uh all the bonuses we have exactly three node and the range is nothing but the value of unique nodes is one two and three right it makes sense right so we have to return all these node we don't have to return the count we have to and all these nodes so how we can do this we will see in the logic button but for now I hope you understood the problem statement so let's see the second example and in the second example we have nothing but we can see let me just scroll it later foreign state with exactly nodes and all the node value varies from one to n right and all the node values should come right means one to one should be present in that particular by itself fine with make sense right now guys let's see how we can get all the minus HD right all the unique minus St of exactly naught logic is going to be nearly easy if you have seen my last I don't remember the problem name was all possible quantity right so if you have seen that problem which is similar to that nothing changes small one line of condition will change nothing but exactly gonna be same right let me show you how it gonna work from scratch right maybe you have not seen that particular problem so what I'm going to do I'm going to say okay so I'm gonna give an example of this first example only n is equal to three so we are going to see how we can get all these five node right all these five unique minus history where n is three so if you understood this that means you can create a visualization for n is equal to five six seven eight as well right and see guys one more thing now constraint here is nothing but n will know more than uh we can say a right n will always be less than or equal to X and it will never be more than eight right fine this makes sense like we can use a approach like n square right and Q as well fine that makes sense so what we can do now guys n is equal to 3 right so n is equal to 3 that means nothing but we need to find all the unique minus is T with exactly which have exactly node means three node right so what we can do we can simply select n is equal to three right so what I can say here I am going to say here I need a more space so here I can say first time I'm gonna put for one second name I'm gonna put uh I'm gonna put as a three numbers because I have n is equal to 3 right so my range is so now again I'm gonna move this I'm going to say my name is going to vary over here the thing which is going to vary is nothing but uh start in it so currently my range is one two three right I hope it makes sense right I need all the minus HD which should have exactly one two and three nodes right that makes sense right miss this makes sense right I hope so now what I can do I can say let's keep one as a root note that keep two as a root note first time uh electric three is low I can make any one as a root note right because I have the range one two three right fine now if I am taking a one Edge root node so I have told you already what is binary system here left side always been less than the root note right side will always be greater than the root number so if I am taking a one as a root note so left side will always be less than one and you know that we have a n one two three right initially we have it in one two and three so I can see there is nothing left on there is no number present Which is less than one right so I'm going to say it is but right side we have something let's say we have now two numbers two and things so I'm going to say I said we have two three same goes for two so if I am taking a two as a root note so what are the number which is less than two that is one only so the left range is going to be one foreign having exactly three node with one two and three right I hope it makes sense now what we are going to do we are going to say fine we got this let me just make it and now if we are taking a three as a root zone so you know that left side is going to be always less than three so you can see we have two range right one two one and two I hope it makes sense right so for now you have understood the first uh we can see the level the first level what we have done we have put all the node as one two and three as a root no and then we have seen what is the left what are the number which can go in the left side what are the number which come on the right side right so left side there is only one number so we have no pass anyway we have this password number one and here three and six so on four three right now let's see the second browser which will help you to understand the question how recursion gonna work so I'm gonna Defender just to learn so second is not good hours again so we can say fine but two comma three can be troubles right one two three we can say this is the same function which we have just troubles so again I'm going to put two as a root node here right I hope it makes sense right if I'm putting it together root node so but I can say now in my two and three so if I'm putting a two as a root notes the number which is less than two should be come on the left side but you can see there is no number left right is there any number less than two no there's no number lesson right but this number uh greater than two so we are going to put three on the right side same goes for 3 is uh we are going to put a number less than which one less than two plus then you can see we have a number only two we have a number which is less than two but there is no number on the uh greater than one so we are going to put null on the right side same right so now guys if you focus on this part just try to focus on this part you can see we go to uh minus system here how so if I just make a p here so guys initially one was there then we go to null on this side but here we have a two root node first M2 at cm foreign and here we go to and in the example we will focus here we have two binary with the root node one so that means we have covered three diagram making a sense right so we have covered three diagrams now let's move to the head so we have sorted for the first and second node now let's move all these things sorry guys so here what I'm going to do I'm going to say again we have sorted for one two we don't need to Traverse because you can see we have only one node fine but for three we need to reverse because we have one range here same guys if he has written we can say one can be root node or two can be rooted right if one is a root node so we can put two on the right side and left side there is two as a root node so we know that there is a number present less than one and less than two is one so we're gonna put one on the left side and write some Islam so if you'll Focus here this is also one we can see we got two one into minus 30 here with the three node right three as a routine you can see if I put three here then I have a uh right side null here but left side we have either one or let me make another tree with the two okay because there could be on the left side there could be two no right one or two right if there's one then we can say right side of two if there's two then left side one so this network we can say two possible with a three node three other root no right so that means that would be good these two possible minus City and we can see this is also present on the this side right you can see this side so that means we have got all the five diagrams right now so I hope guys now you understood the logic part but actually we have to do we have to just make a one equation function where we are maintaining a start and end so you can see if we are making start again we have to travel still from Star to n and we have to keep all the node as a root node so here one two three where we start rain we start and end this so we have put one two and three as a group then we have to check how many what um how many numbers we have in less than one and how many number we have less are greater than one we have to put on the left side and let's say if we are getting a green array then we have to keep dropping all this function right simple thing nothing makes sense so the question base conditions when you start is greater than n and if you can see guys here one and this way so let me just highlight here one so here why I have written that because I know if I'm going to pass something here that will match with this consists start will always be greater than n right I hope it makes sense so now let's move to the implementation let's see how we can implement this condition right implement this music so as I tell you like so what I'm gonna do I'm going to Define one function so where I'm going to maintain start and end right so what I can say if start is better than so I have to return but I've written uh simply a function with the network let's say none right I have written this one fine but if your stat is not greater than n that means we have some range like if we have some range so what we can do we can start over only three for a range of start comma n plus one y n plus 1 because I want to take three number as well if I have is one two three then I want to take one two and three as well right so I take n plus one fine now after that I'm going to know I'm gonna say for left side you have to calculate here starting will be one two the number this minus one so this is f 1 0 1 comma zero right this image started and one to zero and you can see start is greater than start was one and N is zero so start is greater than n so we have to return none right so we are right angular and similarly what is the range of four right side will be greater than one plus one is two the N part three so same thing I'm going to say right side we have a soul and here going to be I plus 1 to n why I have taken I is a root note right so I have to remove I from this range as well I have removed I from this window because I is a root note so once this is calculated we are going to say four all right so for left node in left side or right node in right side I'm going to say create in root node root is economy 3 node and here I'm going to pass our I so now I have created a root node with I so you can see here with the one because I have skipped here as well on the left and right way now I have created I can say root of left is your left side and left node foreign it makes sense right let's have to submit this code Simple Thing guys I hope it makes sense you can see that we've got another right side is not defined why it's not defined left side right side I forgot to put H here all right so it's my bad let's see and it's taking a Time definitely you're gonna give a right answer right I want to see what's taking it this much time so do we are getting a none type is not a terrible so what I've done here I have the Run type is not iterable so see guys we have started and if start is greater than n we have created nothing but all right so the issue is nothing but guys I haven't written this result it's my bad I don't know what I am doing here now let's see so written result now it's gonna pass it you can see guys both addresses password so we have to return it right so that next question call can take this particular number right fine you can see guys it's successfully got submitted now let's move to the next programming language and then C plus and here first of all we are going to Define one function sold so let me definitely have one function soon and that data type is going to be at the same background uh tree node the name is sold and here I'm going to pass start and right and after that I can say start is greater than n so what you can say written what you're going to do first of all I have to Define this everything as I'm going to return a vector of three node so let me Define here only three node the name is designed so I'm going to say before returning result load we can say add node ad we can say pushback right push back no so we can send lpdr after that you can say result return result right return fine now guys I can increase the size right so I am saying that guys if start is not greater than end right that means nothing but we can say if study is not greater than result then we can simply move to all the possible Bluetooth right so we have to take all the nodes which in that given name so we can say 4 into is equal to we can see Star and I less than equal to n support I plus 1 2 N so this is going to be for the right side fine so now I am going to say assign this whole thing into a photo left side I know the data type but you must know the data before writing Auto hit that data type is going to be better P node star like but for now I'm gonna write only Auto right side I hope it makes sense so let me do this little fast here because you know all these things right this is a busy so what I can see I can save all right so we put left and right side so I'm going to say for left note right so I can see for auto left node Auto right node in our right side so we are going to talk about the right side and after that we are going to create a new nodes because if we know root is going to be nothing but new three node and here we're going to pass our I so disable root node I and after that all these nodes we are going to send our left and right root of that is foreign so what I've done here I have to find a root node and after I have assigned them left and right chain once this is done after that we are going to say so let's open that we have to put in our result push no push back right now let's call this function here with this range of 1 to n and later whatever the output they are going to give so return that now let's see what this is the final known Simple Thing guys we take over the left side and all the right side we have tower all the net possibilities that possibilities then we have done this part and let me show you the example here as well so you can see that we taken the one as root one but here we go to because if we go to possibility 2 and 3 as you know this right now right so one time we have pushed two one time we have Push three right so the same thing we are using here now let's try to submit this port Java and in the Java I am going to say polar function solve with a range of 1 to n and here then return whatever the solution so let's define our sole function so I'm going to say okay list and in uh tree node and here we can see what we are going to say we are going to see our soul function right sold in the star let me get in Note 8 fine here you can see if our star is greater than n so we can say what we have to do nothing we have to first of all add none and then we have created this pizza but the result is one result is nothing but list of T naught right so list of two we know and here we can see results New additives right I hope it makes sense fine but if stat is not greater than n that means we have some range so we are going to go to all the possible name for inters equal to Star I less than equal to end I plus we are going to assign each as a root node right so we have also fine I'm gonna take you as a root note so what I'm going to say and right side as we know now right side is sold I plus 1 to start right after that once we got all the left and right possibilities we are going to Traverse all these portions we can say four three node left node website for three node right side and root of right is going to be like right so why it has no taken let's see that water as well so let's still work this one so we have given a i plus 1 start right that's why it's not taking the right side we have to pass foreign language and here in the JavaScript what we are going to do we are going to say first of all uh Define one function const sold as this is Javascript we can understand easy when here we are going to take a start and end once we have done this part we are going to see what we are going to say nothing but fine we are going to see if start is greater than n so what you are going to do you are going to say return first of all you have to result dot push you have to return and then you have to return result fine so let me put the same column as well right almost this again then what we are going to do we are going to say fine now if star is not greater than n that means we have some range varied range so we are going to go to all the rails so that is equal to Star I less than equal to end up and I'm going to say fine if I go to the screen then I'm going to convert left side and right side so I can say left side this one is sold start to my minus 1 and right side is going to solve and I plus 1 to start a note star we can say end so once we go to left and right side so we pass our valid ring both now after getting a left and right side then what we are going to do all the possible all the roads which you have left and right side make all the combination so we are going to say for each left side foreign right once this is done we are going to call this function uh we can see let's pull this function sold 0 or not 0 1 to n with an A and after that return whatever this function return right and let's see where this is the final goes so I have questions should work right but we got an error right side is not present light node is right okay fine let's see now for future work right let's see so you can see guys both the desk is password selected submit this code and let's see what this is getting personal and you can see guys it's just simply got some meter right so we have this uh done the implementation with python C plus Java JavaScript programming language I hope you understood the implementation part except any kind of doubt in the problem understanding part 2 implementation part you can directly write in the comment section I'm gonna I'm always there to help you right so if you learn something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
162
hi let's talk about find peak element so find peak elements question is pretty straightforward so uh the pick element is the greatest in array and you are going to use the login method so when you see the login right you are not going to traverse every single element in the array so you need a middle value um like binary search right you take the middle value from to pointer right so i'm going to just talk about the example here so you need 2.0 which is your left and right 2.0 which is your left and right 2.0 which is your left and right and you need another value called middle so the middle will be equal to left plus right minus left divided by two so um when you find the middle right you just compare the middle itself and plus one so you will know that we're trying square and then you keep moving so for this example one two three one l and right allow for a zero r for the end and for the uh index one because zero plus three minus zero divided by two is one now i compare what should i compute i should compare the middle and middle plus one so which one is greater three is greater right when three is greater than i have to move my left pointer to here and then the right point is still the same line now i'm going to do a calculation again if i have the same uh different pointer so this is two right two plus three minus two so it's one divided by two so it's zero so two right so middle become two meter become two i now let's check again uh m and n plus one which is one right three is not less if three is not greater than one so uh you move the left pointer uh right pointer uh back to the middle so when you see uh left and right it's at the same index you break out okay i'm just quickly talk about another one so left right the middle is right here right now that computer middle itself and the plus line so three plus three and five right the three is less than five so i move the left pointer all right now right pointer doesn't move so i have another middle uh if i have a new left right so this is my middle and computer full so it's not right so when it's not i move the red pointer to the middle now i have the new i have to i have new middle if i have uh if the left is still less than right so zero one two three four right so the middle will be four because just based on this equation you will get the middle so i'm going to check 5 and 6 so 5 is less than 6 so i move the left to right so left to the middle plus one actually is this right now you will get the uh condition when l is not less than right all right let's just call it and you understand it and all right so in left equals zero right equal to num star length and in this exponent just minus one all right well left is less than r okay so i have middle in middle is left plus right minus left divided by two right i'm going to check if nums are m is less than num star n plus 1 and elsewhere so if the middle is less than middle plus one then i just have to swap my uh left pointer to the middle plus one if not i just set it to the middle now once i return for the middle right because when they are equal oh i should i return the left right when they are equal i can just do the either one then so return left is the index okay let's run it let's see if i have a typo or no okay all right pretty good right so the space and time that space is nothing right you just have left and right and middle doesn't actually matter but the time is important because you are going to use logarithm method so you will be logged in because you are actually using binary search like cutting the cutting cut into half every single time and then to check if this is smaller than this right if this is smaller than this then i just move my left pointer to the middle plus one or the right to the middle okay a little bit and peace out
Find Peak Element
find-peak-element
A peak element is an element that is strictly greater than its neighbors. Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**. You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in `O(log n)` time. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 2 **Explanation:** 3 is a peak element and your function should return the index number 2. **Example 2:** **Input:** nums = \[1,2,1,3,5,6,4\] **Output:** 5 **Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1` * `nums[i] != nums[i + 1]` for all valid `i`.
null
Array,Binary Search
Medium
882,2047,2273,2316
1,685
So hello everyone, so today we are going to solve today's PTD whose name is Sum of Absolute Difference in Sorted Array. Okay, so let's first understand what the question is. Without understanding the question, we will not be able to solve it further. Better first understand what it is saying, we have given the name 'Inger Array Namas' which is non- name 'Inger Array Namas' which is non- name 'Inger Array Namas' which is non- decreasing order. Now what do these people do, they write in such a way that they confuse us. Decreasing means increasing order obviously or sending order. Whatever you say is fine, now what it is saying is that build and return an array result is fine, a result has to be returned in a, which is the same length as the names, it is fine, true, that which will be the i element of the result, right? Equal to the sum of absolute difference between the names. I mean, the sum of the absolute difference of each character will be the sum of all the characters. Ok, now let us see how this is happening, let us first understand the question, what should happen, after that we will move further. We will solve it, okay, so let me take their example, so what have they done, they have given us an array, okay, this is the array we have, now what are they saying that whatever will be our array named answer, it will be It will be of the same length, which means it will be of three sizes, okay now, but whatever will be theirs, which will be filled in their index, what will be the answer array, what will come there, then the answer of zero means which will be our two, the first of the names, in this also two is okay, theirs. Index Now what we have to do for zero index is 2 might their absolute difference from itself plus 2 my 3 p 2 mine 5 so this is how much is coming we have here pe 0 psv p 3 so four so this is our answer four in the array. Will come here P Okay Same goes for first element answer What will be the access on the first step So what is at 3 minus zero in mm So 3 minus 2 3 minus 3 plus 3 minus 5 So how much is its sum 1 P 0 P So here we have Same goes for second one last index right so last index what is 5 value 5 minus 3 pps 5 value 5 So this is what we have come near 3 pps basically f So this is our f and the same thing We have to get the return done. If we look here then turn to the right side and see what is their output. 45 So we have to get the return done. So it is clear that no one will have any doubt in this question. I hope so, now the question comes that we How to solve it? Now we have considered it as a question, how to solve it, so basically there is an approach which we call prefix sum. Okay, so we will be using only this approach, we will read it in detail later when our course will be launched. How does price work and it comes in cues? S is special in cassettes and often in queues like these. Okay, so let's see what is the equality in this. First of all, we will find out a total sum of all the elements that we have. Why are you doing this and later on you will know that we will find out their total sum, after that using the total sum we will find their right sum i.e. whatever index they have, the their right sum i.e. whatever index they have, the their right sum i.e. whatever index they have, the sum of their right side and the sum of their left side, both of these can be found. Yali means what I am trying to say, like you see if we want to find the total sum then we can say this is left sum plus right sum. It is clear that we can write here right sum if we find If you want to do it with the same approach, then what will be the total sum minus left sum? Is it clear that we will be using this same thing here? Okay, we will be using this same thing for every index, so I just gave you this approach. Told a little about this, now you can think about how we will be using it. Okay, so while using it, I do one thing, first I code, then we will dry run the code and see, you will see those things there. It will be clear for you. Okay, so let's go to our compiler. Firstly, we will have to ID it. We will take the length. From this, we will rotate the size of the entire array. Now we will keep the total sum. Okay, for now it is zero. Now how will we calculate the total sum? So let's see. There is a loop inside Java. If you have read this then it happens in everyone. There is no need to write the complete loop in it. Basically, we can write it directly and calculate the total sum. P.S. This is the same thing as and calculate the total sum. P.S. This is the same thing as and calculate the total sum. P.S. This is the same thing as we write as normal, so what will this do with double dot and Nam, what does it mean that we are going to each element of the array and deleting it. Okay, so just come. I would have written the same thing, I would have written it because I like to nail down the elements directly, so that is, you can write anything according to you, now we make one left, zero is fine and one is fine for our result in which we write. Stay basically, now we finally run our main app, now we have left sum, so we have right sum, if we find it, then how can we find the right sum, if we know that we already have the total sum, then it is right. Even but look at this, we are taking out each index for i, what will we do, now what we saw in this, total sum minus left sum is fine and the element of that index and i will be small, that is why we need left and right. Na and now count how many elements are there in left, we have where will it be used, we will see further, it will be ok, so yes, I guess some people are not getting this thing clear, but no one, we will run it and see, right now, this is For the sake of things, we do it. If you have any doubt left here, we will resolve it there, it is okay, now it is the turn of left, what is the total of left, then the count of left has gone to us, which is our ray. The value is m minus the sum of left is right total right sum right count in is right and what will we save in our result, whatever our sum is coming right, the total value of both is equal to the total of left plus right. The total stem of aa will be the value of our particular index. Okay, and we will move the further left sum because it will not always remain zero, it will be from what, names of aa, next to go is naya and we will finally make the return from here. What is happening in the return result, the code is ours, let's run it and see if it runs, then the general is passed. Come on, let's see what we have done right, let's side-step it. Now we will move forward understanding each and every line of it. We did what is right in the test case that we were carrying with us, take the same test case, okay see, our number has become T, is it F? The length of the names will be as many elements as there are three elements. We will have no clear till here. No doubt means there should not be even till this. Let's look further so we have treated the total sum as zero for now, right? Now what do we do? We are calculating the sum, so what we did is we went from each element to A and how much did we get in total, so our value was here basically 2 x 3 x 5 so the total sum we got is 10. Isn't it clear till now see how much left sum has come, we have left sum. Answer, the array will be of three sizes of same size of N length. Okay, I am going to clear each line. Okay. Now we are running the loop, the main loop in which our main work is being done, we have to understand it well, so I will explain it on the next page, so where is it going from zero to A, okay, so A will run three times. What is our n3? So let's see for the first case what will happen for e 0. Now we are calculating right sum right how to calculate right sum so look at the total sum what we have for now is 10 minus left sum. What is left sum we have zero and numbers of a array we have how many numbers of 2 3 5 neither is right sum what is happening we have total sum is 10 left sum we have 0 -2 ok 8 ok right 10 left sum we have 0 -2 ok 8 ok right 10 left sum we have 0 -2 ok 8 ok right Giving the sum at means which is our index value aa for 0 we are finding neither for two we are finding it nor for sure we are finding it for two and how many sums are left on its right side 5 P 3 Now you must be seeing things, how much is the sum of the right area, eight, okay, similarly, now we will treat the left count with I that the left count is now how much is left in the left size, so according to I, how much do we have here. Now it is zero, it is a common thing where we are now, is there anything on the left side near two, is there anything off course, that zero is there, will remain zero and there is nothing on the left side, now we come to the right. How many elements are there in the count right, so yes, we have a minus aa, how many elements we have, minus, and yes, that is correct, what is the count of the index we are on, there are only two elements, so that is in the right count. It has come, okay, what are we doing now, till now it is clear, we have come till the left count, right count, now we come to the total or do the total, how much is the left count pass, how much is zero, first then the left count, numbers of I this. It is also zero, no dear, oh, how much do we have, it is zero, it will not make any difference, we will be finished now, look at how much is left on the left side, it is zero, above, so zero, so the left total, we have zero, now the right total. So how much do we have in the right side, so how much do we have in the right side? What is the right side number, minus right count, how much do we have, and this is multiplying. Nums of a means in 2, 8, and 4. Basically four is done, now what we are doing is the answer array which is our answer array or we are equating both of them if we look here, whatever it is, then left total plus right total so 4 ps 0 so 4 this is our For what is this happening, we are solving only for A and 0, okay, that means whatever was our answer array or resultant array, whatever we had, our first four has come here, it is okay and we are finally Who will upgrade the left sum because if we have to go further then how much is the moisture. Okay, the left sum will become ours. Here zero was zero earlier, it became zero so it is clear for the first test. I am working as a And let me run it and show it. For now, everything else should be clear. Let's come and see. Okay, what will be the same process for one? Find out the right sum. First, how close is the right sum ? Total 10, left has been upgraded. First zero. What's done is visible above ? Total 10, left has been upgraded. First zero. What's done is visible above ? Total 10, left has been upgraded. First zero. What's done is visible above and minus numbers of a now a i ve on our main array which was tha of names that was th 5 now what's on n p we have f y green right sum now left count. What is there, friend, how many are there in the left part of it? Now things will be clear better. Look, left count, how many have come to us, come here, how many have come to us, now you just see here, we were looking for this very element, that's it. How many ones are there on the left side? Now right count, how many are there on the right side? If you see, it will be a kitna pas minus mine ay, then this is also a common one. That's right, yes, to the right of the index value on which we are standing. There is only one element left, that is, even in the right part, the ice is getting cleared till here. Now let us see the total of the left part or how much is the total in the left part, meaning what is our left count here. But what is the value of a in the numbers of a? How much is the minus left sum? We have it here clearly, so 3 minus is our one. Okay, same go for right total. How much is there in the right total? We have right sum. Minus right count chi one and names of i names of a pass again this is done now what will be our answer i came here so the same left total ps right total ch p 3 is no and our left sum which How much will it be upgraded to? How much will it be? How much was it earlier? So 2 P 3 5 So now what was our resultant array, what was it earlier in the beginning, if we look at the top, it was Fahi, now here it is near. We have similarly solved the problem of zero, this approach will also be clear for your final test case, why what are we doing, okay then friend, if you understand then many, if not then let me know once. Please tell me that I did not understand here, I will tell you, I will definitely try to make you understand and friend, keep understanding like this and keep coding and subscribe to the channel, if you like it then please I will keep bringing more content like this and every day we are solving our problems. Yes, today it is a little late, I am uploading a little late but yes, it was of some use, but soon our DSA batch is also going to have lunch, so then Till then you subscribe to the channel so that you will get notifications of our new videos and if you have any doubt then you can ask in the comment section, ok without any further, let's meet again ok so guys see you in the next video till That keep coding by
Sum of Absolute Differences in a Sorted Array
stone-game-v
You are given an integer array `nums` sorted in **non-decreasing** order. Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._ In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**). **Example 1:** **Input:** nums = \[2,3,5\] **Output:** \[4,3,5\] **Explanation:** Assuming the arrays are 0-indexed, then result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. **Example 2:** **Input:** nums = \[1,4,6,8,10\] **Output:** \[24,15,13,15,21\] **Constraints:** * `2 <= nums.length <= 105` * `1 <= nums[i] <= nums[i + 1] <= 104`
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
Array,Math,Dynamic Programming,Game Theory
Hard
909,1240,1522,1617,1788,1808,2002,2156
1,764
hello everyone let's solve this problem today so it's uh something like a string match since it's the second problem in context and the test cases are not that long so we don't need to use some complicated algorithm like mp we can just use brute force like pattern match algorithm so this is problem we want to match each group in these nums and they cannot have overlap okay let's take a look at constraints the n at most is one thousand so in this cases we can use some naive algorithm let's take a look at my implementation so this is main function we initialize in that to zero and for each group i'll try to match this group in my remaining numbers if this function returns index that is less than zero which means we cannot match this group and i just return force otherwise this index is the next starting index that we can match the next element in these groups okay let's take a look at match group function the match group function and it says start from index and you try to match the groups like match whole groups at this index okay so for each start we initialize match to true and if it match we just return size which is next match index okay then this in the for loop is quite simple we just fold up every element in this group and then we try to see if the element enums is same or not if it's not same we set magnitude for standard brick then we can test next start okay let's take a look at the time complexity assuming there are k groups on average and for each group and the average length is l and is the number's length so in this for loop we know we will follow k times and in this for loop we will follow at most n times and in this inner volume we will follow l times so the time complexity at inverse cases can be ok and l okay that's it thanks
Form Array by Concatenating Subarrays of Another Array
maximum-repeating-substring
You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`. You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
String,String Matching
Easy
1689
27
hey what's up guys Nick white here I detect the coding stuff on Twitch in YouTube first problem of the day so we're warming up with an easy one I check the description for all my information I do patreon I do premium Lee code on patreon and I have a discord remove element is what we're doing today and it is very easy and people dislike it and I guess it makes sense it's kind of a weird kind of a dumb question I would think but I mean I guess it's something to think about I mean it's kind of lame but given an array of nums and a value Val remove all instances of that value in place and return the new length of the array okay so given an array of numbers we're given a value we want to remove every in every position in the array that is equal to Val so we want to delete these and we have to do it in place so we can't you know making a new array and just put these two twos in it and say like that's all good there's no threes anymore we have to go through and we have to somehow delete or something these are these two in place to you know accomplish what we want to do not allocate extra space for another array you must do this by modifying the input array the order of the elements can be changed okay so that's good it doesn't matter what you leave behind beyond the new length okay your function must return a length of 2 with the first elements being two okay so what they want us to do this is why I kind of thinks maybe the problem descriptions a little bit bad is they want us to change these elements basically so that the first two elements are two as if we deleted them so we want to make if we see a three we just want to make this a two and if we see this three we want to make this well it does we just have to have the first two elements or two and then we return up a length we need the elements up to the length or returning to be valid and not have the value in them at all that's why it's weird it's kind of just a weird problem you know for example in this case they want they have a value of two that they want to remove right so we don't want a value of two so if we want if we were to delete all these values of two we would delete one two three so the new array would be of size you know it would be of size 0 1 3 0 4 that's what they want but we can't there's no way for us to just delete the twos I mean we could fill them with nulls but the problem is we when we return the length so we're going to return a length of 1 2 3 4 5 so we're gonna say there's 5 elements without the twos right that's what we're returning is this integer that's what they want but this method doesn't just look at the integer and say you're right it also looks at the array and they don't really explain that but it's gonna check our array and make sure that whatever length were returning that the first length 5 elements if we return 5 it's gonna check the first 5 elements and make sure there's no twos in it so we have to essentially take these twos and we could have to either put them at the back of the array I mean pretty much we have to put them at the back of the array or we have to modify them and change them to maybe ones or something like that as long as there's no twos in the first whatever length or returning elements then we're good so how do we do this it's pretty easy all we have to do is I mean first we might want to just do a little check we'll say okay is nums dot length equal to zero then we'll just return 0 that's fine there's nothing going on here okay besides that what are we gonna do we'll say how about we do this int J is equal to 0 then we'll loop through I less than numbs Dalene so we're just looping through the array right linear loop okay here's the condition we're gonna do if nums of I is not equal to Val so we're gonna say if the current element is not what we want to remove well that's good so what we're gonna do is we're gonna say let's make nums of I since we can since we know for a fact that this element is good we're just going to move this to the front of the array so we'll say nums the front of the array this is a reference to the front of the array is equal to the current element because we know that it's good in then I plus i mean j plus because J is the size we're going to be returning you could call this size validus size valid element size or whatever you want and we will just increment it so that we put the valid elements to the front and you know that whatever length and whenever we know that it's not this value we increment it so by the end of the array we'll only have the size of the elements that aren't equal to the value so we'll have the size of a valid array and all of the first valid out first n elements where n is the valid size are going to be a valid so when it checks it's all good so we just return valid size that's this little problem a pretty confusing description I would say literally I cannot solve a problem without making a typo like what is wrong with me this couldn't be easier to solve I've got a hundred percent you know that's pretty much it's a pretty easy solution let me just show you why we had to do this put it like you might think oh they just want the length so you know you don't even need to do that so this is all elements length without zeros let's see what happens it's gonna fail because look three two they check against the input array see they check they expect you to have the correct array as well so you have to actually modify the values and make sure that valid values are within the size of the array you return all right that's it though it's a warm-up we're gonna go on though it's a warm-up we're gonna go on though it's a warm-up we're gonna go on to some harder problems now thank you guys for watching and I love you all at the bottom of my heart so alright see you guys that's weird
Remove Element
remove-element
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int val = ...; // Value to remove int\[\] expectedNums = \[...\]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[3,2,2,3\], val = 3 **Output:** 2, nums = \[2,2,\_,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2 **Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` * `0 <= val <= 100`
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
Array,Two Pointers
Easy
26,203,283
1,004
hello so today we are doing this problem called max consecutive ones three it's a medium problem and the problem says that we have an array of zeros and ones and we can change up to K values from 0 to 1 and we want to return the length of the longest consecutive sub array that contains only ones here and so if we look at this example we have these ones we can change up to two zeros to one we can flip up to two zeros for two ones and yeah so here how can we do that so the up to get the most number of ones we can flip these two zeros or we can flip this is 0 and this is 0 here and that way we get 6 ones because they could one can also flip these two zeros and get the same number the important thing is the number we get here um and so it's the maximum for this one we can flip up to k equal to 3 and the optimal way we can get the max ones is to flip the zeros here the two zeros here this is 0 that will get this entire chunk of ones and so this gets us 10 ones and the values of a are either 0 and 1 and so and this is the constraint of the value of a so how can we solve this problem so also so basically um if we let's just do this here so let's take this one so the goal is to get the length of the longest so the our goal here is to get the length of the longest consecutive contiguous or consecutive ones which is basically the contiguous sub-array with only once and we can get sub-array with only once and we can get sub-array with only once and we can get that by doing flips up 2k flips of the zeroes tools alright and so same thing here that is sliding window turkey well we need this problem we need to think about using it whenever we have a contiguous the question asked us for a maximum minimum sum or some other like constraint on a contiguous sub array contiguous part of sub array so whenever we have something that we are looking to get in a contiguous part of a sub array and the thing we are looking for is a Max and min a sum we direct I need to think about slightly point of technique this technique has two variants at least maybe more but to the two most important variant which are a fixed size window and in the valuable size window so this problem here let's think about how can we apply this to it so we know we can get we can do K flips that's one thing we know so what you can do is construct a window first that takes that just go tries to accumulate as much ones as you can so here we have one so we'll keep trying so basically our window is going to have start and an end and we just it's 1 so we still haven't consumed K so we try to construct a window so construct a window that uses payslips to get the max once again once we can start it from the beginning so just constructing the first window that we can work from and so that way here we'll still have ones we haven't consumed our K which is equal to and so still our we haven't used two values here we have used one value so I'll say zeros we have used here 0 as R 1 R equal to 1 and now here we have used 2 and so we kind of we try to do to get the number of ones here so the number of ones after flipping here would be 5 so this is currently the max window that we can get so this is the max ones but when we get here our number of zeroes exceeded K so as soon as the number of zeroes exceeds K we contract the window or contract the window basically and so this technique is the variable size window that we are going to be using here because it's not a fix it sighs it's not like it's a window or four bodies and we always keep only four values it's we try to get as much as possible because we want the max once and once our constraint is no longer valid which is the concern that we can't have more than K zeroes in our window then we need to contract the window and contracting the window means just keep making it small until the constraint is valid again so we keep making the stuff smaller so here's our zeros still three so we are still not in the constraint we still the constraint is still not valid and so contract again our a still here only and here it still our andest our status our number of zeros is still three at this point now if we now add that and then we can keep contracting now at this place here we still have three zeros and so condition is still not about so we go again and now we have just two zeros right so our condition is valid now so now we can advance K so basically one condition is valid it's valid advance end and when condition that is not well or while so well condition is bad at that fancy while condition is not valid advance stop until it becomes valid and so here now it's valid so we advance a number of zeros is still - so our condition is zeros is still - so our condition is zeros is still - so our condition is valid and here we'll just keep track of the number of one so let's imagine that I kept track of the number of ones I didn't but down yeah so here we have just one and just keep going since the condition is still guarded we have to keep going the condition is still valid we have three keep going the condition is still valid we have four keep going we'll go here actually since we have two zeros sorry that we have flip it and the condition is valid so we have six and so here it becomes six and now the condition is no longer valid since we have three in yours so we need to advance start so advance start again yeah our condition number of zeros become our number of zeros become how many now we have just two and so the condition is valid again but we no longer can advance this pointer at the end of pointer so we are done and the other is opt is 6 as we said here so the main idea is while the condition is valid keep expanding the end when the condition becomes no longer valid we advance the start so that we can get it and to get a window that makes the condition valid and then start doing the end again and keep doing this and so at the end and always while doing this I keep track of the goal function that we want so that's the idea now let's code this up so the solution to this is pretty straightforward so what we said we need is we need to keep the number of zeros track of the number of zeros we need to start and we need the end so this is actually quite uncertain with this and so the number of zeros starts off as zeros start out at end was just that keep track of India and then we need our result with max one the max ones or max was calculus for this function our result here and zero right now we want to keep expanding the end over in the range of or just to make this seem like the condition the code we just described so low start in the equal to 0 and what we are doing is well and is less than the length which is what we said here when and it's no long is reaching the end we are done so the length of the array so we are going to check if the value here is 0 we are going to increase the number of zeros that we have which is the same thing we said here so if egg and is equal to 0 we are going to increase the number of zeros we have and then we are going to check if we have if our condition is valid which is what we said here while our condition is not valid the defense thought until it becomes valid right so we are going to what does condition not valid means condition now that means we have more than k zeros because we can't just leave more than a case there also that we shouldn't have that and so we are going to check while our condition is no longer valid which means this so condition are no longer about not about what did we say we need to do we need to advance the soft pointer right so it was our start pointer only if so we need to advance our pointer right when the conditions now about but another thing we need to do is we change the value of our starts right and so we need to check if the value of the start value becomes 0 then we need to increase we need to decrease so if the value that we are going to advance from so we are going to advance a wire here or go to advance to this one if this value was 0 then the number our number of zeros need to decrease right and then we advance and after that we just put back the right value in res finger what is that's just the count the number the size of the current window because the current window we know that we are keeping it in the condition but we are keeping the condition but for that window so all we need to do to get the number of one's is take the size of window because that will have the K zeros at most and the ones that are in the window and so we just do my stress and get the size of the window which is n minus start plus one and at the end we can just return to that is but something we shouldn't forget is increase our end volume so this is actually small a skin okay so that passes respond this yeah so that passes a quick optimization here is we don't need to define this and here that just makes it a place so we can just say for end and range of this and that's pretty much it oh we don't need to do this and anymore since it's done by the range and that's pretty much it cheap ass yep okay so that's it for now um this was the an application of the slanting window technique with the variable size window it's a very useful technique so keep it in mind and see you next time bye
Max Consecutive Ones III
least-operators-to-express-number
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. **Example 1:** **Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2 **Output:** 6 **Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Example 2:** **Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3 **Output:** 10 **Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. * `0 <= k <= nums.length`
null
Math,Dynamic Programming
Hard
null
423
hello everyone this is the lead code problem reconstruct original digits from english given a non-empty string containing an given a non-empty string containing an given a non-empty string containing an out of order english representation of digits from 0 to 9 output the digits in ascending order input contains only lowercase english letters input is guaranteed to be valid and can be transformed to its original digits that means invalid inputs such as abc or z-e-r-o-n-e are not permitted abc or z-e-r-o-n-e are not permitted abc or z-e-r-o-n-e are not permitted input length is less than fifty thousand example one this input is 0 1 2 shuffled in random order output 0 1 2. example 2 this input is 4 5 shuffled in random order output 4 5 here is a table i listed all the numbers and letters it will help you to find the pattern there some letters only exist in certain numbers for example z only exists in zero x only exists in six w only exists in two u only exists in four and g only exists in eight counting how many of these special letters in the given input we know how many of these numbers are there some letters exist in more than one numbers for example f is in both four and five we know the number of u is the number of four so the number of f minus the number of u is the number of five h is in both 3 and the 8 we know 8 by the number of g so 3 is number of h minus the number of g s is in both 6 and 7 we know 6 by the number of x so 7 is number of s minus number of x there are only one and 9 left one is number of o minus zero minus two and minus four and nine is number of i minus number of five minus number of six minus number of eight this is not the only possible pattern some numbers has other possible combinations once we have this pattern the code is very simple first we count the occurrences of each letter this is the pattern for number zero to nine then add numbers in the result thank you for watching
Reconstruct Original Digits from English
reconstruct-original-digits-from-english
Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_. **Example 1:** **Input:** s = "owoztneoer" **Output:** "012" **Example 2:** **Input:** s = "fviefuro" **Output:** "45" **Constraints:** * `1 <= s.length <= 105` * `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`. * `s` is **guaranteed** to be valid.
null
Hash Table,Math,String
Medium
null
27
hi guys welcome back to another video in this video we will be looking at another lead code problem named as remove element the problem statement is as follows given an array nums and a value val remove all instances of that value in place and return the new length do not allocate extra space for another array you must do this by modifying the input in place with order of one extra memory the order of elements can be changed it doesn't matter what you do beyond the new length so two examples are given here the first example contains an array numbers with the following elements and the val is three so after we remove the valve from this array we remain with two elements which are two another example where the nums is as follows and the val is 2 so after removing 2 from the given array we are left with 0 1 3 4. now let's consider the second example where the value of nums array is as follows and val is true let's go through the algorithm to solve this particular problem initially we take an iterator and point it to the beginning of the nums array and then traverse the numbers array for i is equal to 0 to nums.size and if for i is equal to 0 to nums.size and if for i is equal to 0 to nums.size and if nums of i is equal to val that is if any of the element of num's array is equal to val then we erase that element and decrement id and finally we increment id to point to the next element of the array and after finishing the loop we return the size of nums vector initially i t points to the first element of nums which is zero so numbers of i is zero whereas val is two since this both are not equal we proceed further now id points to 1 even 1 and 2 are not equal so we again proceed further now the value of nums of i is 2 and val is 2 since both are equal we erase 2 from nums array while doing so the iterator points to the next element so we need to decrement id to bring it back to the original element now again we have encountered a 2 so val and nums of i both are equal so we can again erase it from the nums array again while doing so the id value points to a next location so we need to decrement id now i t points to three since three is not equal to two we can proceed further now i t points to zero again 0 is not equal to 2 so we can proceed further see similar case with 4 and finally when i t points to 2 val and nums of i are equal so we erase 2 from nums array finally we have left with a new array which contains 0 1 3 0 4 whose size is 5 so we can return nums dot size that is 5. so now we can begin with our code which is quite pretty simple initially we need to create an iterator and point it to the beginning of nums vector now we need to traverse the nums vector or nums array and at each traversal we need to check whether nums of i is equal to plan if so we need to erase the value of nums of i from numbs vector here we are using the erase function from scl library and passing it the iterator id to delete that particular value from the nums array and we decrement id and i as well and finally after finishing the loop we can return the size of nums so here the reason for decrementing the value of i t is that whenever we erase an element from the vector the id iterator points to the next element so we need to bring back to its original element that's why we decrement the value of id so our code is finished and we can run the code to check whether it contains any errors the cold run fines so we can proceed further and submit it and it got submitted successfully so if you liked the video do hit the like button and subscribe to my youtube channel for more such upcoming videos thank you
Remove Element
remove-element
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int val = ...; // Value to remove int\[\] expectedNums = \[...\]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[3,2,2,3\], val = 3 **Output:** 2, nums = \[2,2,\_,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2 **Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` * `0 <= val <= 100`
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
Array,Two Pointers
Easy
26,203,283
1,319
hey guys welcome back to the channel this is today's video we are going to continue our graph placement bootcamp playlist right uh so as promised i am providing you videos every day this month so do don't forget to subscribe to my channel that will help you to put more and more of such videos right so in today's video we are going to solve a lead code medium problem based on dsu's right and you will understand that how this medium problem would be a piece of cake work for you if you have watched the other two videos that is on crystals and dsu's right so this is a problem that was asked in amazon and facebook as well so without any further ado let's get started with this video okay so this is the number of operations to make a network connected so basically uh you can go through this problem i will attach the link in description down below but i will just explain you the problem to make things quicker so let's say there are different computers right and there are different connect computers that are connected by some wires right but you can see that there are some computers which are not connected right so we have to like we can't add any extra edge right but there would be some edges which are not required like if you see this edge is not really required because this edge connects 0 and 2 and this edge 0 and right so that all the computers are connected right so the idea over here is you can't add any extra edge but using the edges that are already there and removing some edges and like playing around with the edges can you make all the computers connected that is basically what the question says so if you see this question right over here you see that four and five are not connected all the computers are not connected right you have to use these wires only the wires are given to us and we have to connect all the wires right and all the computers right so here you can see there are some extra edges which we don't need so we can take this out you can take this crisscross vola wire and we can apply between four and five so now four and five become connected and now we can also take this wire out and we can connect this and now this entire computer will be connected and the winning operation is two because we extracted two wires right there can also be a case where we are unable to not which we can use to make the computers connected right this is a very straightforward problem in crystals so whenever we talk about adding or removing edges right and trying to uh like find the number of connected components or checking whether the graph is connected or not is there any path between the two nodes right these type of things we you should understand by now that it involves uh solving the problem by use with the help of dsus because dsu's helps to us to solve this problem like adding an edge in constant amount of constant time or maybe checking whether there is a part between the two edges right our final function linear function helps us in doing that right so now uh we just solve the crucial problem right and uh the kruskal's algorithm right so basically where we there we sorted edges right and then we check that so what was crucial algorithms or minimal spanning trees algorithm basically doing right we were removing unnecessary edges and by removing the unnecessary edges we were getting the minimal spanning tree with the minimum cost right so if you see in this example right where we are where we discuss this example where we remove this h7 try to get the female spanning tree and this really helped us in discarding the edges that we really don't require to make the graph connected right so even here also in the see in this problem also by now you should understand that we can use this same algorithm like a little bit of modification we don't need to sort the edges because again first of all we don't need any weight over here like if you go to the problem right do you see any need attached no it is just whether they are connected or not right they're just the connection in two nodes is given as edges right so over here we don't need to consider that what is the we just need to con perform the minimal spanning tree we don't need to find the minimum cost for a spanning tree because obviously cost is not involved over here that is like the slightly easier problem uh slightly easier version of algorithm right so over here definitely sort won't be required right and also you don't need to uh you don't need this step you have to calculate the mst weight because weight is not over here in this context right so all you need to do is you need to traverse to all the edges that has been given to us and then you have to check whether the same connected component or not and that you can do using find root function right and then if they are in the same connected component right if you find the edge which connects to nodes of the same credit components then and there then i can say that hey this edge is not required and what i can do is uh like then i can add that edge in a discarded list right and later i can use the discarded edges list right to make connections with the computers that are not yet connected right so let's see how we can do this so now what i'm trying to do solution that i'm trying to propose is i will traverse to all these edges right and what i would do is i would like see okay initially let's say that there is no edges and uh none of these 0 1 4 5 2 3 they are all in different connected pockets right that's how we will start and then we will connect 0 and 1 and you will see hey zero and one is connected so just union them and now they're in the same component right now and the idea is to uh like make a connected component like have one single connected component right then comes zero to now zero to ah 2 is in a different connected component and 0 is in a different connected component so we will attach this right now 0 3 again 0 uh 3 is in a different thing is a different connected component and this is again a different kind of component so we attach this right now when we come to one two so we already see one and two lies in the same current component therefore we add this to the discarded list because we won't so that means this one two is not required this edge is not required and we can use this edge to join some other computers right which are not in the connected component that's the idea right so let's not take this and let's add the discarded list right so what is the total size of this discarded list and that is one two and one tree that is two right so there are two edges which we discarded and you are still able to connect these components right but four and five is not yet connected right now how do we understand that whether this uh like all the nodes in this graph are connected or all the computers are connected or not simply we have to find the number of connected components and if the number of connected components is equals to one we know that entire graph is connected right so now what we will do is we will just check and now how do we find the number of connected components right the number of connected components will be equals to the number of roots right number of roots if you go to the parent array whoever's value is minus one means that is the root so the number of connected components will be equal to the number of roots right so then we can get the number of component power connected components so over here if you see let's say zero is one good four is one root and five is one root so number of connected components is three right so we know that we have to make this current component as one right now when we have a connected components equals to n what would be the number of minimum number of edges required to join all these components and make it into one that will be n minus 1 where n is the number of connected components right because see over here you have three connected components this is one connected component this is one kind of component right in order to make all these components into one single component for you what you will do is you join this component with this component that will require one is that you will join this component and this whole component to like make it fully connected that means two uh two edges would be required so i can simply say that whenever my number of connected components equal to three and i want to make the number of connected components as one then i need two three minus one that is two edges right and where will i get this extra two edges i will take it to the list area discarded size so that means if i can if my discarded right if my discarded is less than the edges required and what is the edges required they just required is number of connected components minus one right if the discard it is less than the discarded size is less than they just required that means i need some extra edge but i can't get any extra i have to use this edges existing edges only then i can say hey i can't join the i can't join all the computers because i don't have enough edges i just discard a few edges and i'm going to use that only you are not going to give me an extract so i am going to use the discarded edges but when discarded number of discarded sizes less than the edges that are required to make the component like the uh like the full component right there the connect the component right correct all the components of the graph and uh that would hence i would return minus one else i can return edges required that means my discard it is greater than equal to that is required that means i have enough ammunition to make it a connected component single connected component and hence the edges required will be my answer so let's quickly check out the code it's a very straightforward problem uh i hope you have understood this problem if you have any doubts at the end of the video feel free to uh comment down below or also you can follow me on instagram and connect with me and ask me doubts and i will be more than happy to resolve them for you right okay so i just pasted a dsu code because i am not going to write this entire dsp code again this is like i've already explained this in detail in the previous two videos so now i'm just going to write the code it's very straightforward code uh so basically as i said what you need to do is you need to traverse the edges so let's say our connection is uh connections right so there are two things you need to do right one you need to find the number of current components and the edges required and you find need to find a number of disc edges that you can discard right so i will have discarded edges right equals to zero and i will try to check if i can union right if i can union this connection zero uh this is basically okay if i can union these two nodes right then it's fine that means there are different connected components but if i can't union this two different uh do notes that means that the same current component in that edge in that case i can add this edge to the discarded list or in other words i am just increasing my discarded with this count right okay now what i am going to do is after my dsc unions are done after i like traverse to all that is now i'm going to check i'm trying to traverse the parent right and i'm going to check if my e first equals to minus 1 right uh basically yeah so basically it will be components right forms equal to zero so the number of roots right so basically minus one is basically checking for the root right and every do every component will have a single root right so number root will be my number of connected components right so i will be doing a columns right so what will the edges require to join every component will make it a single component that becomes minus one right now if i find it if a is my discarded at this count is it less than the edges required that means i don't have enough ammunition to join all the computers that is one as it's been pointed out here else i will return the edges required right so we run this code i hope i didn't make any errors here there were some errors let's see what are they uh cannot find simple okay sorry i forgot to like make a tsu class you always forget this okay this will be n and i think you're good now cool let's one submit this and it's done right so that's it guys for this video you can see the last amazon feature in the last six months right so it was such an easy problem right once you understand the issue and crystal's algorithm i hope you enjoyed this video uh i hope that really hope that you're liking this uh this entire uh video series i'm trying to put up every month i also hope that you're liking this graph placement series if yes then please uh share uh it on linkedin uh tagging me or also using the hashtag right it will surely motivate me a lot also don't forget to smash the like button don't forget to subscribe to my channel don't forget to comment any doubts you have also you can reach out to me on instagram as well you can follow me over there i'm quite active over there if you have any doubts i would more than happy to resolve it for you right having said that let's end this video
Number of Operations to Make Network Connected
unique-number-of-occurrences
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[0,2\],\[1,2\]\] **Output:** 1 **Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3. **Example 2:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 2 **Example 3:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\]\] **Output:** -1 **Explanation:** There are not enough cables. **Constraints:** * `1 <= n <= 105` * `1 <= connections.length <= min(n * (n - 1) / 2, 105)` * `connections[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no repeated connections. * No two computers are connected by more than one cable.
Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.
Array,Hash Table
Easy
null
518
in today's video well this isn't really today's video because I actually recorded this whole video I got deleted off my hard drive accidentally and now I'm actually in a huge pain because I have to reteach this but we are going to do the total unique ways to make change problem so what is this question asking us it is asking us given an amount and a certain amount of coins one two and five coins or we could just gather two coin given an amount we need to say how many unique ways are there to make change for this amount so 4 td amounts 5 if you give me a 1 2 and a 5 point they're going to be 4 unique ways I can just use the 5 I can use a 2 and a 1 I can use a 2 and three ones and I could use five ones if I have n amounts three and I just have the two coin am I going to be able to make change no there will be 0 unique ways to make change so how are we going to do this problem yes maybe is done in the programming to solve this question what we are going to have to do is we are going to at each stage we are going to consider a certain coin and see how it changes the total amount of ways that we can make change this is very similar to the zero-one knapsack problem and you the zero-one knapsack problem and you the zero-one knapsack problem and you will see what I mean when we go through this dynamic programming table and I will show you these subproblems and I want you to know these subproblems and not memorize the patterns of how we fill the table out so let's look at that right now every single dynamic programming video should start out with the explanation of these subproblems it's not about the table behind me it is about the subproblems and how they relate to each other so what does this mean what does that sell me that cell is the subproblem if i need to make change for one and i only have the coin 1 how many total ways are there to make change this salad means i need to make change for the amounts 3 and i only have the coins 1 and 2 and notice every row represents the addition of another coin this row represents a deal one point this row represents adding the two coin this row represents adding the five coin if I put a dot right there if I have the amount one and I have the one two and five coin how many total ways are there to make change and then finally the original question that we asked if I have an amount of five I need to make change for and I have the one two and five coin how many total ways are there to make change we are going to be answering six times four we are going to be asking 24 questions twenty-four questions to questions twenty-four questions to questions twenty-four questions to answer just one question which is our ultimate goal which is the goal at the end of the table here is how we start our table if I have a zero no matter what coins you give me I'm going to be able to make change one way which is to do nothing and again I have zero it does not matter what coins you give me you could just have the one you could have the one in the two you could have the one two and the five and it does not matter there will be one way to make change using no coins okay so that makes sense so what if I have no coins at all and I need to make change for one then I will have zero ways to make change if I need to make a change for the amount to and I have no coins how many ways can I make change zero ways and then it's the same thing any amount you give me if I have no coins there's no ways I can make change so now the answer to this cell is we're adding the one point so we have two choices use the one point or do not use the one point so here is how the relationship forms the relationship is if I do not choose the one point our subproblem is make change for the amount of one and we only have the one quarter if I do not use be one my amount stays the same but my subproblem drops through and I have no coins so if I don't use the one point I drop down a row and I have no coins but I'm still solving for the amount one if I do use the one it changes my amount but I stay in the row where I can use the one coin so I subtract one from 1 which is zero but I stay in this road so not using the one point using the one coin what I add those two possibilities I get to where I'm sitting at so this cell is one plus a zero if I do use the one coin then there is one way I can make change if I do not use the one point then there are zero ways I can make change so when I am at this position I have those two choices and the addition of those two choices gives me the total ways when I need to make change at this cell let's ask ourselves if I only have the one coin and I need to make change for two then I subtract one from here and then I go here within the same row if this is if I do choose the one coin so I did choose the one coin so there's one unique way to make change if I do choose the one point if I don't choose the one coin then there are zero unique ways to make change because I just can't make change if I have no coins so 1 plus 0 is 1 and again 3 minus 1 I do choose it I don't choose it I just go up a road because I'm not considering it every wrote we consider the an additional coin I'm not considering one so I jump up to the 0 and if I do consider I do my amount minus the coin amount 3 minus 1 lands me at 2 I use the coin so I subtract by its amount but I still am in the row where that coin is considered because I just used it so 1 + 0 1 so now because I just used it so 1 + 0 1 so now because I just used it so 1 + 0 1 so now again don't use the coin 0 do use the coin 4 minus 1 is 3 the answer is 1 at that subproblem so 1 plus 0 is 1 and now if we don't use the coin it's 0 if we do use the coin it is 5 minus 1 is 4 and then we stay in the same row so it becomes 1 plus 0 which is 1 so think about this if we just have the one coin how do I make change for 5 I do 5 1 coins if I just have the one coin and I make chase for 2 that is 2 1 points each of these are 1 unique paths so do you see how this kind of intuitively makes sense and when we build these sub-problem answers we're build these sub-problem answers we're build these sub-problem answers we're going to have a correct answer down here so now I'm considering the two points this is a big jump this is why this problem is very similar to the zero-one problem is very similar to the zero-one problem is very similar to the zero-one knapsack problem we're now considering the two point we already considered the one coin we're considering the two point now what I do is can I even use the two point when I have an amount one I can't even use the two point so I can't vote one minus two I'm gonna go negative so here all I can do is not use the 2 coin so I just don't use it so it becomes 1 plus 0 because we just call a 0 so it becomes 1 and that becomes our answer so now when we're at 2 we can use the 2 point so if we don't use the 2 point we get home totally unique ways of 1 if we do use the 2 point it becomes 2 minus 2 which is 0 and we stay in the road because the 2 point is still considered but it's subtracted from our amounts because we used it so we did 2 minus 2 brought us to 0 in the same row and now we have 1 plus 1 is 2 if I have a 1 in the 2 point there are two unique ways to make change for it a 1 and just the 2 point that answer makes sense so now if we're at 3 don't use the 2 point we get 1 if we do use the 2 point 3 minus 2 is 1 and now we stay in the same room 1 plus 1 is 2 and now here don't use the 2 point we get 1 do use the 2 point 4 minus 2 is 2 stay in the same row we get 2 so now to plus 1 is 3 if we need to make change for the amount for and I have a 1 in the 2 coin there are 3 ways to do that I use 2 two points I use 2 and then 2 1 coins or I just use for one coins three unique ways it's making sense so far so now don't use the 2 coin I have one unique way if I do use the 2 point 5 minus 2 is 3 we have two unique ways and then now 2 plus 1 is 3 and now if we are in our final row we are approaching our final sub-problem if approaching our final sub-problem if approaching our final sub-problem if we're at 1 and weird considering five point the five coin has jumped into the picture now so now we're considering the five point can I even use the five point when I'm making change for one can I even use it when I'm making change for two can I even use it when I'm making change for three I can't even consider the five point so what happens I can't consider the choice of using it I can go 1 minus 5 thats negative so I considered only the choice I'm not using it so this becomes 1 this becomes 2 this becomes 3 why because up to 4 we still can't use the 5 point but what happens at 5 we have our choice opened up to us to use the 5 point if I do not use the 5 point there are 3 unique ways if I do use the 5 point 5 minus 5 is 0 stay in the same row because 5 is considered in this row so we have one unique way if we do use the 5 we have 3 unique ways if we don't use the 5 the addition of those is the unique ways if we have one 2 in 5 for the amount of 5 so 3 plus 1 is 4 and that is our answer there are 4 unique ways to make change for 5 given the coins one two and five and each iterative step every road we considered another coin at the end we knew what the total unique ways are when we consider all of the coins and that is what dynamic programming is about we built our answers up through the relationships between the subproblems we saw how they related and we built up to our global answer here which is 4 so that is how this problem works so a lot ask about the intuition behind this so a lot of these problems intuition can drive the way you solve them but sometimes it's just remembering these patterns remembering the zero-one patterns remembering the zero-one patterns remembering the zero-one knapsack type problems that is the key to this problem so let's look at time and space complexity and so now the time and space complexities for this problem we are going to be computing the answer to a times C subproblems so that is the time we are going to spend solving subproblems as for a space we will be storing a t plus 1 times c plus 1 subproblems so our space complexity is just a times C and remember it is the amount and C is the number of coins that we are given we also can do this in a space but I wanted to keep it this base complexity for this walkthrough so that we can see how we change the coin we consider in each step and this is very similar to the zero-one knapsack problem similar to the zero-one knapsack problem similar to the zero-one knapsack problem which I highly encourage you to watch that was this question if you like this video if this was a clear explanation hit the like button and subscribe to the channel I hope to do videos like this every day to help others in the software engineering interview so this
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,473
hey guys this is jason how's everything going in today's video i'm going to take a look at the 1473 painthouse 3. actually i did this in today's live contest but i didn't make it i tried to backtrack backtracking solution and it cost too much time and of course i met tle and it actually worked but it's very complicated and i didn't made it to avoid the duplicate calculations so after that i did some investigation and take a look at the discussion that other people are talking about so i finally understood uh the key point of this problem so i made this video hope it helps to be clear this is not i didn't came up with this uh solution um yeah let's just begin so there's a row of m houses in a small city each house must be painted with one of the end cutters labeled from one to end with one base some houses that has been painted last summer should not be playing paint again a neighborhood is a maximal group of continuous houses that are painted with the same color for example houses like this contains five neighborhood one two three two one so each neighborhood should have the houses painted with the same color now we're giving it array houses an n by n matrix cost and an integer target where houses i is the color of a house is i zero means not pending yet constant ij is cause of paint house i with the cartridge plus one because cutter is one base okay so i need to return the minimum cost of pending all the remaining houses in such a way that there are exactly target neighborhoods if possible not possible return minus one suppose we have five houses all of them are not none of them are painted now we have the cost table like this means that the first house costs one to pay the paint cutter one cost 10 to paint color two the same for the rest now we need to paint all five houses uh with three neighborhood so the final the best approach is one two one which exactly three neighborhood one two three now let's see the cost because the first house is to be paying with one so it costs one the second one costs one the third one cost one the fourth one costs one and the last one cost five so totally nine hmm okay so for this kind of problem i did there's nothing to start with at the beginning right it's just seems like um some at didn't even know where to start so i just start backtracking which is not a good idea the best way to solve problems i think is to recursion right most for most problems yeah i forgot that the best is to do recursion and then try to improve it with the dynamic programming or memorization or anything so for this one let's just take a look at the basic examples for example we have five houses need to paint and uh just the first example now for the first house what's is going to be painted well there are two possibilities let's see what happens if we paint one it means there is already a neighborhood right so for the okay so for the next one let's say if it is i don't know where to paint something like this right so we need to actually uh to create like create a target minus one neighborhood right neighborhood from index equals one right yeah but let's take it deep take a look at deeper actually this part this one right uh there's a problem here if it is one if you choose to paint it as one it actually doesn't create a new neighborhood right if this is the case you actually need to create the target minus one neighborhood from index plus two okay index equals two right because there's only one neighborhood here well if this one is choose two then actually we need to choose target uh create target minus two neighborhood right from so this is a basic uh basic recursion relationship so actually for let's see if this sub problem looks like a recursion right we just create a target one neighborhood from index one which is the same act similar to create target neighborhoods from index uh at zero but actually but the previous actually previous quarter actually matters here if the previous one is one when we are starting one we didn't we don't add one neighborhood if the previous one is not one well this ad neighborhood so actually we if we create a peng method the first one the steps which you're gonna be uh using the recursion should be uh should have i think you should be you should have three uh parameters which is one is a starting next let's say housing next one is proof counters right creep house this is brief cutter and then uh the target i say it's neighborhood okay this is the recursion with the pain method so at last we could do what we could do the problem should be we should paint from house zero uh with the proof card because no matter what we choose for the zero index we could always create a new neighborhood so we previously said to minus one this no cutter will be minus one so yeah and the target we're just passing target now let's just try to do our recursion well because the house might have original origin cutters like it might be not zero it might be something different than the preview color so let's do to create some if class here uh okay the cost origin quarter it should be houses house index right cool now if origin color is zero it means we could paint any cutter or origin cutter it's different is already painted but it is pretty cutter or if it is not the previous color so these are three cases right cool and for each cases we need to get the minimum right so i mean cost okay so if we this is zero if it is zero what we do well if it's zero we just we could paint any anyone right we could paint any uh cutter so we loop through the cutter we pin it if we paint we need to add the cost right adds the uh cost know from the cast table and what you do if we paint with a cutter we need to actually like here if we paint one we need to paint continue just continue our painting right so we paint next one so uh the cost so for each of these check uh for these uh for each of these possible cutters actually we get a possible optimal results so we need to update the minimum cost among all of the part solutions so we created minimum would be infinity so the cost would be of the cost com okay so the possible mean cost should be what should be paint right paint the next one and the next one is house index plus one proof cutter is our cutter which is i and the neighborhood so this is a tricky part if the next color uh if this is going to be paint oh no paint right if the current cutter is the same as previous one then the neighborhoods doesn't change right so if i which we're going to paint is equal to the previous one then just the inus it is within the same neighborhood so neighborhood if not we were different neighborhood so we minus one and then we need to add the cost right so cost uh house index uh cutters color is i so i minus one so this would be possible mean cost yeah this is one possible main cause uh when we paint this house to i with a cutter i and we update it math wing i mean possible mean cost so this is the how we handed it when the when it is not painted yet so we do the simulator for if it is already painted and it is previous cutter well it's simple right so for this case we didn't add we don't add neighborhood so we don't need to minus one so we just say my main equals okay we just create another it should be uh paint right you paint next one house index plus one the previous cutter is the origin card right it's origin quarter and the neighborhood we don't need to change it because it's the same in the same neighborhood okay so it's done and if it is a different color than the previous color uh what we do wow we just say mean math mean we paint the next one uh origin cutter is the yeah we use origin color here but uh the like here it already is belong is a different neighborhood so for the next one we need to uh minus one so this is it and we just return the minimum right so when will these recursion end well it actually ends when the house index is uh is all the houses are appended so if house is indexed equals to m we need to return when we go to the other houses is paying neighborhoods should be equal to zero right so if there's no neighborhoods we need to create if equals to zero then we return zero right cost is zero if not there's no more houses to paint so it's infinity right cool so this is it i think it should might should work let's try to review our code before we submit a code so we create a paint function this pain accepts housing decks so which houses to pay and preview cutter and the neighbors target with the how many neighborhoods you want to create well if the house is the houses are pen and the neighborhoods we don't need to create any neighborhood we return zero or infinity it means impossible right and we get the current color if it is zero which means we could paint any color so we painted next one we tried to paint the next one previous cutter is i if this color is the same as previous one the neighborhood it doesn't change if not we minus one and plus the cost we're paying right yeah so we update the minimum and then if the origin if the color is already painted if it is the same as previous one then we just continue to paint the next one with the neighborhood we want to create if it is different then the current has created a new neighborhood and we minus uh yeah we change it to minus one so return minimum yeah this should work let's run the code yeah but actually if we said if it seemed possible with the term return minus one so we need to check if it is infinity or not cool we submit look i have tried a lot it's always meant me to meet the time let me exit it but it's hard so yeah of course we got time limit exited well it's very um it's not that easy but we might think we might be led to the conclusion that if we say we need to paint the houses in the middle like index to two with previous carry with one and uh neighborhoods with two we need to something find the minimum cost for sub problem like this right but the previous color proof cutter and the proof neighborhoods for the houses before this index actually they will have many possible combinations right so this might not be one possible combinations which leads to our request our call of paying a specific house index specific brief cutter specific neighborhood so there's a lot of duplicately caught cause to paint right so that leads to the memorization sadly i didn't come up with these approach at the live contest so this is re is very straightforward at which a cache pro cache approach we just say cache we create a new map well for the we create a key if you do if it is already uh checked then we just return the result and then we need to set the uh sets the cache right cool let's run the code it should work and we submit yeah we are accepted so this is approach of memorization obviously we only add the memorization and it just uh it is accepted and uh so it helped uh reduce a lot of time so what's the time and space complexity of the hour approach here for time hey guys uh after i draw some graphs on my notepad um finally i think i got to understand what time complexity for this problem is let's try to allow me to illustrate uh demonstrate what i have done so to analyze the time complexity of a recursion the better thing we better try to understand the caudary right so let's see for the first time the cautery culture of paint okay the first call of paint should be paint uh zero minus one okay right now is target which is used t this is the first call and this call actually will trigger uh the trigger following calls actually it will trigger one and one k minus one and then one two k minus one which means for the next index right okay so actually we could remove the depth here so you see it's the same so this two previous one is two k minus one right and then pre and then previous one is n k minus one so these will in turn will trigger what will trigger you see what trigger uh the previous one is uh for the case here this will trigger um because previous one is one now for this index two if this one then k minus one doesn't change right so it will trigger one okay minus okay i'll write it down for better understanding so one this is okay that's our two if the previous one is one no we will because previous one is one and then we'll call this with minus one right and then we will call uh two this is for the case here i mean for it means for the first number the previous one is minus one but actually it will could be any one right okay now for the case here it means the prevalence is one actually for left for two it could be any one right it could be anyone so if it is proven as one then it is the same as previous one so it uh it doesn't create new neighborhood so now here should be a two 2 which minus 2 k minus uh minus 2 right because for 2 this is for the first index actually for the index of this one but now and because pre-version is two but now and because pre-version is two but now and because pre-version is two then for the comparing to the previous one is a minus one and then for one it's different this issue mine came as 2 right so h should be 2 and k minus 2. this will be all continuing and so for here will be 2 1 k minus 2 dot 2 k minus 2 n k minus 1. well let's just review it one more time this is for uh remains for the first yes for the first position the previous one is minus one right let me quote it to actually for the for position here it might be one two n right that is for the next index that's the first but for the next index this is the previous possibilities so for the here it is uh the possibilities for here right but the previous is for one means for one yeah so if it is first one it doesn't change the neighborhood okay so for the case here is two then we update here so for the last case is one for n if the first one is n then the case all the possibilities for index one if it is uh if it is still n then the neighborhood doesn't change right you see so you see for index two actually there will be uh there will be how many there will be actually for each of these n cases there will be n right this is without memorization i say so for a layer here it should be n and here it will be called n into part two so each of the possibilities will generate new possibilities so if we do nothing without memorization it actually will be leads to uh it will lead to needs to um okay put one plus and plus n to the power of two to the power of m actually so it's o i think it should be m there's a case that k right if k is a smaller this will actually be smaller than this let's say the k is big enough so we will always travel forward so here we always traverse to the end i handle uh the last index so i think it should be a reasonable uh like a upper bound now this is without memorization if we with memorization what will happen you see uh for the case of two we see that for the combination of these actually they will be uh for the second they'll be uh n possibilities right one to n and here the possibility will be two the next one will be three right so if we do the memorization the tree will start at uh no a lot of the calculations could be avoided by mem by just getting the results from the cache which means for the first layer it will call with one for the second one it should be uh n right so it should be n times one and next one is uh n times two right because you see for the possibilities will be n here of two possibilities k minus one or k minus two okay so the third one should be n plus three times three right so last which is n times m with the assumption that k is big enough we can have this actually 12 which will it will end uh shorter that's k right actually so if we sum the limits up it will actually create a time complexity with n times uh n squared yeah so actually this is our time complexity if we fail uh if we should uh terminate the uh terminated without going to last index actually we can see that the length k sliding window like a sliding window k just moving to the n m so actually uh it would be i think you'd be reasonable to think it should be n times m times k right yeah suppose this should be like a k length k a interval k intervals like overlapping with each other so yeah i think we could reasonable thing it reasonably i think if it's uh oh yeah we can omk so for the space well um well for each layer it's different so actually this will just be the same omk the upper bound will be m square actually our solution here it should be n m to the square because we were going to last index right we didn't think of the neighborhoods being minus so we should if we uh if we're gonna improve it okay this is a count i counted to account the call of paint to validate my assumption so this is done yet is already done so this is the result time and space complexity this is actually should be m squared how could we improve to m and k we should stop when neighborhood is minus right and negative right so it's negative it's impossible so if this okay um yeah if neighborhood is bigger is smaller than zero you return infinity yeah so that's for by these if class we improve the time complexity to from uh n m square to n k yeah i think so let's try to run our code hmm it should be a little faster yeah okay so that's all for these one the time complexity cost me a little time i hope it helps i'll see you next time bye
Paint House III
find-the-longest-substring-containing-vowels-in-even-counts
There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. * For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`. Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where: * `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet. * `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`. Return _the minimum cost of painting all the remaining houses in such a way that there are exactly_ `target` _neighborhoods_. If it is not possible, return `-1`. **Example 1:** **Input:** houses = \[0,0,0,0,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3 **Output:** 9 **Explanation:** Paint houses of this way \[1,2,2,1,1\] This array contains target = 3 neighborhoods, \[{1}, {2,2}, {1,1}\]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. **Example 2:** **Input:** houses = \[0,2,1,2,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3 **Output:** 11 **Explanation:** Some houses are already painted, Paint the houses of this way \[2,2,1,2,2\] This array contains target = 3 neighborhoods, \[{2,2}, {1}, {2,2}\]. Cost of paint the first and last house (10 + 1) = 11. **Example 3:** **Input:** houses = \[3,1,2,3\], cost = \[\[1,1,1\],\[1,1,1\],\[1,1,1\],\[1,1,1\]\], m = 4, n = 3, target = 3 **Output:** -1 **Explanation:** Houses are already painted with a total of 4 neighborhoods \[{3},{1},{2},{3}\] different of target = 3. **Constraints:** * `m == houses.length == cost.length` * `n == cost[i].length` * `1 <= m <= 100` * `1 <= n <= 20` * `1 <= target <= m` * `0 <= houses[i] <= n` * `1 <= cost[i][j] <= 104`
Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
null
142
hey everyone welcome to Tech wide in this video we are going to solve problem number 142 linked list cycle 2. first we will see the explanational problem statement then the logic and the code now let's dive into the solution so here I've taken the first example from the liquid website so we need to find the node that is connected to the tail of the linked list right here minus 4 is the tail node of the linked list and it is connected to the node 2 so we need to return node 2 as the answer if there is no cycle we need to return none that's all the problem is now we will see the logic initially I'm going to have two pointers one is slow and fast both will be pointing to the Head node right then I will move my first pointer one step ahead then I will move my slow pointer one by one right so when I do like that the slow pointer and fast pointer will meet each other if there is a cycle exist else there will be none right so now we will start so I will move my first pointer one step ahead so my first pointer will be here and I will move my slow pointer to the next node then I will move my first pointer one step ahead so my first pointer will be here right then I will move my slow pointer will be here and now if I move my false pointer my first pointer will be here and the node -4 be here and the node -4 be here and the node -4 and if I move my slow pointer to the next node it is going to meet with the fast pointer so which means there is a cycle then I will make my slow pointer as pointer to and I will start again from the head node with pointer one this is a new pointer right now I will move my pointer run on pointer to the next node if I do like that my pointer one will be on node 2 and pointer 2 will also be on 0.2 so when both 0.01 and also be on 0.2 so when both 0.01 and also be on 0.2 so when both 0.01 and pointer 2 meets together in a particular node then that node is the node connected to my tail of the linked list right then I will return pointer 1 or pointer 2. that's all the logic is now we will see the code so 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 I will be having slow and fast pointers as my head right then I will write a loop until my fast and slow pointer meets then I will move my slow pointer to the next node then I will move my fast pointer one step ahead right then if my slow pointer and fast miter meets I will break out of the loop Loop right if my Loop successfully finish running then there is no cycle then we can return none if there is a cycle I will have pointer 1 Point into the head this is a new pointer right then pointer 2 will be the slow pointer that we have previously done then I will run a loop until my pointer one meets my pointer too right then I will move my pointer one to the next node and pointer to the next node as well then I will finally return pointer 1 when we found the node that is connected to the tail of the linked list right now we will run the code so the time complexity is order of N and space is constant space right thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
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
77
Hello hi guys welcome will roll question combination not to do is that you have box and item identical okay so you know how you can take that before you have that identical item how many ways are there NCR ways. Okay, earlier you had seen from these items inbox from this and from the nomadic item like this, click on his wait number methods, let me talk to you about four drops from play store, four drops and two items 422994 in the box, two identity items, pregnant from the item. Subscribe to comments feed that we will make mathematical sense of NCR. Okay, so look at the example and fat is 43.2 factorial visible 212 support is 43.2 factorial visible 212 support is 43.2 factorial visible 212 support is 42.2 tutorial BTC's 42.2 tutorial BTC's 42.2 tutorial BTC's 260 take care four drops two items what are their names Vansham four drops in how many ways You can replace them, give this to you, it is important that those items are 98100, I am saying this, give this madam, no entry, on this side there are 2 medium ones, I probably said it wrong in the middle, cut it, you are on the side of God and North Indian is of the companies. Like the names of both should not be identical and like the pundits, their names are one and two that the complaint here is that they have come here for two minutes, do not wash after giving something, but have to choose the laddu box, whereas this is for two boxes. Or this one for drops or this one just for that or this one for two options or this one for boxing in total 6 ways if you are talking about four drops how many two identical items in it It can be presented in many ways, this hundredth degree only gives you those two items, all you get are two boxes, yes no different day, choose * box yes no different day, choose * box yes no different day, choose * box Bisalpur or you have to choose yourself whose brightness will be either this boxing, this or this. Two boxes, these are drops, these are two boxes, these are boxing, so now we have the difference in this, so that of the chicks or after that, inside the box, they will be arranged in the items like you have distributed in Bantu, I will come here from these 6 of these. Village 121 This same selection did not get selected, that 123 maximum problem has been created, now it has come here and aaya hai means Hina has come, now it has come and has come but here there are 121 different if the romantic item song is different then the question was also asked by the commission four. There were two identified dreams in the boxes. Discussion Bluetooth * Lots of more were looted. Do the Bluetooth * Lots of more were looted. Do the Bluetooth * Lots of more were looted. Do the objectives because if you have two items in 2 boxes then this is nothing more than the selected item song of 472 boxes of more reversals. Lots of more two or 9 million support of delivery. There are some methods like this, it is of the same area, now here we get those notifications, so first the boxes will be in this letter, they will be placed in the morning and in those boxes, mute will be arranged, then one place is placed, then it is turned up, now for this type For One Dos Regiment, through One Dos, there was 2121 subscribe for each other, this time I want that if you are clear above, then you can go home but in the room, and you remember, they had 2001 plus 2 and soft all morning. If I talk about the whole, then that 2014 feels like three and 404 rates, so this is 400 to you and from you item, you have to click on two items in the remaining four boxes in four drops and this is equal to selecting Tumkur, now see I am level pina. Permit at the box office. The item was placed above the labels. The item was suitable for me. Go in it at the moment, listen carefully to this. Only people have got medical done on it. The item was above the level and there were boxes in the option that I If I go to this box, one used to decide, but talk about 182, it seems like Ramrao one used to decide, I go to the first box, 34 will be left in the second half, go to the fourth and then two came close, here all four were empty on you. Four drops were empty so I went from here once there was a war and this is appointed for you two boxes are your option I this time I will go in this or in this belongs to the ribbon this grows belongs to today site This vaccine is hot, if I go to this, then I will go to this, then 121 friends, if I go to this, then volume to bank, Larson, if I go, then one blank lines two, if I talk about here, then tubelight friends and if I talk about this here, then black one two lines. This volume Kumkum ko black one blank two to one iski baat karoon is plot mil gaya to two black one leen this weeks valuable 121 black piper for valuable 1512 opposition my voice four only its talk to tubelight like one blank two bank one life live Tea at the level within individual performance, according to your item option, cigarette smoke in the office but without clothes to wear, rather your 12 scientific Aadhaar number to bank is there somewhere, that sum of profit and blasted tube light will be switched off ok Now let's see inside the Congress, subscribe and keep it small, it is of great use, it has got a lot of use, so I have boxed it, I have kept it here, it is four drops, right, I am here. Deciding zero Drops is saying Mexico Now look taking the thing is boxer will lay I will keep the item in myself I am not keeping what I said here 4 Bahubali 2M have to be selected degree four chords drops have to be selected which alarm In which Mandal has set Arun Gurjar, if not, then here this level first box works, I have decided, I have put the item police, if I can put it right, I can put the item, it will not work to avert the war of Ulan planet or now this level. Above this box there are more boxes above the labels, this is the box level, this is the first box level, next settings, you will get the red third option, then it is putting it in the house, should I put it in the house, should I keep it in the temple, if you don't keep it, then it is just a memory of Vijay. If you keep it blank will not be liked, then come blank, if you keep it blank, then come blank chick. Expressed this wish completely that said here any meaning of yours Imran gives and any item blank sexual here blank festival Festival Subscribe To That Those Things Are Producer A Right And Kaustubh Is Right A Producer Right, Fury Also Night Was Cost Torch Light The Producer Of Wheat Crop Is A Plastic's Melody Bhakti Cost Torch Light Bill Will Be Right So All Four Commissions 34 Third Option A Blank Sexual Black Subscribe Now there are 16 items on top of this I want items I will keep West They will keep them I will keep them in circles I wo n't keep them So actually no box Its four boxes Both of its wishes have been expressed So 16 to 16 notes, according to the contacts, the entire expansion is complete, all the voices of every box, these people became one by one, 22 became 4080 16 Okay, now I will show you what I have reached, but now I want that so don't take it, I will show the full intensity of love possible. It's polythene cross rockstar refused four from us that we won't be able to do anything how many types are there one way and 30 is getting us more on the floor meaning four ways to have fun till now we have four drops you say that Yes, I call my waist like this, so this happened, there is a way, all four arms and legs are possible for virgins, coffee test is now we 431 is one of four, there are four ways to select music rock, where one of your item complaint is fixed, now These are the ones and if there are tantrics in the seam, then only they have become 1994 boxing, one thing, how many of these two should be given by na, and the other mp3 Hum to jahan teen aayi hoon teen aaye ho, this brother All this is this idea and also there are ongoing treatment chillies and methods so this one no inside this yes no yes inside this no yes for 4 minutes how many children do you have from opposite 42 that tiles 24 August 2002 one Subscribe this way, 12345 last two, I will complete this tour by clicking on my number here, you can make 10 using this, see here I will be of Congress, if you want then you should do this and also see this Total boxes of the current box, this is the selection, sort in how much should be the total, according to the items, do it comfortably, now section Monday, till now there are 20 boxes, total box, it is the turn of the comment box, once again one and a half combination, there is a lot of add light in this, the comment box goes up. It will have to happen next year it will be talked about first but not soft, Badi refused with mock, Uday Singh will continue to be the answer for business, it did not happen and these questions can be asked that the first one refused, if the bandits refused, then take my new Badi. Now if we have to select here then we will do it one day and on that day we will become complete from one to three idiots in it, till the time we have bravery we will increase them on Thursday. Up here, we turtles want that we Wash three here and appoint 2 inches from here in the video, then it is needed, okay, if it is equal to the section of tourism, then we will do it. Come friend, make you the king of the country. In the second moment, the government has been edited and will only stop and go. I have made a mistake in talking nonsense. Tears will do it. Okay, this area is vacant once. Chant is a robber. Well, before this, I need this record. I both have dance class and are admitted in the festival. So, first of all, call me. A subject stitch submit that value special account Parmeshthi is shown Congress showed the world our Shankara have permitted Within a day the box came to this option and the item was taken Here bring the box and the item is not there we came to the option ok There is Nehru Place among us, I do Flipkart, you must have understood, let's meet in the next RAW, I am having fun, so I request you, friends, tell me the quality, tell friends, they will also enjoy the fun in the war, thank you, no.
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
401
so today we would be solving lead code question number 401 that is binary watch and what the question says is that uh we are given with uh timings that is turned on time and this is a binary watch so the hours in it is in the power of two to the power 0 to the power 1 to the power 2 to the power 3 similarly uh these words was the RS and these are for the minutes to the power 0 to the one two three four and five okay two to the power okay timings are given in that way so we need to figure out we are given and these are switched on these are a single number like 16 is a single number 32 is a single number 2 is a single number one single number four is single number eight a single number so we need to figure out we are giving with the number of turned on LEDs so each LED is behind every number like 180 is behind 16 180 is behind 32 One LED is behind four one LED is behind this and we will just neglect this pm1 already okay so we are given with number of turned on LEDs we need to tell we need to print out in a string format a vector of strings the number of timings we can make like for example it said that I will switch on only one LED so what all are the timings that we can make 0 1 with one minute two minutes four minutes eight minutes 16 minutes 32 minute that is we took once every LED and if we had not taken the minutes one we would have taken the hours one so one 2 4 and 8 okay single time each now supposingly I was given three so I would I can take 1 2 and the timing for hours should not exceed 12 we are given with it that the timing should not exceed yeah 0 till 11 okay hours one and zero to fifty nine the minutes one okay that should not exceed this much the minute should be in the range of 0 to 59 and the r should be in the range of 0 till 11. so if I just take 8 then I take four because I am combining these two hours so now and I am given with turn on ledger 3. so now here I have received 12 I cannot go beyond 12 so I'll then be moving on to my minutes hand and then at minute hand I can choose from these variety okay I can switch on this because I am left with only one LED two I took from here so one two three four five and six so six different numbers I can make because I am left with just switching on One LED two I am done so I can just do this or there can be a better option that I could have chosen to from here then all six two from here and all six or any one from here then from any four of these I can combine so that is the way I need to choose that I need to switch on those LEDs and I need to tell the permutation and combination of times that I can make okay so let us move on to the question I need to return a vector of string so I would be creating a vector of strings vector of string resultant okay then our answer variable would be gone called and I would be passing my rest Vector okay then comes the main thing the number of turned on LEDs then the initiating start point of every led by this I'll tell you and there is one more thing that we need to handle that is what is the time right now actually the time would always be in a pair of hours and minutes so we would be taking a make pair and that would be carrying initially 0 comma zero okay that is done we are done with this and at the end we would be returning Twitter that is the spelling for you return sorry my mistake my return our result we would be running our result now comes the time for R function and before our before creating a function I would uh I would say that we uh we should create a vector of int that is for the R's hand and that would be 1 2 4 8 and yeah that is it and for minutes and I need to create a the vector as in one two four sixteen one two four eight sixteen sorry my fault 8 16 and at last 32 so if we have these things now let us create our function void answer we have passed our Vector of first string Ampersand res okay that would be carried on then I would be passing my um pair that is of int comma int and that's what I would initially name it as time because that would be carrying time okay and number that is the turned on time okay the turned on time or I should say it turn down time only I should say turn down time only turned on time only and at the last I would be carrying my start Point what is the start Point let us see let us have a look I would be explaining what we are really doing let us first go on creating the function I know that there would be some at a moment in which my turned on lights would be completed there would some there would be something in my time variable so I need to extract my time okay I need to extract my time and just insert it or just insert it in my resultant Vector of strings okay if turned on time is equals to zero then what to do then please result 10 dot push back what to pushback just convert to string the hour one that is time DOT first very good then what then let us check if time dot second if that is greater then if that is sorry if that is less than 10 then we need to represent it in this format if this is 1 then we would in minutes and we would say 0 1 2 then 0 2 if it would be 16 then 16. okay so if that is less than 0 then what to do then please add a 0 before it is no need to add a zero because that is a two digit number and after though after doing all this please just convert the second one to string the second one the time dot second and that is it please do these things if the turn on time goes to zero and yes one more thing a return okay next thing we would be iterating over all the timings okay we were we would be iterating over all the timings for and I is equals to start time start point till I is less than our DOT size Plus minutes dot size and I plus we would simply be saying if I is less than r dot size then please if this is the case then please time DOT first can you please add this timing that is hours at I and please do check if this time that we have gained up till now if that time Dot first is less than 12 in that case only please do call my answer function and let us iterate over more timings that can be added okay more timing that can be added to this time load first that okay to this time of first for this function being called right now okay for this function in our stack for this function at this stage in our stack if this is less than 12 then please do call more timings the time remains as it is and if you have taken this time this are that I then one LED has been used so just uh remove its count so uh turned on time turned on minus one that is so and the start Point what is my new start point that would obviously be I plus 1 okay for this one okay if I is not less than r dot size then I am left with just one option that is I need to go towards the minutes one and more thing after doing all this time DOT first minus is equals to ours at i y after I had checked for I am at this eye okay I am at uh some minutes and some hours and I checked all combination keeping this hour hand constant okay now I just need to erase this r hand from my time DOT first to get me along with the rest hours and keeping them as constant and calculating the timings okay the different timings format turned on number of Rights okay so at this moment this r hand was constant now I just need to erase this R end and let me move on to the next r hand similarly uh time dot second plus is equals to minutes minute it's minute or minutes it's minutes I am using minutes only yeah minutes at I minus r's dot size y because we have been using they are both size as and whole okay and then I also check if time dot second if it is less than 60 then only please call my function pass in the rest pass in the time please reduce the turned on time by one because we have used this number increment my eye go on and after doing all this after keeping this minute as constant please do subtract minus is equals to the same thing okay that is it after doing all this I think we are done if there would be any error that would uh be because of spelling mistakes other than that I do not think that there is an error yeah let me submit it let me compilation error one two four okay there is a comma now I think that is good again Bool um on this dot pushback to string timer first Plus two string timeout first time Dot okay I think this bracket should not be here if it is less than then please use this format and then just add it and please do please sorry this should be here then that is it yeah that is good to go now here I is less than ours it is ours yeah should I make it r or rest or all I have used various times are okay R's RS if it is less than RS hours and hours okay that is ours so I think that is it we are good to go oh semicolon that this time please yeah so we are done with it will be submitted because I have again I have done it previously uh just to be very clear the logic is clear uh the implementation was clear and I think the explanation was also clear uh and I do not uh think that there is anything more to discuss yeah this question is a backtracking question and this is important because this is asked in Google this is a lead code easy one but this was asked and to be very honest I could not make it I had to see the solution but to figure out the solution was also a major part okay so if this easy question can be asked in Google with such manipulations then we can expect more tougher questions but for now as of now we are done with it uh if you have any doubts please write it in the comment section do share your thoughts and this was it for the video let's meet in the next one till then bye
Binary Watch
binary-watch
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. * For example, the below binary watch reads `"4:51 "`. Given an integer `turnedOn` which represents the number of LEDs that are currently on (ignoring the PM), return _all possible times the watch could represent_. You may return the answer in **any order**. The hour must not contain a leading zero. * For example, `"01:00 "` is not valid. It should be `"1:00 "`. The minute must be consist of two digits and may contain a leading zero. * For example, `"10:2 "` is not valid. It should be `"10:02 "`. **Example 1:** **Input:** turnedOn = 1 **Output:** \["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"\] **Example 2:** **Input:** turnedOn = 9 **Output:** \[\] **Constraints:** * `0 <= turnedOn <= 10`
Simplify by seeking for solutions that involve comparing bit counts. Consider calculating all possible times for comparison purposes.
Backtracking,Bit Manipulation
Easy
17,191
775
welcome to april's lego challenge today's problem is global and local inversions we have some permutation a of zero one through n minus one where n is the length of a so basically we have a permutation of numbers between zero to n minus one it's going to be reordered in some way but each one of these numbers are going to be distinct now the number of global inversions is the number where i is less than j and a of i is greater than a of j so here with this example we can see that one has one global inversion because it's greater than zero but if we had like other numbers less than that afterwards those would also be global inversions the number of local inversions however is where a of i is greater than a of i plus one so here we can see that one is the only global inversion because it's greater than zero and that's the same as the local inversion because they're right next to each other here we can see there's gonna be two global inversions one is greater than zero and two is greater than zero but the only local inversion here is this two is greater than zero but one is not greater than two now big hint where can we place the zero for an ideal permutation what about the one all that means is if we had want to have minimize the number of inversions it would just be an order being sending ascending order zero one two there are no inversions right okay so the first approach i thought was finding the number of local inversions is pretty trivial we can do that in oven time just looking at the previous number to see if it's greater um or not than this index number if it is we can just add one there but what about global inversions that's a lot trickier right so if we had i don't know um say three two zero one uh we can see that this is the ideal permutation we know at three this has three global inversions right because um there's three is the greatest number and we know there's three numbers below that here we can see that two there's gonna be two zero there's going to be none and one there'll be known as well because that's the last but to find global inversions is a little bit tricky you can't do it in an oven time because while we're going through we basically have to remember all the different numbers that we have already seen so we need to rephrase this problem here rather than thinking about oh how do we count up the global inversions really the question is return true if global inversions and local inversions are the same right and kind of figure that out what we would do essentially is use this number here and just check to see if the difference between the two is greater than 1 or not see with 3 we know that we can't have a number bigger than one otherwise it's going to have more global inversions same with here with one we can see the difference is one that would mean this could have more than one global inversion and like if these were flipped say this was um i don't know like one here same thing here with one zero we know that uh if this was greater than like here we know it's only one inversion but if it was greater say it was something like kind of messing this up here but if the difference was like 2 like this then we would actually know well we've probably seen another number less than this so this actually could not be a local inversion so basically what we have to do is move through here and check the difference between the index number and the i the ideal position and if the difference really the absolute difference is greater than one we know that there's more than one global inversion so i'll show you what i mean what we can do is just initialize the length of a and say 4i and range of n at any point if the absolute value of i minus a minus i is greater than one then we can immediately return to false because there's more than one global inversion then otherwise if we can get through this whole thing that means the number of global inversions and local inversions are the same so this would really be it this would be oven time and actually use um all events or constant space and there we go accepted now i realized this solution is very simple um which surprised me but i definitely was not easy to come up with um because the first approach i was trying to do was find a number of global inversions so only when i did some research and finally figured out yeah we need to think more about what the problem is asking here we don't care how many global inversions are we just want to know if the number of global and local are the same and once you realize that you can kind of play around with the arrays and realize the difference between the i and the number itself can't be greater than one or else there's more than one global inversion okay all right hope that helps i don't know why these questions are so hard this month i guess they're really pushing us but hey it's better than just getting easy problems all the time and not improving so thanks for watching my channel remember do not trust me i know nothing
Global and Local Inversions
n-ary-tree-preorder-traversal
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
Stack,Tree,Depth-First Search
Easy
144,764,776
347
hey everyone welcome back and let's write some more neat code today so today let's solve top k frequent elements i really like this problem because it's pretty clever and once you figure it out the code is really easy to write so we're given an input array nums and an integer k and we want to return the k most frequent elements that appear in the array nums we can return the answer in any order so for example we have this input array three ones two twos and a single three and we wanna return the two most frequent elements right so we know that the most frequent is of course one it appears three times so we add a one to the output the second most frequent is two so then we add a 2 to the output and that's all we want now if k was 3 of course we'd add the last element k is never going to be greater than the distinct number of elements in the input array so that's good for us and our input array is always going to be non-empty so for example for each be non-empty so for example for each be non-empty so for example for each value right we're going to count how many occurrences it has so for example one occurs three times two occurs twice and three occurs once and then we can take this basically this list of pairs right then we can sort it in ascending order right so basically it's already sorted in ascending order right because the most frequent is here the second most frequent is here the third most frequent is here right now of course sorting it in the worst case right basically if every single value in here was distinct and we wanted the top k distinct values we'd get a time complexity of n log n right but we don't necessarily need to sort the entire thing because we only want the top k frequent elements so in another solution we could actually use a max heap so we would still do this whole operation where we count the number of occurrences of each value and then we'd add each pair to our max heap and the key of this max heap would of course be the number of occurrences right so the count right and then we'd pop from our heap exactly k times so why is this more efficient well we know popping from the heap well first of all we when we initialize our heap we're going to add this entire set and there's a function called heapify i think that can do that in actually linear time so big o of n time so that's the good thing and of course we know we're only going to be popping from the heap k times each pop is going to take log n and we're going to be doing that k times right so that's going to be k times log n right so that's a little bit better than n log n at least as long as k is less than n right but it turns out that there's actually an even better solution there's actually a solution that can be done in o of n time linear time so big o of n time and big o of n memory but we are still going to be using this exact a technique where for each value like one we count the number of recurrences like three so this problem can actually be solved in linear time if you use the algorithm called bucket sore so when you first think of bucket sort this is probably what you're going to think of the way bucket sort is usually taught is that for each value for example 1 we're going to take an input array right this is our input array this row is the indices the index of the array and this is actually going to be the value so for example for one we're going to go to the posit the index one and in the value we're gonna put okay one occurs exactly once now we're gonna see a second one we're gonna say one occurs twice right basically we're going to go through the input array count how many times each value occurs and then in our input array put that count for that index right map the value to the index and then put the count of that value so 1 occurs 3 times 2 occurs twice 100 in this case occurs once now this algorithm would be linear time if our input values right were bounded for example if we knew for a fact that every value was between 1 and 10 then we would know that the size of our input array is also going to be 10 right but in this case the values are unbounded right like this could have been a million and then the size of our input array would have been a million even though the total input array size is only six right we have six elements but then that array where we actually store the buckets sort values is going to be unbounded right and also we want the top k elements this still isn't very clear of where exactly the top k elements are actually going to be so in this case this type of bucket sort doesn't work but there's another way we can do it so in this case you can see for our array where we're going to be doing the bucket sort the index i was using the each value in the inquiry for example you know one was being mapped to index one right and there we were storing the count there's actually another tricky way that you can do it that will lead us to a linear time solution so if we're pretty clever this is what we're going to do for the index we're actually going to be mapping the accounts of each value and in the values we're actually going to have a list of which values have exactly this particular count for example a hundred right we know that a hundred occurs one time so what we're gonna do is for this position one we're gonna say okay this value occurs only once a hundred occurs one single time which value for another value in our input array 2 we see it occurs exactly twice right we can count that with a hash map pretty easily and then we'll say okay this value occurs twice so in the position 2 index position 2 of our array we're going to add that value 2 is the value that occurs twice we see a last distinct value in our input array 1. we count it occurs exactly three times so in this position index 3 we're gonna say okay there's a value a single value a one that occurs three times now it's possible maybe we had a third three right maybe two occurs three times in that case we would actually have multiple values in this position right but in this case we can see one occurs three times two occurs twice 100 occurs once so they're all going to go in separate positions and then you know once we've taken every single input value and then and counted how many times each value occurs and then put it in the appropriate spot in this array what are we going to do well we want the top k values right the values that occur the top k values that occur most frequently right so what are we going to do we're going to start at this end of the array we want all the values that occur six times why are we stopping at six though why don't i extend this array farther right seven eight a hundred right why did the indices stop at six notice something about our input array is size six right so that means if every single value in the input array was the exact same the most number of times a value could occur would be exactly six time so the cool thing about this in about this new array that we're creating is it's bounded by six or well technically six plus one because we do have a zero but that's not actually necessary but it's basically it's proportionate to the size of the input array right so you know when we're scanning from right to left or however we do it we're only going to be doing that we can scan through the entire thing in linear time now in this case we see six there's no values that occur six times so we can't find our top k element in that position we'll try the same thing with five no values occur five times four no values occur four times three oh a single value we're going to go through every value in this array there's only a single value in this case but we do see a 1 occur so to our result we want the top k values the top k occurring values we are going to add a 1 to that 1 occurs most frequently in the input array so we add one to our result we need one more because i think we were looking for the top two values k in this case is going to be two so now we're going to go here which values occur twice a single value and that value is two so we're going to add that to our output array so now we've gotten the top two values and then we can return this array now why is this linear time again because remember the max size that this array could possibly be is going to be about equal to the size of the input array right because we could have a value for example one could occur six times in that case we'd have one over here now what if every single value in the input array was distinct right that's another extreme what if we had one two three four five six in that case this position would be empty because no values occur six times no values occur five times four times three times or two times every one of these six values would go in this position at index one reason being each one of these occurs exactly once so in that case we'll have all six values concentrated over here and that's still going to be linear time because yes we are going to be iterating through this entire input array which is going to be big o of n and then we're going to add another big o of n to that right big o of n plus big o of n because we're going to have to iterate through six values in exactly one position so that's still technically linear time now we are creating this uh array to help us and we're also going to be needing a hash map to count the occurrences of each value in the input array so the memory complexity is also going to be big o of n with that being said let's jump into the linear time code it's pretty easy once you can identify this trick so we are going to use a hash map to count the occurrences of each value or also the array the special array that's going to be the same size as the input array about is going to be called frequency basically you know the index is going to be the frequency of an element or the count of an element and the value is just going to be the list of values that occur that particular many number of times so i'm going to have an empty i'm going to initialize this as an empty array the number of empty arrays that go in this is going to be about the size of our input plus one so now i'm just going to go through every value in nums and just count how many times it occurs so for count of this particular end value we're going to do 1 plus what its current count is count dot get n now if n doesn't already exist in our hash map or dictionary we're just going to put a default value of zero so this will return zero if it doesn't exist but this is how we're going to be counting the number of times each value in nums occurs next we're going to be going through each value that we counted so n c in count dot items because that's going to return the key value pair every single key value pair that we added to our dictionary and for every key value pair for every number and count i want to change the free i want to in the frequency array i want to insert so for this particular count remember the count is what's going to be the index so at index count we're going to append to that list this value n what we're saying is this value n occurs exactly c number of times and once we've done this we've basically initialized everything we need to so now we're going to have our result output right we want the top k elements so 4 and so we're going to be iterating through this array frequency in descending order right because we want to start with the numbers that occur most frequently so for i in range length of frequency minus one which is the last index and we're going to go all the way up until zero and we're going to be going in descending order so we're going to put a negative 1 as the decrementer and we're going to go through every value so for every let's say n value in frequency at this index i because we know everything inserted in i is actually another sub list so it could be empty or it could have some values whatever it does so let's say n is non-empty then we're going to go n is non-empty then we're going to go n is non-empty then we're going to go ahead and take that end value and append it to our result because we're basically getting the end value that occurs most frequently now when are we going to stop at some point our result output is going to be the exact same size as k because we're guaranteed to have at least k values in our input array so once that happens once if the length of result is matching exactly k that's when we can go ahead and return result we know this is guaranteed to execute at some point so we don't have to put a return statement outside of the loop and that is the entire code so we could have solved this problem in decent time if we used a heap it wouldn't be too bad k log n i think that's a doable solution but with this kind of neat trick we can do this in big o of n time and i hope that you did learn something maybe a little about a little bit about bucket sort this problem definitely taught me something when i first solved it and i know many people have been requesting problems and i'm trying to get to all those requested problems as quickly as i can so i hope it was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
73
in the spirit of learning continuously sometimes you will encounter problems that do not test your coding skills primarily it does not matter how well do you know data structures or how good of a code you can write sometimes it is just about the logic you are taking and how are you solving a problem that means we are testing out your problem solving skills once the problem is set zeros in a matrix on lead code so you're given a matrix and you have to set zeros in rows and columns based on a certain condition correct let us see what we can do about it Hello friends welcome back to my Channel first I will explain you the problem statement and we will look at some sample test cases going forward we will try to approach this problem in a Brute Force way and see its limitations then we are gonna optimize it step by step first we will optimize it according to time and then we are going to optimize it according to space after all of this we will also do a diagram of the code so that you can understand how all of this actually works in action without further Ado let's get started first of all let's make sure that we understand the problem statement correctly in this problem you are given a m cross n Matrix that has some integers right now you have to Output a resultant Matrix such that if any element is 0 you have to convert all the other elements in the same row and the column to 0 as well so what does this actually mean let us look at our first test case so you are given this Matrix right and this has some integers according to the problem statement if you find any 0 in The Matrix then you need to convert all the other elements in the same row and in the same column to 0 as well right so for this particular test case your resultant Matrix will look something like this correct similarly let us look at our test case number two in a test case number two once again we have a very big Matrix right and if you check the zeros I have two zeros in here what I need to do is I need to convert all the other elements in the same column and in the same row two zeros so for a second test case this Matrix will be our answer right so this is what you have to do primarily in this problem however there is one challenge the only challenge in this problem is can you do all of this in place simply means that you are not allowed to take any extra space to arrive at your answer for now if you feel that you have understood the problem statement even better feel free to try it out first otherwise let us type into the solution a good developer will always try to come up with a Brute Force solution first because then he can verify that hey a solution to a problem exists so what is the most naive way that you can approach this problem let us say you are given this sample Matrix right and I have to find out a resultant Matrix the first way could be that okay I make an extra Matrix where I will store all of my temporary results right and then what I'm going to do is I will Traverse each element one by one if an element is 0 what I can do is I can simply copy it in my new Matrix right next when I move to the second element I will just check if I find a 0 in the same row if yes I will simply write down this element as 0 similarly I will go on to my next element and once again I check my row I find a 0 over here so okay I will once again write a 0 and then I can copy the 0 straight away to my new Matrix so this is how you populate one row similarly you can go over each column as well you will look at the next element 3 right you check if you find a 0 anywhere in the row no do you find a zero anywhere in the column yes so what you simply do is you will write down a 0 over here and then move on to your next element once this Matrix is filled it will look something like this correct and what you can do is you can simply copy all of these elements back to your original Matrix or you can return this new Matrix right and this solves your purpose this is the correct answer but do you see the problem with this approach in this approach to identify the state of my new element I have to Traverse the entire row and all the columns again and again correct for every element you will have to Traverse the row and then look at the column right so this ends up taking a lot of time hence this is not a divide solution what can we do about it let us try to start optimizing it cool to begin our optimization Journey once again I take up the same test case right and in a Brute Force solution what was taking up the maximum time we took a lot of time traversing through all the roof again and again right just to determine if we have any zero in there and we did the same for columns so you should try to think around that you need to find a way first that you can store that revert and you're not evaluating it every time so what I can do is I can take up some temporary space just to store that hay this row has a zero and this column has a zero so you can see that I take up two areas to store all of this interim result what I will simply do is I will Traverse through my first row I see do I see a 0 in here yes so I will simply Mark a true in here correct now move on to the next row I do not see a 0 in here so I will mark this as false similarly for the third row and similarly for the fourth row now do the same exercise for each of the columns in the First Column I can see a 0 over here right so I will mark this value as true I cannot see a 0 in the second column so I mark it as pause no zero in the third column either and I can see the 0 in the fourth column over here so I marked this value as true correct now Things become very easy what you will do is you will start to Traverse each element one by one and for each element you will just check do you find a true anywhere in the row or do you find a true anywhere in the column if you find a true what you're gonna do is you will replace this element with a 0 right so now move on to the second element you check its row you see a value true over here that means there was a zero somewhere so what I will do is I will simply replace this value with 0. now move on to the next value you see a true once again over here so Jeff replace this value with zero the next value is already 0 so move ahead now move on to the second row you see the element 3. check the Boolean value for its row this value is false it simply means that no 0 exists in the row you don't have to check it again so you're saving time over here and check if you find a true in the column value you find a true over here that means there is a zero so you need to just simply write down 0 over here now move on to the next value you see a 7. once again just check these two values if one of them is true that means there is a zero if both of them are false that means there is no zero in the entire row or in the entire column so if both of them are false just copy the value as it is so just keep on doing this for each value in the original Matrix and what we're going to do is you will replace the values as and when required ultimately your Matrix will start to look something like this and you can see this will be your answer correct so with this approach we also achieved two more outcomes first of all we saved a lot on time right because we are not iterating through the entire Matrix again and the second Advantage we got is we are doing all of this in place we are not taking an additional metrics to score some temporary rewards we are modifying the contents of this original Matrix right so we achieved two outcomes but we took some extra space to store this intermediate results right so that is one area where we can still optimize so how can we go about optimizing even this when you're trying to optimize you first have to identify what do you want to optimize in The Brute Force solution we were optimizing for time right hence we figured out a solution by taking a help of some extra array that can store our intermediate rewards correct now you want to optimize for the space that you are taking you take some extra space just to store all your intermediate results right and that is what you want to optimize so once again let us take up our CM example and we will try to optimize for space as well and there is a very neat little trick which you can use to optimize for your space so from our previous example we took some extra space to store intermediate results right what you can do over here is in this example you can use your first row of the Matrix and the First Column of your Matrix to store all of these similar results I'm going to show you how you can do it in just a little while so now what we're gonna do is just treat this inner Matrix as your sample Matrix and iterate over each row one by one so when you iterate over each row if you find a zero anywhere over here what we're gonna do is you will mark this first value as 0. and this simply means that the value of false and then you will be able to relate it to the previous example in a next row I do not find a 0 over here so let this be 1. in the next row once again I cannot find a zero full let this be 8. so when I went through my first row I found a 0 over here so what I'm gonna do is I will mark this value as 0 so once I mark this value as 0 I see a 0 over here right when you go through your second row you do not find your zero so do not do anything go through the third row and once again you do not find a zero so leave out this value now do the same thing for each column look at this column you do not find a zero so leave out this value go through this column you find a 0 over here right so replace this value with 0 and your Matrix should look something like this go through the third column and you do not find a zero so don't do anything with this cell yet right The Next Step will be to copy all the zeros that you already had in your first row and your First Column so I had two more zeros over here right so I will copy this 0 and I'm going to copy this 0 right you can see that some of these values are unchanged right but wait for it we will ultimately arrive at our answer now you have completed one iteration of your Matrix right in the second iteration once again start traversing each element one by one and this time you are going to follow the approach that we just took in our previous example if you're looking at this first element that is four just look at the column index and the row index if any of them is zero that means there is a 0 somewhere in the row or in the column so what I'm gonna do is I will replace this value as 0. now as soon as you see a 0 don't do anything about it because it is already a zero now move on to your next value that is 2 once again look at the first row and the First Column if you find a zero anywhere that means there was a zero somewhere so I'm gonna convert this value again to 0. move on to your next value that is 3. now look at the row index that is 1 that means there is no zero anywhere in the row look at the column that is one again that means there is no zero in the column answer so this value is going to remain unchanged and I will write down 3 over here right look at the next value 1. compare these two indexes you find a 0 so replace this value and put a 0 in here look at the next value 5. now compare these two values if you find a 0 so what I'm going to do is I will replace this 5 again with a 0. look at the next value seven and look at these two indexes eight and one none of them is zero so that means this value will be retained and it will be 7. the last two values will also be converted to a zero just try to do this as an exercise now you have completed 80 percent problem the did not iterate through them correct to find out these values what you simply need to do is just look at the first row and First Column if you find a zero anywhere over there just convert all of these values to 0. in this case you can find a zero so I'm gonna simply write down 0 in my first row entirely and 0 in my first column and you already have all of these values right and that's it this will be your final answer so we complete this problem in two steps basically right in the first step we took advantage of the first row and the First Column as an extra space where we could store our intermediate reverse right once we got these intermediate results we were able to fill in the rest of the Matrix correct and in the final step what did we do looked at our remaining first row and First Column and replace these values as required correct so you can see that we did not take any extra space that means in place and also we were also time efficient now let us quickly do a try run of the code and see how this works in action on the left side of your screen you have the actual code to implement this solution and on the right I have this sample Matrix with me that is passed in as an input parameter to the function set zeros oh and by the way this complete code and its test cases are also available on my GitHub profile you can find the link in the description below beginning ahead with that dry iron what is the first thing that we do first of all we create two Boolean variables that will Mark if you find a zero anywhere in the First Column or anywhere in the first row right but remember that we will use them at the very end right next what do we iterate through our array to set our markers in the first row and First Column right so when this Loop runs what will happen is it will look at the values in this inner Matrix and if it finds a 0 anywhere in any column it is going to replace this value with a 0. so in the second row as well you find a zero so this value will get replaced correct so right now what we have just done is we have determined the markers in our first column and in the first row now to move with the intermediate step what do we have to do we will replace our entire inner Matrix right and to do this we run a for Loop that will look at this inner Matrix and we'll compare these indexes as the markers if it finds a zero anywhere then all of these values will be marked as 0 and if it finds a 0 here all of these values will be marked as a zero correct so once this Loop ends we this value becomes 0 and all of these values will become 0. because you found a 0 here and here right now moving ahead we are just remaining with our last remaining checks right and that was that if you find a 0 anywhere in the first row or anywhere in the First Column we do find a 0 over here right and these are marked by the first row and the First Column Boolean variables we already did set them first time we were iterating through our original Matrix correct and using this value we will replace our remaining elements to 0. so once this Loop ends your resultant Matrix will look something like this the time complexity of this solution turns out to be order of M cross n because you are traversing through the entire Matrix three times right and the space complexity of this solution will turn out to be order of 1 because you are not using any extra space and doing everything in place right I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that the most interesting bit about this problem is to do everything in place when you have to do something in place that means you cannot take any extra space sure it is perfectly all right if you're just taking one extra space to store maybe some temporary value and then use it for swapping that's perfectly fine but if you are taking an extra array of a temporary space that violates the concept of an In-Place violates the concept of an In-Place violates the concept of an In-Place technique so in place mechanisms are very handy in tight situations when you're limited by space and in scenarios where you're not allowed to write new files think about it there are also some sorting techniques which work in an In-Place manner so while going through In-Place manner so while going through In-Place manner so while going through your coding Journey have you found any other problems that worked in an In-Place manner what about the farting In-Place manner what about the farting In-Place manner what about the farting techniques how do they work can you find some instances that can be done in an In-Place technique while following this In-Place technique while following this In-Place technique while following this video did you face any problems tell me everything in the comment section below and I would love to discuss all of them with you on my website study I have also covered a I have also covered a I have also covered a section on in place techniques be sure to check it out as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
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
422
hey everybody this is Larry this is me doing uh the first weekly premium challenge of the uh after March weekly code there I don't know whatever we're doing this Farm uh let me know what you think uh oh man I don't even know what I'm saying anymore hit the like button hit the Subscribe button join me on this card let me know what you think about this problem and let's chill together let's do it uh today's problem is 422 right at word square so giving it a way of strings words return true of it forms a valid uh word square okay a sequences of strings form a ratted word square of the cave row and column reach the same string uh what does that mean uh first one first come with ABCD okay uh bnrt if the case okay I mean I get it but I'm just trying to understand if there's anything weirder I mean there is something weird about empty spaces I don't know that um like what if you have something that's emptied in the middle what does that mean like for example if you try something like uh let's just say it's missing the middle does that one is it rather than input okay so just return Force if it's not then or do you combine the words together it's very unclear uh maybe that's why there's some downloads because I don't think I necessarily understand this but okay fine um like do we keep merging or do we just because I don't know n is only 500 so we could do something 500 square really quickly right we just do it for each okay so let's do it I mean I don't know anymore uh and then we'll maybe we'll find out why people uh hate this poem right so yeah 4K and range of n um so now I mean what's up K is obviously that word but then now we get the vertical word right so if just to be lazy if length is oh wait no yeah I have to do the thing so then um yeah for I in range of n um maybe word is uh vertical word to say as you go this we're gonna go and would stop uh K sub I right and then yeah if I have to check that it is um I have to check bounce that's one right so I have to check that if length of word sub k um is if I is less than this then we do it yeah oops and then basically if length of vertical word is not equal to length of word sub k then I guess we can early terminate uh but otherwise um yeah I guess now that we could do or if this string is not equal to words of K then yeah then we terminate and then return true otherwise right I don't know I mean this is supposed to be easy so it should be whatever um I have a lot of typos basically word with words um got this one wrong what is the world here I return true but it's false the third read and Lead okay I mixed it up it should be ik um and then this is I and this is K all right I don't know how that makes it right oh I guess it's just return it reading the same word comparing it to itself that's a little bit silly all right oh I mean okay I wasn't sure if there was gonna be like a weird uh thing but I guess maybe just not assuming this weird case is already good enough I don't know how to handle it to be honest like do you cut it off or whatever but I don't know I guess I don't need to know um what is the complexity here right uh what is n anyway yeah and it's 500 so um we look at each character uh at most twice right so uh so this is gonna be linear time than your space um and you don't even actually need to do the linear space is just me being lazy and kind of com you know doing it this way um you could actually just do like a pointer and then keep going down and then comparing one character at a time so you get constant space right um keeping in mind that when I say linear space of course the size of the input is n Square so this is O of N squared which is linear time right well that's a linear when I say linear time that's what I mean because the in the size of the input is uh n Square so linear N squared is going to be the time um cool yeah um I think that's all I have for this one I don't know what to say about it I mean it's supposed to be easy so I don't know um that's all I have with this one let me know what you think stay good stay healthy to good mental health I'll see how later then take care bye
Valid Word Square
valid-word-square
Given an array of strings `words`, return `true` _if it forms a valid **word square**_. A sequence of strings forms a valid **word square** if the `kth` row and column read the same string, where `0 <= k < max(numRows, numColumns)`. **Example 1:** **Input:** words = \[ "abcd ", "bnrt ", "crmy ", "dtye "\] **Output:** true **Explanation:** The 1st row and 1st column both read "abcd ". The 2nd row and 2nd column both read "bnrt ". The 3rd row and 3rd column both read "crmy ". The 4th row and 4th column both read "dtye ". Therefore, it is a valid word square. **Example 2:** **Input:** words = \[ "abcd ", "bnrt ", "crm ", "dt "\] **Output:** true **Explanation:** The 1st row and 1st column both read "abcd ". The 2nd row and 2nd column both read "bnrt ". The 3rd row and 3rd column both read "crm ". The 4th row and 4th column both read "dt ". Therefore, it is a valid word square. **Example 3:** **Input:** words = \[ "ball ", "area ", "read ", "lady "\] **Output:** false **Explanation:** The 3rd row reads "read " while the 3rd column reads "lead ". Therefore, it is NOT a valid word square. **Constraints:** * `1 <= words.length <= 500` * `1 <= words[i].length <= 500` * `words[i]` consists of only lowercase English letters.
null
Array,Matrix
Easy
425,777
1,224
hello friends today i'm going to talk about leader code 1224 maximum equal frequency the problem is that given an array numbers of positive integers return the longest possible index of an array prefix of nums the condition is that you are allowed to remove exactly one element from the prefix array so that every element that has appeared in it will have the same number of occurrences and here this example here and we have eight numbers we have this called this prefix this has seven elements here and after we remove five we will get this two six elements for each elements it uh appears exactly twice so this is a valid candidate solution okay so we return 7 here and for this when you move 5 and we are getting the 13 for 13 where you move here we is f element appears exactly three times so the total 13 is a valid solution and etc so let's consider the problem here and for this problem let's consider this example and my first nail idea is that maybe we can come out with that we first when you move from the end to the beginning that means that when you move file and we check whether it's a good candidate um whether we remove the three whether it's a valid candidate or solution and you move three and five when we finish it uh when we get a value solution during the moving that is the answer because we are going to we need to find the measurement prefix and nums and for example if you remove five here and we will have this array and we will we can figure out we can use a hashmap to get the frequency of each number the frequency number in this case and in this case is we can see that if we remove file and we will get the two and one two and three and has two so we'll find that this is a valid condition so we return 7 for this case and this is the final solution and for this case is the example here second example here where you move to and we get this map 1322 and when you move one element from this array we get this number has exactly twice so we return to five and this is the final answer now the problem is transferred how do we find the clinician is satisfied the continue that for that means here for uh the solution is satisfied if for example here so how do we film finals then i also think that we can deter each element one by one right and for this element if we deliver there are one two three four unique elements here we if we remove the element five and two here we will get the new hazy map for the new hammer then we can charge whether it is certified whether although k has the same value and if we remove file here we can this all the key has the same value too so this is a valid solution so for every candidate we have to figure out uh to remove one to uh to remove one by one so the last solution um it takes uh for travel sentence or n time then we figure out the condition the conditions for each one takes the worst case it is or n time then overall tills or n square time this will cause time limited executed because we have the here is ten pounds five little the lens will be ten power ten generates generally 10.8 is acceptable generates generally 10.8 is acceptable generates generally 10.8 is acceptable for new code and the second idea is how do we optimize this to the on organ or end time actually we can um optimize to end time so here we have to define three in variables the first variable is for the maximum frequency the mass frequency indicates the biggest number of occurrences for the kind of norms array and another wherever is dictionary counts that is about the frequency of each number like from this array we get this array we will get this hash map this is called digital cons then the credit parties we have defined define a third variable is another hashing map because we call it additional times that means the frequency of the numbers and here example for example we have the element here we use a digital number not you know your screen number is easy to explain it more clearly a0 and a1 and we constructed the digital accounts here for the digital cons we get a 0 at once a one has three times and then we get the dictionary times the given time is that is the frequency of the frequency number that means that this frequency either has frequency once so it has one because this frequency wants only occurs once and it's filling three only occurs once so this is the definite counts you will have another a 2 and a 2 3 here let us mean that here's the 3 and 3 occurs twice so here the frequency of the num is 2 here and for this case is the maximum frequency is uh manufacture is uh getting this is got turn from these digital cons so maximum frequency means three here three and one so medicine-free is three maybe we can radically manage frequency here and to get those solutions here so we have figured there are four cases the first case is that if the element has has only one unique values that is that case if the element is all the ice number here for this case that is we can get the maximum frequency is equal to current i right so if we find the maximum frequency equal to current i which radius will directly return the answers equal to the i here because we can for this we just denote any one number that is real or valid solution and the second case is that if the all the element occurs only once so for this example a1 a2 for this we get this additional counts is now this and we do not need to get additional times actually because for these cases the condition is that the measurement frequency is equal to one all element has occurred once for this case we have directly to return the eye and then we have the third and fourth case for the show casey that we have only one element occurred once all the other elements occurred more than once for example here we have a0 and a1 a2 and a0 has occurred once this and 81 it will occur twice so this taking a count and for this is the maximum frequency is 2 here and we can delete a 0 here and we get the dictionary counts is 1 8 2 this is a valid solution but how do we figure out of this way this is a valid uh solutions we can already underneath 0 and try again and delete a1 and then a2 again try again this will go back to the knife solution again so then the trick is here we just use the dictionary and times here for this case additional count is from this dictionary counts we know that y equals 2 once and 2 equal twice and because this is 1 has equal to 1 so and frequently equal to 2 and frequently 2 is 2 times 2 plus 1 equal to 5. the total number equals 5. so the canadian that if the measurement frequency times the degree times maximum frequency here plus one equal to you can kind of number uh counter number of this array then we return i this that means this kind of way is a valid solution because this only occurs once the other cases on um the measuring frequencies on uh of course the same in this only in these cases we can get a valid solution we just need the number that has occurred once that is a0 and then we can let's go to the first case is if the element occurred more than once than the rest of the elements for example here for these cases we have the idea of occurred three and a one equal twice a two over twice and for this we didn't only also zero a1 and we will get the solutions this all the element occurred twice so this is a value solution but how do we get this we know this frequency number is now is three now it's not one again and also we get the dictionary times equal to is three equal to one and it's two equal to two here clearly that we cannot uh denote two way we need to do it once that is frequencies three that is a zero everybody new zealand all the others are the same so we can see that we have the two plus then three equal to seven that is valid so is two plus two how do we get the values so that is actually the maximum frequency number equals minus one because us it has muscle has one smaller than the zero if we not these cases we cannot get a valid solution here so only this case so here that should be the minus one the mass frequency is three minus by two so it will has to be one smaller than the zero so it's the minus one here and this is then we plus the maximum frequency if this is equal to i we return i so this is basically the four cases so during the thousand we can judge the whether this if forces is satisfied if they are certified we can directly to return the solution let's write the code here and so we define i additionally counts and dictionary times and also management frequency for divisional concept videos this is a default is nowhere here and maximum frequency equal to zero numbers then we tell us from the uh every element from zero to the last one we can traverse from the end to the beginning of from beginning to end here we chose from the beginning and we also define the answers here initialize as zero and we update the division noise plus one now we update the dictionary times the digital current is based on the dictionaries the element so plus one because we are chosen in this so every time we have to denote the previous answer for the teaching at times the previous solution because additional count is not a final answer so here we have to update the additional accounts we have it initially disappears the statistic previously there should be the minus one and minus one then we updated the maximum frequency now we consider the four cases the first case is if it's only one element so the let me tell you the frequency the my unique element so the frequency is equal to i here because we are starts from zero or zero so it's filled with i plus one here and so zero i plus one the second case is that if maximum frequency imagine frequency is only one equal ones and a third frequency that is for this case e for the maximum frequencies equal to the i plus one and return and so not return just uh my finished answer equal to i plus one the first what happened and you can answer here okay so right here we traveled from the first and beginning to the end we updated the answer here until the end before if in any cases the condition is satisfied we will update the answers until the end so we can get the maximum length of the prefix number yeah we made it thank you very much for watching see you next time
Maximum Equal Frequency
minimum-falling-path-sum-ii
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). **Example 1:** **Input:** nums = \[2,2,1,1,5,3,3,5\] **Output:** 7 **Explanation:** For the subarray \[2,2,1,1,5,3,3\] of length 7, if we remove nums\[4\] = 5, we will get \[2,2,1,1,3,3\], so that each number will appear exactly twice. **Example 2:** **Input:** nums = \[1,1,1,2,2,2,3,3,3,4,4,4,5\] **Output:** 13 **Constraints:** * `2 <= nums.length <= 105` * `1 <= nums[i] <= 105`
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
Array,Dynamic Programming,Matrix
Hard
967
1,048
welcome to mazelico challenge today's problem is longest string chain given a list of words each word consists of english lowercase letters now let's say word one is a predecessor of word two if and only if we can add exactly one letter anywhere in word one to make equal to word two so for example abc is a predecessor of a b a c because we can add an a right in between here and that's gonna equal that word a word chain is a sequence of words word one word two all the way to word k where uh with k is going to be greater or equal to one and where word one is a predecessor of word two and word two is a predecessor word three so on and so forth we turn the longest possible length of a word chain with the words given to us in uh words right here so here we can see the longest word chain is going to be a to ba to bda and then bdca so i'd be a chain of four now to give you a hint instead of adding a character try deleting a character to form a chain in reverse so what we might think here is say that we had this word bdca we could do some slicing and we know that one character needs to get deleted so we can start off by checking dca then check b c a then check b d a and so on and so forth and check to see if that word exists in our list now if it does we know that there's at least a chain of one and what we can do is create like some sort of recursive function to return how long this path is and we have to do that for every single word and we can optimize by doing memoization we could keep track of what the max length or max length of the path was so that we don't do repetitive calls okay so what we'll start off by doing is creating a set to make it a little bit faster and we have to have our memoization so we'll have a dictionary here and now we're going to have our recursive method and this is just going to be passing in the word now the base case is if this word is not in the set then what do we want to return well it's going to turn to zero because the chain doesn't exist right so we'll just return to zero otherwise we're gonna have to make sure to see our memorization if word is in memo then just return word memo here now otherwise we'll have to calculate how long that chain is for this word so a couple things we want to initialize first we should have the length of word so we'll have length of word here and then we'll say for i in range of n let's calculate the max path and we're going to do that by uh first initializing max here and we're just going to calculate the max equals max of max and recursive uh what we'll do is word starting at i no up to i plus we're going to delete one character so word i plus one all the way to the end one thing to note here though is we have to add one because every single recursive stack we want to say okay this is going to be one word two words three words and so on so forth once we have that we should have our max value so let's add it to our memorization we'll say let's say memo word is equal to max and finally just return the max now what we need to do is call it for every single word we'll say 4w in words let's call our recursion for word here and finally now we have all the max lengths for every single word in our dictionary inside of memo right so all we need to do just return the max of that we'll say return to max of memo dot values okay so let's see if this works return word dot memo uh okay i flipped that memo word okay so that looks like it's working so let's submit it and there we go accepted okay so time complexity wise it's going to be at least n times l because uh l being the length of or average length of word and it's actually going to be because of this recursion it's going to be another l so it's n times l squared we also have our memo and our recursion so we have to have extra space n times l space as well but otherwise i think this is perfectly acceptable there's some optimizations you can do make this code cleaner but you can certainly use lru cache to get rid of some of this but i think this is fine okay thanks for watching my channel remember do not trust me i know nothing
Longest String Chain
clumsy-factorial
You are given an array of `words` where each word consists of lowercase English letters. `wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`. * For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`. A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`. Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`. **Example 1:** **Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\] **Output:** 4 **Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\]. **Example 2:** **Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\] **Output:** 5 **Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\]. **Example 3:** **Input:** words = \[ "abcd ", "dbqca "\] **Output:** 1 **Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains. \[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed. **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 16` * `words[i]` only consists of lowercase English letters.
null
Math,Stack,Simulation
Medium
null
341
hello everyone welcome to our channel code with sunny and today i am going to discuss the problem flatten nested list iterator index number is 341 and the problem is of medium type of late code okay so let's discuss the problem now we have been given a nested list of integers nested list as its name each element is either an integer or a list okay so it is like we have a certain let's say an array of elements and for every index i we have either a integer or a again an array okay it is like a nested list okay suppose we have a like nested for loop it is like of nested list like it would be like either any index of the array should be like a integer or it's like a entire array also okay so each element is either an integer or a list whose elements may also be integers of other list integers or other list okay so implement an iterator to flatten it that is we have to just uh remove those bounds of the array and we have to just flatten it like suppose in this example you can see here we have three elements of the array and for our my first element is again an array which is of two elements like one and my second element is an integer and my third element is and again an array consisting of two elements like one and one okay and we need to just flatten this nested list so after flattening it should be like one two one okay so what is the basic meaning of flattening that is if you have an array inside an another array just to remove the bounds of this on a inside array like one and one you can see over there and you have to remove this array bounce and just place the elements as it is it should be like one and one in here okay so it is basically like your l outer array that is your nested list area size will either remain constant or it is going to be increased okay so before going further into detail we need to understand what is this nested iterator class and what are these three functions that we need to implement for this problem okay so a nested iterator is basically a constructor first and we need to initialize the iterator with the nested list okay and there will be next function also that is going to return the next integer in the nested list okay so it nested list is our like is the given array which may contain another ad inside it and this next function is going to return the next integer in the nested list okay and there will be boolean has next function okay so this is which is basically going to check and return true if there are still some integers in this nested list that is it should be like if we are going to just take the element from this nested list and all the elements in this in that nested list is going to be like the list again then we are going to return false and if there exists a single integer in that nested list they are going to return true okay if you are not going to understand this statement no need to worry about i'm going to explain this in detail with the help of example okay so otherwise return pulse okay so let us understand this problem with the help of example so let me take a list over here like one and there will be like two and again i'm going to take another list like one and this will be closed like this okay when you okay so suppose at a certain instant we have this elements like one and only two only these two elements in this list and if we call this next function it is going to just basically check if there is some more elements in this like okay so if you are not going to just get it out just check it out the meaning returns the next integer in this nested list like what is the next integer in this nested list it should be like in this one it is going to check yes if there exists a next integer in this now you can see this is a nested list this is actually basically wrong it is not going to check or give the next integer so if you're not going to be just confused about that because we have to return the next integer the question will be framed and will be asked the queries according to the given problem statement so if this next function is going to be called then my next will be like will be obviously an integer okay so it will not give any runtime error okay now let us understand what is this has next function is going to do okay so if we have some hash next function it is going to just check if okay so let us read the statement also returns true if there are still some integers in this nested list okay so if there's still some integers in this nested list like check if this is the nested list and if we keep popping this uh or you can say like if we have this current nested list over here and check the integer over this one like integer over here is 2 and it means that if we have this current nested list and if i'm going to check if there exists a integer now present over there that is here it is 2 just return true and what about when our answer is coming out to be false suppose at a certain instant we have this nested list like one and let's say we have another like one and two and this is my current instant of this nested list okay now if i'm going to just call this has next function which is going to check if there exists any integer over this nested list that is present over now you are going to check okay so you are going to just iterate or you can keep popping out the elements in my current nested list you can see this is again a list and this is again a list so there doesn't exist any integers so we are going to return false okay so if you are going to return false just it is completed also we need to be careful that we need to flatten this list okay so what about flattening this list means so if we have been encountered some elements like this one there's some list like this one we need to just remove this array bonds like we have to just keep it as one and two and just push again into my this current encounter nestedly so you can stack okay so now there comes the main role of stack or you can use the queue also it doesn't matter i think okay so here i have here i'm going to use the stack and basically i am going to just push all the elements from the like if you have this okay so if you have this nested list i'm going to just pop the or you can say sorry i'm going to just push the elements from the back side of this list like first one this one will be pushed then this one will be pushed and you can see last element is going to be like this one it means that this will remain at the top of the stack and if this will remain at the top of the stack then it means the first element of this stack will be this one and if we keep popping out the elements then this one will be popped first then again this one it means that elements are going to be processed in order starting from this first one then the second one and this third one so this is the main key idea that's why i'm going to push the elements from the back side okay so let's move further to understand the coding part okay so you can see here i have a stack of nested integer star and s okay so basically uh okay so the question statement is a little bit confusing and it takes a cert it takes me a lot of time to understand i interpret this and even after interpreting it is like if you are going to implement this then in the coding section uh it takes us a time and there will be like much more confusion over there okay so now it i have taken some 15 or 20 minutes time to write down a best code of this problem okay so let us uh understand this one okay so i am going to implement using a stack of like suppose you are in the real c plus scenario we have a stack like sometimes we are going to use like stack of int stack of strings now here i have a stack of like in nested integers of pointers you can see i'm going to store the pointers of nested integer type nested integer is basically a you can see you can have a class over here as nested integer and there will be functions like in is integer that we can use directly or we can use directly get integer function and so on or you can use the get list function also okay so this is basically a constant vector of nested individual okay it doesn't matter now you can see here i have a constructor and i need to implement this so i'm going to just push the elements from the back to the front so that elements are going to be processed in order starting from the beginning okay so you can see i have iterated from back side of the this nested list and up to greater than equal to zero and just push the address note that i'm going to push the address because my stack is of type nested integer star okay so i have the net in this next function that is going to check if it my next would be like uh integer or not that check if it is integer no need to check because i need to return the next one so just return as it is okay it doesn't matter so i'll just take in the value stack the top uh top is basically and pointer just return the value of this point of get integer now you need to think what is this get integer method is doing here and where it came from okay so no need to worry about you can see i have a get integer implemented inside a nested integer that's what i have used over here also so just pop the elements from the stack and return the value now comes the main function or you can see the main role of the function like has next okay so let us understand this also uh basically you can see if you read over the statements of the problem it should be like as has next it's going to return true if there are still some integers like still if it exists a single integer i need to return true okay so let's pop out the elements from the stack one by one and check if it is an integer just return true as it is like at the same instant okay using each integer function of the nested integer class okay so i have just pop out the top element like star itr okay and if it is integer return true as it is otherwise we can store my current list and we need to flatten this list like flattening this list is like again pushing the element on the back side also so just have stored it in a nested integer vector and okay so let's start flattening this by pushing the elements from the back side and using the help of the address you can see okay and finally return false if there is not a single integer like all the my current nested list it's like composed of only the nested address and that doesn't take us in any single integer okay so in that case i'm going to return false okay so this is what i need to implement so let's submit this code and check it out if this is an working and efficient solution or what okay so i have something like okay i think i missed something or what stack of nested integer there is a language problem or what yes it here it is of java i think i should submit in c plus yes it is good okay so i think i haven't changed the language i also have just written the code and waiting for my correct solution okay so if you have any doubts do mention in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video
Flatten Nested List Iterator
flatten-nested-list-iterator
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the `NestedIterator` class: * `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. * `int next()` Returns the next integer in the nested list. * `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = \[\] while iterator.hasNext() append iterator.next() to the end of res return res If `res` matches the expected flattened list, then your code will be judged as correct. **Example 1:** **Input:** nestedList = \[\[1,1\],2,\[1,1\]\] **Output:** \[1,1,2,1,1\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\]. **Example 2:** **Input:** nestedList = \[1,\[4,\[6\]\]\] **Output:** \[1,4,6\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\]. **Constraints:** * `1 <= nestedList.length <= 500` * The values of the integers in the nested list is in the range `[-106, 106]`.
null
Stack,Tree,Depth-First Search,Design,Queue,Iterator
Medium
251,281,385,565
515
hey everyone welcome back and let's write some more neat code today so today let's solve the problem find largest value in each tree row so just like the problem says given a binary tree here for every single row we want to find the maximum element in that row and as you can see in the first row we just have a single value so it's going to be one in the second row we have two values among three and two is greater so it's the max value in that Row in the last row we have three values and nine happens to be the biggest in that case so we want to return the result in the form of an array where each value in the array is the max from every single row so we have one we have three and we have nine and this is what we're going to return that's going to be the output for this problem if you're new to these types of problems almost always with binary tree problems you're either going to be doing some kind of depth for search approach or a bread for search approach it's usually more common to do DFS but in this case what do you think is going to be easier for us to solve this problem with probably breath for search because breath for search is also known as level order traversal which is basically traversing the binary tree by row so the first row then the second row then the third row it's going to be pretty easy for us to uh find the maximum in each row if we're actually traversing ing each row so the general idea here is with breath for search we use something called a q in my language we end up using a double-ended Q AKA a deck and using a double-ended Q AKA a deck and using a double-ended Q AKA a deck and what we do is we initialize let's say the Q I'm just going to draw it like this and we're going to add the root node to the Q initially and not just the value but the node itself because we're going to then pop from this q and before we even do that actually we're going to compute the length of the Q we're going to have one value in the Q so we're going to know that the first row just has a single value or a single node and then for that we're going to find that the maximum was one so in our result down here we're going to add the one but for this node then we're going to check does it have a left child yes it does so we add the left child three to the CU does it have a right child yes it does so we add two ALS o to the Q so now we are done with the first row but now we're going to compute the length of the Q again there's two values in the que there's two nodes so we know to Traverse the second level we're going to iterate two times we're going to pop each of these nodes we're going to first pop three we're going to find that so far it's the maximum but we're also now going to add its children five and three to the Q here so I'm going to add that five and then I'm going to add the three but we know that these are even though they're a part of the que already they're not a part of the current level they're a part of the next level so then we pop one more time we pop the two here so among these two that we popped we know that three was greater we know now that we are actually done with this level so we end up adding three to our result it was the max value in that row and we also for two we add its children it doesn't have a left child so we don't add anything for that but it has a right child 9 so we add that to the Q and at this point once again we will see that okay now we have three values in the Q so there's going to be three nodes for us to Traverse this level and basically none of them have any children so that's kind of like the base case but even though this isn't like a recursive algorithm that's our terminating condition but for each of these we're going to pop five it's the greatest so far uh then we're going to pop three five is still greater than three then we're going to pop nine is the larger so 9 is going to be what we add to our result now so this is overall the solution and that's how we solve it with a Q since we're adding and popping every node a single time it's going to be Big O of n time because with a Q we can actually pop from the left in constant time just like we can pend to the right in constant time as well space complexity as you can kind of tell with this Q in the worst case it's also going to be Big O of n so now let's go ahead and code this up so I'm going to first initially just have an empty result it's going to be a list we know that's ultimately what we're going to return so I just usually like to write it out at the start uh but we also know we're going to have a Q and like I said I'm going to use the deck from python it's a double-ended CU I'm going to initialize double-ended CU I'm going to initialize double-ended CU I'm going to initialize it with by passing in an array with a single node which is root so this is Will initialize the que with a single value in it but there is the case where what if the root node is actually null that is a potential Edge case we have to handle and the way I kind of showed in the drawing explanation is the expectation is that we never append any null nodes to the Q so the easiest way to actually handle that is just check at the beginning if not root if it's null then just immediately return an empty array we don't have to even do this uh code but otherwise we're going to check while the Q is nonempty this is one way to write it we could also just uh take the length of the Q but this actually does the same thing so I'll leave it the more concise way but every single time we're going to get the length of the que you actually don't need to do this because uh in Python so this is what I'm doing I'm going to Loop for every single time in the length of the que initially I'm taking a snapshot here but we could actually write it like this as well in Python because range is a function it's only going to be executed a single time we're going to take the initial length of the queue but in most languages for Loops actually don't work that way you don't use a range function you usually just have a condition and that condition is run multiple times so I'm kind of writing it this way so that it's easier for you to translate into a different language if you choose but basically uh this will allow us to go through one level in the tree and we know that uh for that tree we are trying to find the max in the current row so I'm going to call that the row Max we are initially just going to set it to the first node in the Q currently because we know the Q is non empty so I'm going to say Q at index0 and we know that's going to be a node and we actually want the value so I'm going to say value that's initially the maximum and then as we iterate over the entire row for every single node we're going to say a q.p left and that's going to give us the q.p left and that's going to give us the q.p left and that's going to give us the node and since we ultimately want to find the maximum we're going to update that row Max is potentially a new value like a node Dov value and then so this is finding the max in the row but we should probably also populate the next row at the same time so we should check is no. left non null if it is let's append it to the Q same thing with node. right if it's non null let's append it to the Q and so that's pretty much everything we need to do but the last thing you shouldn't forget is we actually need to update the results so after we've gone through the current row after we found the row Max let's go ahead and append it to the result like this so result. append row Max so this is the entire code let's go ahead and run it to make sure that it works 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 NE code. thanks for watching and I'll see you soon
Find Largest Value in Each Tree Row
find-largest-value-in-each-tree-row
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**. **Example 1:** **Input:** root = \[1,3,2,5,3,null,9\] **Output:** \[1,3,9\] **Example 2:** **Input:** root = \[1,2,3\] **Output:** \[1,3\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
485
Hello Everyone Welcome To That Point Sub Electronic Subscribe And Subscribe The Amazing Must Subscribe Play List Ronit Roy Example Jo Hair Din Ko Different Awal Maximum subscribe and subscribe this Video Subscribe Padh Subscribe Now Subscribe To I Want Their Embarrassing Squashed Interview Will Be Treated S Subscribe Thank You All Subscribe School Subscriptions That Electronic Western Wear Giving Importance Of Immortality And Different And Subscribe 0 subscribe And subscribe The Amazing subscribe Video subscribe and subscribe the Ki Bihar Good Let's Move Ahead Devi Seervi To Subscribe My Channel Subscribe and subscribe hai iske do not to do sachiv veer wa subscribe hai next verification adhavwali subscribe Video subscribe 100 subscribe ki nau comes the logic wife in english lights S2 Maths Video subscribe do subscribe to ki modernitya ki censorship saheb told in the presentation avanish Slide Dubai Who is this Video subscribe Video Subscribe 512 Current Subscribe An Anindya And Is Simply Do Subscribe That Accepted And How Did Not Emotionalize Politics to subscribe our Channel and subscribe the Channel subscribe that in cases off line join this Video David for Tomato Like this the report and intuitive station I don't like you
Max Consecutive Ones
max-consecutive-ones
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
Array
Easy
487,1046,1542,1999
131
hey everyone welcome to Tech quiet in this video we are going to see lead code problem number 131 palindrome partitioning we are going to solve this problem using backtracking I am going to use the first example to solve this so now let's dive into the solution and logic so guys please like And subscribe and this will motivate me to upload more videos in future also check out my previous videos and keep supporting now let's dive into the solution so in this problem we are going to return the substrings of palindromes what I mean by substrings so we need to consider first we need to consider all of the characters as single Single Character okay a is separate one and another will be a separate one why is this because even if we set a reverse this particular a we are going to A1 we are going to get a only since a is already present we are not going to consider this one okay here B is not there if we reverse B it's again B we'll be appending B okay so we are going to use backtracking here so at the first level I will have a start index okay the first level I will be having a start index first I will pick a and I will append since a is a palindrome I will check a palindrome whether this particular element is a palindrome the particular path is a palindrome or not I will use a separate function for them in order to check whether my current path or current elements that I have set of elements I have is a palindrome or not okay so since a is an element since I have only a now I just check whether it's palindrome or not yes it is a parent room I am appending a here in this level okay then if it is a parent room I will move my start pointer to the next one okay start and after start I will only take this part for the next back track at the same level okay now this is my start and this stage I will be having a and b only okay here I will be having a and b here I will check whether this particular path the particular substrings or palindrome or not this is not a palindrome so I will return okay I will return so then I will check from this part in the same level okay since the previous A and B are not palindrome right so now I will check only B whether B alone is palindrome or not okay now I will check whether B is a palindrome or not yes B is a palindrome then I will append it in my path okay it is a separate one since we are doing recursion here B is a separate one okay so we will be having b and a so when we do the recursion like that so when we reach the end of the string I will append that in my result stack okay all these three will occur in separate recursion stages okay first I will open a then I will append B okay now we will see the code so I will explain it again so in the first stage I will be having a I will append a in my path okay I will open a in my path this is my path then I will do the recursion at that stage I will be having a and b in my I will check A and B only then it will be false so when it's false I will append a in my result stack okay then I will check a and a are request or palindrome or not if they are palindrome I will append that in my path okay then I will take B alone then I will take a b since they are true I will take b a b is not palindrome I will return okay now we will see the code so now I'm going to write a function backtrack okay here I'm going to have a starting index and the path that I am telling that I was telling then I'm going to have a result stack okay so I'm going to check whether my starting index my index have reached the end of the string okay if it is reached then I will append it I will append the path then I will return okay so here I am going to check using my start index I'm going to check this string so if I'm going to write a separate function is palindrome okay I will show that I would check whether my current start index my current string that I'm checking substring is palindrome or not if it is true I am going to increase my index I'm going to check the next character okay since it is true I am going to append that currently I'm going to append that substring to my path okay this is my result okay so I'm going to write a separate function whether it is a palindrome or okay so go to check whether it is parent room or my current substrings substring is a palindrome or not so I'm going to declare the result stack as my Global variable and then I'm going to backtrack so initialize I'm going to first initially initialize as 0 at the start I'm going to send a empty list for the path under I want to make it as result then I'm going to return the result so I think it should work as you guys see it's not that much efficient uh but the time complexity for this one is 2 power n uh since we use recursion we can also you do it in our iterative way but using backtracking is pretty much easier to read and understand so thank you for watching this video please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
1,027
hello everyone welcome back here's van damson and today we are going uh to tackle very interesting problem from lead code longest arithmetic subsequence so it's a medium difficulty problem uh and it might be quite trickier to understand and solve it efficiently uh but uh we will dive to the solution right away so let's first understand the problem so we are given an array of integer and we need to find the length of the longest arithmetic subsequence in the arrow so to understand uh so our arithmetic sequence is a sequence where every two successive numbers remain constant and a subsequence is derived from the array without changing the order of the ri itself so here is some example so given a all right nine four seven two then we can see that longest arithmetic subsequence is 4 7 10. so four seven ten so uh difference between every consecutive element is free so four plus three is seven plus three is ten and length is three of this particular sequence that is subsequence and we need to return this left so let's dive into go implementation using dynamic programming and also knowledge that the num length so uh array of numbers cannot be greater than 1000 and also each number cannot be greater than 500. so n will be Len of num and if n is less than two return n because it's longest sequence and longest will be two and then we initialize the vector so make int of N and for I in range DP at I will be make array of integer 2002 and J will be range DP I and DP J so it will be initialized as one and four I from 0 to n increment and second Loop so for J zero less than I increment and now we calculate the difference num I minus num J so difference between number and Plus 501 so DPI at difference place and J plus one and if DP longest so then it will be maximum and longest will be DP I at position of different and return longest element so this is our implementation so let's run it and see if it's working so hopefully it's working so it's working and as you can see on previously mentioned case the correct output is three so we using 2D dynamic programming approach and we create an array of and differences and we keep track of the maximum length of arithmetic subsequence that ends with particular difference so we'll start by iterating over the array from the beginning and for each pair of numbers represented by I and J we calculate their difference also we increase it by 500 one because RIS are zero index and we Define the maximum value uh possible and because the difference is uh at most 500 we increment it by 501 to be on the Zero index place so for each per we calculate the difference and then we update the maximum length of the arithmetic sequence that can end with this particular difference so we continue this process for all parts of them numbers always updating the max length in the corresponding DP vector and in the end we return the max length found during this process so let's run it for unseen test cases and see if it's working as well so hopefully it will work so yeah it worked and we beat 78 with respect to run them and also 60 with respect to a memory and remember the key to master this kind of problem is practice and the more problem you solve the more pattern you will recognize and making it easier to tackle new problems and if you have any question or idea please share in the comment down below and don't forget to hit the like button and if you found this video useful subscribe for more uh coding tutorials and challenges uh in go and as always keep practicing stay motivated happy coding and see you next time
Longest Arithmetic Subsequence
sum-of-even-numbers-after-queries
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). **Example 1:** **Input:** nums = \[3,6,9,12\] **Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. **Example 2:** **Input:** nums = \[9,4,7,2,10\] **Output:** 3 **Explanation: ** The longest arithmetic subsequence is \[4,7,10\]. **Example 3:** **Input:** nums = \[20,1,15,3,10,5,8\] **Output:** 4 **Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\]. **Constraints:** * `2 <= nums.length <= 1000` * `0 <= nums[i] <= 500`
null
Array,Simulation
Medium
null
1,933
dream is decomposable into value equal substrings yeah let me first try to explain it so we are giving us a dream so for the consecutive characters so for example 0 it is the three and 1 one it is the three but when need to meet one condition that is yeah we need to have ADD yeah we need to have exact exactly one substitute have a length of two but this one we don't have and this one we have because uh there are five consecutive ones and we can split it into three ones and two ones so in this way we have exactly one less of two and others if it is exist it must be the length of three yeah as you can see it should be easier solved by list groups because list groups can solve such kind of a groups problem in O time basically it is a twop pointer idea but the L group going to make it a template and yeah you can avoid making so many mistakes so I'm going to start from the I so I should be less than the length of the string and then I'm going to prepare a start should be equal to I and I will have another poter Z would be equal to the start yeah now I'm going to check this Z so f z is less than the length of S and S do equal to s z so Z should the plus equal to one yeah now I'm going to check it so Z minus start modular 3 so if it is equal to1 so I can return a false because it should not have one otherwise I can put it in inside my result so my result would be D minus do uh modular 3 yeah so inside it can be zero or it can be two but definitely there's no one because I going to return forse yeah and let me prepare a result should be an empty array yeah and finally my iort should be equal to Z now I'm going to check the answer so for n in result if this n equals to two So my answer would plus equal to one and finally the answer should be equal to one yeah because for the length of two I should have exactly one yeah now let me run it to tck as you can see it works now let me submit it yeah as you can see it's pretty fast because this is just all and time complexity and for example this one there are five ones and for five ones five modular three it going to be two and from here we're going to count at as one and if it is three it going to be zero I don't need to C it yeah so this is why thank you for watching see you next time
Check if String Is Decomposable Into Value-Equal Substrings
number-of-different-integers-in-a-string
A **value-equal** string is a string where **all** characters are the same. * For example, `"1111 "` and `"33 "` are value-equal strings. * In contrast, `"123 "` is not a value-equal string. Given a digit string `s`, decompose the string into some number of **consecutive value-equal** substrings where **exactly one** substring has a **length of** `2` and the remaining substrings have a **length of** `3`. Return `true` _if you can decompose_ `s` _according to the above rules. Otherwise, return_ `false`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "000111000 " **Output:** false **Explanation:** s cannot be decomposed according to the rules because \[ "000 ", "111 ", "000 "\] does not have a substring of length 2. **Example 2:** **Input:** s = "00011111222 " **Output:** true **Explanation:** s can be decomposed into \[ "000 ", "111 ", "11 ", "222 "\]. **Example 3:** **Input:** s = "011100022233 " **Output:** false **Explanation:** s cannot be decomposed according to the rules because of the first '0'. **Constraints:** * `1 <= s.length <= 1000` * `s` consists of only digits `'0'` through `'9'`.
Try to split the string so that each integer is in a different string. Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique.
Hash Table,String
Easy
null
1,192
so let's talk about it code 1192 critical connections in the network so first let's draw a example network we have node one connects to node two connects to node and node 1 connects to node 3. and we have another node 0 that is only connected to node 3. so in this network the critical path is the edge that's connecting 0 to 3. so why it is the critical path so when you remove this edge the node 0 can no longer reach any node in this network and you are basically breaking this network into two sub networks so to solve this problem we use dfs from starting from any render node in this network and while doing the dfs we keep track of two numbers one is the depth of the current node the other number is the min depth of the current node so the mean depth is basically the smallest depth of any node that is reachable from the current node and we will show what that means so let's say we start from node 1 here at node 1 we have depth of 1 and the mean depth of one also note that if you visit an unvisited node the minimum depth is always the depth itself and let's say we search from smaller to larger numbers so for node 1 we go to node 2 and node 2 will have this depth of 2 and min depth of 2 and node 2 will go to node 3. at node 3 we have 3 as depth and min depth of 3 again and etc at node zero we found out that there's no other nodes to visit so we backtrack to know three and the key thing to note here is that at node three we find out that the mean depth of node 1 is smaller than the mean depth of node 3. so what we do here is we update the min depth of 3 to be 1 and we backtrack to node 2. similarly at node 2 we find the min depth of node 3 is smaller than the mean depth of node 2. and we do the same thing we update the mean depth of node 2 to be 1. so at the end of the dfs we maintained the depth and min depth of every node so if we put that into a table so what we observed here is that node one two three they all have the same mean depth and node zero has main depth of 4. so we observe that only node 0 and node 1 has their depths equal to the mean depth and back to the network we can actually see that node 0 and node 1 they are actually the entry point of a strongly connected component scc so scc is basically a directed graph where any pair of node can reach each other so in this network we observed two sccs after we did the depth first search one scc is formed by node one two three the other is formed by node zero so as we can see node one two three any node one can reach two can use three and 3 can reach 1. and for node 0 it cannot reach any other nodes and the edges that connect the sccs into a whole network is actually the edges we want to find which is again called the critical connection so let's transform this concept into code so here we define the critical connections function the input is n is the number of nodes and we pass along all the edges so the first step we do is to convert all the edges into a graph since we know all the nodes are from 0 to n minus 1 therefore we can use a vector to store the adjacent node of any given node and we define another vector called min depth which is used to store the minimum depth of any node that is reachable from the current node and the initial depth is one and we always start from node index of 0 although any node can be used as the root node here so in this dfs function we first initialize the min dapps with the current depth as we discussed before and we get all the adjacent node of the current node so note here we also use the mean depth to denote if a node has been visited before as the min depths are initialized to be zero and if the min depth value is zero it means the node has never been visited so we recursively call the dfs function and while doing the dfs we want to keep the min depth value of the current node updated by comparing with its adjacent node except for its parent node eventually if the mean depth value of the node equals to the depth value it means the node itself is an entry node of a new strongly connected component or scc in that case we want to add that edge into the output so in summary in this problem we use that first search essentially turning the undirected network into a directed graph and by keeping track of the depth and the minimum depth of each node we can effectively detect strongly connected components we can also identify any new entry point of a strongly connected component which would let us to get all the critical connections in this network
Critical Connections in a Network
divide-chocolate
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network. A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\] **Output:** \[\[1,3\]\] **Explanation:** \[\[3,1\]\] is also accepted. **Example 2:** **Input:** n = 2, connections = \[\[0,1\]\] **Output:** \[\[0,1\]\] **Constraints:** * `2 <= n <= 105` * `n - 1 <= connections.length <= 105` * `0 <= ai, bi <= n - 1` * `ai != bi` * There are no repeated connections.
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
Array,Binary Search
Hard
410,1056
546
move out this okay given several bouts of different colors represented by different positive numbers you may experience several rounds to remove thousands of no boxes there if she was time you care and choose some container box in the same color combos with Kaiba right okay go then we moved him and got K times kick okay points find a maximum pointing and get huh I just want those farms okay let's say so in this case you we move alright let me read this again the story given several boxes of different cards from them at different positive numbers each so you keep on moving boxes and okay why does it still trying to okay so first remove the two twos and then you can remove to two E's and then you remove 200 you move it to four for one point and this explanation could be a little better and then you okay I mean it definitely is a hard problem let's see what can I do I mean I think my intuition is that this is some kind of recursion problem so is likely dynamic programming sadly so what are the subproblems right the subproblems is what happens we for indexed from 0 to n so you're trying to optimize what's the most points you get from 0 to n and the most point you get from 0 to N is just some there's some of the subcomponents from yeah so it's from so to I and I plus 1 2 and is optimal and where you joy that the ride will is the number of subproblems and there's a lot of repeating subproblems and dad I mean up to end square of them and it's just a hundred so and any time you get a sub section that only has one color then you could just return dad otherwise which takes account of one case as well is that sufficient let me think about this it's that good enough no I mean just that's one way to do I think I'm trying to figure out is a better way to construct subproblems so basically what you have is these tougher I mean it's roughly right there's there ways to kind of split the problems up I think what I said earlier in dividing by 1/2 may not be accurate in dividing by 1/2 may not be accurate in dividing by 1/2 may not be accurate if like for example like for discs for this case like for the case where I have to read like that's an example something like that a way to think about a lot of decision problems my other I'm also try to think like what Adam so there are some numbers or colors I guess they were to try to figure out are there more than two dimensional sub problems because for something like this case you can read to write them in any reasonable way because you know well this would give just sex you have to somehow figure out like the merging it's not super intuitive to me and then you have something like this where you have something like this then would it disappear way to subproblems you first remove 2 3 and then you get the six of them which is 36 which is already way more than how like which is clearly better than 3 times 3 because then yeah sorry 9 times 2 is you gotta try 7 of you to it like take if you just remove dis you get one point plus six so that's three six plus four so you got 41 so that's quick hmm-what so you got 41 so that's quick hmm-what so you got 41 so that's quick hmm-what so try to think I mean I think dynamic program will kind of lead us to the right direction or memoization but I'm trying to think if they're trying to think about the like what is the best way to split this up man just it's indeed a hard question let's think about this a little bit what I'm thinking now it's like it's still like you have colors is there a analog to a graph problem that I can kind of take advantage of and clearly the point incentive system is nonlinear but is so there's definite thing we're like you're definitely in centralized to get more boxes put it put is there a point in which yeah but yeah to be set up five is better than one set of six that's the query work really probably doesn't work it doesn't sound like you could just you know how do you solve the subproblems okay so four okay I think what I would think about is think about in terms of browse maybe it's an Ncube dynamic programming where they take three states or maybe library states just three states but we did n cube time but nothing for you to Brown can you be greedy each well because in this case you can't be greedy and either that like in this case let's say we picked away oh yeah no but you actually need to remove two three and then two anyway so there's no like ordering down so I mean or like the ordering matters I see and yeah and you also get to a thing where I'm the case that I'm trying to figure out is like well like something like that where you have like a sandwich and the idea move is just to keep on taking stuff from the middle and you may give an imagine a with a case where you know someone like dad even right we're like well what's the ideal case here probably to get the 16th and get to once so then in this case you get two three ones plus 16 is even nineteen Oh typo but can you do better in to know like is it extends to be query can you prove that greedy make sense in each sub-problem hmm and I think about that okay I'm trying to think about is like going back to the older example of like when I just don't to Congress how do you represent this as a sub problem or like what is the sub problems here all right well the sub problem is just do all the twos and then do in it like I heard something like this what would you change about it and clearly you can't do some kind of Tudor 100 ring because which is the number of possible states just because there's binary whether you remove them one or not so that's a little too much but in this case you'd still remove to do reflux but then what if you have something like that do you still we move to do a first hmm just everything yeah I mean there's not anything I don't I'm gonna have all the understanding I need emerging stuff is no tricky look at this example and here I'm trying to convince myself also that maybe it does I think for giving subproblems try to figure out like okay they'll be greedy that's fine okay I think I have a better way to think about it I think what I've been thinking about is kind of from the beginning to end we're like okay my next move is to pass this point and a lot of memorization case maybe that makes sense I think maybe the question or I'm just trying to think about it from a different angle where maybe the question is well what have I pressed this color lass does that make sense I say this case I know that's I want to press the twos last and I wouldn't like this case when we moved to choose last but then what would I have to do to remove tattoos last well I moved it threes and then make the subform it's just this because you want to be move to stand on inside and then still trying to figure out like if there's a clever way to can't do the merging I'm just thinking about it too much like this toes pack size you okay yeah I mean I think I'm gonna give that a try I mean okay yeah I mean okay and I think I've spent that you know way too long kind of thing about this yeah I think like this was interview I would definitely like commit to writing any kind of code as soon as I can and then figure it out but I'm missing a dimension somewhere no it's just hang on hmm they're quick on the one point I know it's here okay I just minimize it worried about moving the stream somehow okay yeah and I think ya know just go on and see what happens if I remove order so just left right and yeah I mean definitely feels like an Ncube memo friend just left right but what is the third dimension anything with color is what try to also think like I mean it's just unique different positive integers I guess that's fine I guess it could go up to any number it some flaming and then I think the numbers don't really matter in the sense that you could just rien Dex tell me if it matters in a weird way does it matter left too late okay well I just start calling something yeah I mean I think I've been you should I don't really come with to code before I have a general idea of what I wanted right but slipping away to what I'm thinking so let's go okay still a little bit used to this thing so let me see if I could - I this thing so let me see if I could - I this thing so let me see if I could - I don't know what in what I can do him what I can - so let me just SS pilot what I can - so let me just SS pilot what I can - so let me just SS pilot need code I do something like just to clean this up a little bit and again I choose 105 because I think the max is our hundred okay so that looks like I could do anything just for fun okay so I don't know the boundary of what I can and cannot do but okay and nothing like in real program and you just have you actually like you know manually set you know to give you boxer sizes so you could manually said it but I'm just too lately and no I'm just I think so in order kind of if this was like a programming time testing well one is I'm already ready to light it way too slow but uh but also I would do something that's so someone like that actually works better and I think just for you just to pretend at least to be slightly cleaner this is what I'm going to do so it matters generally what you put as like the center for while you are in this case I chose zero because we're trying to maximize the score and I don't think there's any way now there's no way to get negative so what you want to do is yeah there's no way to be negative so 0 is the minimum score so that's like a good kind of base scenario and I think and it's just constructor sorry it goes by I'm so used to just having name for to name go for a lot of stuff but uh that's just actually change something okay get max score say yeah Pakistan is one okay as for what K is that to be honest I don't know yet I think there's some intuition about how I want it to be let me think about it my question is okay well okay what is K well first of all well let's just get rid of taro fame there was greater than zero it should be actually by just touching oh but that's one too and we return it can type right now okay so that's the programming part despite another base case of a base case if maybe something like that generally yeah I guess it's greater than because if it's decoder could still get one point let's just return so here what do I do now okay let's say I tried it in action okay I think we're going to do is well given this sub problem we'll just take stuff off the front does that make sense that was ko well I guess the way I know if we only take the last or the first K characters and then or okay so I think what I want to think about it is now unless I only process the first so K could be the number of characters to skate that's already processed so okay so what does that mean all right okay what that means is okay let's say I have this subset I'm gonna take up one and that's to some so why not wear nothing but scaffolding so what does that mean how do I solve this so the levels you go 0 and then that's you go to one point something dis subproblem I guess I'm good I guess they turn it if well I guess that's just a base case don't turn it off this chain them okay how much can I chain them the other one is three well you want the entity to betray or not enter David in the immunity so I mean I'm joining it pretty terribly but what do you want to do is to solve some problem of distrust first weed so it's not sufficient I just elevate for Hey okay I think I am messing up a little bit okay so what I want to do now is okay I got it a long time so the subproblems here is okay so I mean I think all these things that we're talking about all the concepts that they're kind we want but I think we just kind of need a clever way to kind of schedule the subproblems in a way that is exhaustive right so I think that's the only tricky part I think the thing that I kind of took a I mean I some intuition about it but I think I was trying to kind of get around it but unsuccessfully clearly is that for example in this case and what I want is so I mean I have some intuition about it being three dimensions - right but I being three dimensions - right but I being three dimensions - right but I think what this should be is kind of just like ongoing or maybe that's not the right word but it's the numbers number of the same digit so far so in this case we say we have let's say we have this then the subproblems would be well let's stick to so let's take one sub prompt in particular because that's the one that's no well so let's just take this skip the one down so let's say you have tests so at each decision this is just well I hear ya decision right you have given or dissed the decision is better so you want to so well you know that the three and D and matches so now you just solving this subproblem where we can use it way and there's some yeah I think that's right I mean I think that's even an optimization really so you just saw just sub problem we're okay but then you have to keep track of class so cuz I didn't in this case you would the parameters on it well this is represented by left right so but so the sub problem would just be this first you last use it three and use one of them so I think maybe a another way of representing and but in that case you would so yeah I mean I'll just type out a little bit first I guess maybe just streak maybe not to bet over now no then I'm getting over it so you could have like last stages or something where I mean so and then you know all the TP or file for so you have an end to the fourth dynamic programming but 10 to the 4 is a hundred million and that doesn't even count the number like many loops but I think if you all you take the invariant of always assuming to first teach it so yeah in this case I think how I could just constructed it instead of what I just did instead of that instead of this like we constructed as if i encode that we as to within the left part of the array then maybe we can use what we have now which is n cube okay so I think where I would do this okay so the base case for something like this is well that just said when you begin a mini everything right so I guess that's the base case so you say okay like something like white trim so what I'm trying to do is well like it's like well given this let's just trim the white as much as we can that's a rather this way then you just take the ring off right so okay hmm so well left is yes then like my eye watches telling me to stick okay man I forgot to there's a little bit hacky for now in theory we could just pass in to get back school or if you have like an Opie type thing you know that they'll be doing variable so basically this is just trimming the N then white shrimp was press and streak I suppose I think because then whatever you do in the middle because I mean that's like the minimal base case and that uh yeah what you do it in the middle and you could actually yeah maybe I don't even need just white trim okay because I think so another I mean so you could do this Florida man I mean it's an optimization for sure but actually another way you could do it is another way do you think about it is just do another recursive call so let's say the score is you go to game Mexico left in that case it will increase the street post one all right okay that's but this is only the case if here is you go to piece of glory and in this case you do minus one okay so that takes one thing off and this is actually this plus streak time streak what's that what my ping to tell me because then in this case it'll go straight past one and then I will also increase the score now no I okay now I need this part here because you really do need all them at one point to get the points together so you so in this case max which is Taccone max score is you go to Ken Mexico laughs like and also as I know there is there should be - - and now you have no more should be - - and now you have no more should be - - and now you have no more streak maybe left us one I do not press one yeah I mean just do it this way still we're dynamic programming forms that's sometimes unless you like really excessive it's hard to prove to use or it's far for me to prove for myself that you know it's right okay let's try this press a strict time streak and now we have we do order as we could tell actually there's not that much programming a lot of it's just try to figure out what you want to program so just resets the streak okay now we're just looking into this set I guess now yes now you try to solve to four which is fine so you maybe even - no it is fine so you maybe even - no it is fine so you maybe even - no it should take it surfaced and off you go - should take it surfaced and off you go - should take it surfaced and off you go - right do I have to do laughs he goes to white I don't know if I need to do this per se but I think it's just returning really and we turn the base case just in case I guess now you trying to your subproblems for this is okay good and back score and you left to the white trim what is this trick so basically I'm just dividing in strong's pitiful for it doesn't make sense for anything really but let's say this was our supply then we went and tie well this is how some point everyone this to see what happens if we take the entire subset here and it may be this - there's an infinite loop or no be this - there's an infinite loop or no be this - there's an infinite loop or no cost and the next round we trim and then you just stop for and then okay so I think this is a bad way to end this is why we keep the laughs it's because if our top father and I went our waters I can't even when does it make sense to just supply maybe to send right I told them I try maybe oh okay so did I remove this okay fine but actually I think what I want is the left trend I've been confusing myself a little bit so we went from the laughs where I guess you just okay then we try something else so let's say I have just one of things I think we would it's now I okay now I think I know what I won't do so you definitely do the trim so just I think this makes sense now I mean I sat down a few times I mean they say you get the max score of two cuz okay so this now paces off the first letter or first color so now okay cuz now you just it's already factored in and now you don't be poison to tears and now the thing is you only recurse on every iteration of the next of the same color so like so if I see this trade then yeah we recurse on this and I say if there's a three on the middle then we also because on this but for so yeah so then you just always elevate on the next merge they say that's all the possibilities because you only want to after middle once the splits are in case of the yeah the subproblems like you only want to merge between the next degrees right and in this world this text accounting the case where we have nothing well this takes account in the case where we don't even we just hit it by itself so in this case if we did waive it okay I think I've a better idea okay actually now that I'm thinking about it seems way obvious but I guess that's the vein of dynamic for Graham while I'm sometimes it's tough okay this time we've left room what is left okay just to make sure I get my indices right in this case just when so when it ends this is the first time I mean okay so then we can still do stuff we're okay if well repeal left as you go to left rim that means if it matches the same as before then I want to do that recursion on the stuff that's so then I would do recursion on this stuff and all the stuff afterwards okay cuz so what this third dimension will allow us is that when we self I mean South this point and we go to this point it allow us to continue that carry that Street to plus one so that it solves for the case where I do two twos and enforce and in degrees which is in a problem okay I think I'm convinced by that the new right is and since they're the same that's three plus one plus get a max Quan the right size so that's I plus 1 to Y and in this case there's no streak and then if school is go syntax and over it max is you're gonna score okay hmm now so what I'm doing now is I had to recache the answer there's two used to be a trick on here but when I'm trying to figure out I used two new straight good and old streak I guess I should but then I implemented here this is okay well just actually seeing the compilers primary type or somewhere is impressive decoration of annoying thing about CIS cohabits stackoverflow okay so let me think about it for a second so this n square shouldn't I guess the thing that there's something wrong here in that if we trim off the beginning and it's yeah I mean I think I just don't progress this should be first one so that it keeps on going the same train okay well I guess there are other cases as well doesn't call the same thing try so what happens over stack over for when you do a memorization means generally you call the same thing more than once and then goes to an infinite loop because should finish dark space there's only and table shanky okay well that's just real quick yeah it's tacked over phone well that is it tells me enough with just one eight texted boy so what's one eight let's trace this a little bit so I'm it's 1/8 trace this a little bit so I'm it's 1/8 trace this a little bit so I'm it's 1/8 and say well my guys must be so I said left room has to be it laughs okay so hopefully it that's my still unfortunately okay I mean we're making progress obviously it's not the right answer so let's see what we can do that's just and then we can see how it fits it when we fingers where I did some every times score - yes that's right six three times score - yes that's right six three times score - yes that's right six three times four that's five seven two three no separate five seven one let's do the zeros for now a bit but this is query should be okay I mean we could want a easier example just to kind of confirm our thing I really hate that they show you the expected just cause I think you should be able to figure out by yourself what is right I mean no one's gonna switch on anyone or until the answer or whatever anyway so two to three points it's that way I don't think so cuz you should get five points right so okay so that's good that we actually found very quickly what uh it's just like the cheating answer anyway uh what case is wrong why is it giving me too - so I wrong why is it giving me too - so I wrong why is it giving me too - so I think it just never goes into streak now I guess actually we start streak at one technically or you get the point is wrong because when you always take away at least one so that's why that should know yeah of course I didn't want button okay well my perfect we're good I couldn't submit early okay so that doesn't seem like that's too easy I need to add points here you should be okay with co2 don't squeak Stewie vibrate so just take something I mean just some off by one and there we could coercion because I think what happens is that this looks okay but I think here is not doing the thing where two four three where we expect is that it takes this 3 and then somehow we merge them so mmm also to see what the left rim is maybe I'm off by 100 trimming okay so actually doesn't do any trimming right and it's that right so just this part is probably right I just poured we get itself you do one there was no so maybe this isn't right the base case should be maybe strict on the street yeah I did that to be lazy way I don't think that's sufficient that's actually even worse so just of a couple of things were having a logic with roughly right but there's some definitely off by one issue there's a great tricky question okay if you have to consider this case more okay that's actually I think maybe we don't need that case nothing western-style okay well we're making western-style okay well we're making western-style okay well we're making something I don't know if it's progress but okay business it was the same card you get one for the same kind of a streak you get four points I think that's good one two with no streak is five point by so that means this food you know gives you five point seven someone's Goz food we were know because in that case we could even simplify to formula even more or the input this you're not very good so okay so I mean yeah so we definitely move may put some progress in the even a user simple case where this is just clearly wrong so I mean so that's good so I don't whimper now but so two one is five points which is clearly well so there's an off by one on the streak somewhere that's probably giving a to streak so because I print wanting to know is that because I print yeah and these are actually lastin first-out first and last actually lastin first-out first and last actually lastin first-out first and last out so sir one course 0 first and with one streak Oh okay I think this would have been okay I think that I just have two cases that is a little bit so the edge case is that if I or you have if I left from itself then it should not get a plus one to streak or because then this would already be too is that right oh why is Trixie sucio one oh good okay trying to think why does have a streak of one right because of this but that's how I say so this is just going this is fine but then it messes up I guess I do need that base case but I need to do that more cleverly because the streak is because it we curse with this trick it being one and then now here it gets five points so why didn't this work because most of those tricks are zero so we've left with zero two right there oh maybe I just need to know this is a okay fine I think this should be okay I think I just need to do something like okay well that Jim plus one you know I think this actually take cares of the left rims I just need to start from there and plus one a thing of spurring the case itself okay so that works for that case you know spend like an hour and you're so still not confident about it so let's try this one I think what we expect is you head to four and then get to five you hit the one and then two so then it should be five but clearly this is not working still something we do we educate this we need left from here for now pointing it is making it slightly more confusing to debug right so no that's okay so it does everything one by one but it does it do the case where we want it to be which is with one eye to be right and right is okay so think we need a cosine here now that's not right trying to think I mean I clearly there's some thing wrong with the right part but what happens happening is that we're not taking in the case where I is you go to write in some way so then it doesn't what happens when eyes you go to write there may be some recurs or likes off by kind of trim area because you have to do left trim as you go to now you can't do tests on the we're missing one case where well that's not we are definitely missing the case where is the code to write but what happens when I is you go to write well like it's just a case when is you go to know but then it if is to go to right and it just recurse the same frame with the street plus one and then you get some wicker surfing which is why wise goes outbound and you know ones are tough and I think we have the right philosophy and strategy I think we have to try figure out but always from because right now it's going so 2 - 1 - 2 - 2 which is but it's not a so 2 - 1 - 2 - 2 which is but it's not a so 2 - 1 - 2 - 2 which is but it's not a because would one and yet I to be right one you ought to be right so this is the case where you press the bun and a foot well switch off the cars on the foot we need a case where if we curse the middle I see three plus one what is streak is zero but in these cases I think what I know that making out and saying that like in this case trick should already be at one I think that's maybe why because once this gets match so this takes care of the default is just when he gets mad she should already be at two let's see hmm well just not conscious week well this ship now yeah maybe this should be right now I think I just need to represent it better look but if no I - well just more better look but if no I - well just more better look but if no I - well just more progress is it that's clearly there's a off by one timer but at least now it's doing you know one but with a streak of or one of a string of two but it's not well this is a streak of two zero one oh I see I cannot set this to 1 but this that seems a little awkward okay hmm Oh still 1 &amp; 2 10 points but why because this gets added twice um it's just off by one so what happening is our pace cases a little think this is because you they said you want to increment it only if streakers - oh okay like right now this streakers - oh okay like right now this streakers - oh okay like right now this is very hacky sugar sir we start a new streak so it's few kids even on one okay even if this is right I'm so not confident about this as a resaw I think there's a thing we should set the fault three a long time we got the right answer there but I think I mean it's one of those things where also I mean I guess well somewhere where I mean it seems like a complicated enough case that applies right but this statement also just means that just some like I think yeah I mean there's some wind acting down that would make this cleaner but when I see somebody before me and see if it works before we okay so that finally work that took over an hour or something like that do i unfortunate but at least now we finally got it and ply spent about half an hour on an well a couple of all by one hours but uh okay well I guess I think that would conclude my foot
Remove Boxes
remove-boxes
You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. Return _the maximum points you can get_. **Example 1:** **Input:** boxes = \[1,3,2,2,2,3,4,3,1\] **Output:** 23 **Explanation:** \[1, 3, 2, 2, 2, 3, 4, 3, 1\] ----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points) ----> \[1, 3, 3, 3, 1\] (1\*1=1 points) ----> \[1, 1\] (3\*3=9 points) ----> \[\] (2\*2=4 points) **Example 2:** **Input:** boxes = \[1,1,1\] **Output:** 9 **Example 3:** **Input:** boxes = \[1\] **Output:** 1 **Constraints:** * `1 <= boxes.length <= 100` * `1 <= boxes[i] <= 100`
null
Array,Dynamic Programming,Memoization
Hard
664,2247
828
today let's talk about question a28 count unique characters of all substrates of a given string let's define let's look at the function first let's define a function count unique characters that returns number of unique characters on s for example calling count unique charts if s is lead code then lt cod are the unique characters since they appear only once in s therefore count unique charts as result is 5. how many letters are there in lead code we have l e t c o d there are six characters but e is counted because it repeated twice more than once so that means if a character shows up more than once it's not unique it should not be included in any answer given the string s return the sum of calc unique charge when t is a substring of s notice that some substrings can be repeated in so in this case you have to count the repeated ones too so we're gonna count iterate every single substring of s and check add up the unique charts of each one of them we look at the examples now s equal to abc the answer is 10. all possible substrates are a b c abc so it's one two three ten aba returns answer eight because the last string returns one instead of three because there are two a let's look at lead code has l e t c o d e the answer is 92 yeah and the string length is 10 to the power of 5 as consists of only uppercase english letters only so to solve this problem i'm thinking about counting the participation account counter participation meaning we only think of we set the left boundary and the right boundary of current substring it's using e as an example so let's say we're interested in how many substrings that this letter is participating um because there's a e to the left of it there's the e to the right of it so we know that e and this e will be participating in only this string so we can for every single substring in this substring we can add one and how many are there are one two three four five so we know that this particular e participates in five substring and add five to the final answer and repeat this for every single character we get the answer for this problem now we start implementing so first of all we create a hash map it indicates the indexes of every single character the hashmap is not necessary and now we're pushing back the sentinel nodes when calculating the range of the subarrays we put one in the beginning put one in the end now for every chart in a string it's uppercase okay we'll push back all right now everything is complete and we just have to iterate through every single item in this and build the answer we iterate every character for every character we iterate every index indices wait for every indices we don't enter it through sentinel nodes and here we build the answer so the answer is there are how many combinations one two three four five six sixth place to put uh this is five one two three four five six five and the indices we want to find out how many characters between two indices so if it's right next to each other it means there is zero so left is how many characters between the last char and current chart the right indices is how many characters between the next chart and current chart what's that there are zero one two zero two minus one that's one zero one two three four five six seven eight two eight there's a five eight minus two minus one yep should be good let's check again we create a vector with 26 char for every char we push back -1 we push back -1 we push back -1 as the beginning sentinel node for every item every chart in this string it's a upper english upperclass case english we push back the current indices of that char and then we push back the sentinel node and we build the answer for every vector in char end you go through the one after first till the one before last yep should be good here we go thank you
Count Unique Characters of All Substrings of a Given String
chalkboard-xor-game
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Array,Math,Bit Manipulation,Brainteaser,Game Theory
Hard
null
787
Hello friends, how are you all? Hope you all will be fine. So today we have a question of cheapest flight with stop in Hindi. This is a medium level question of lead code and it is a very good question. In this question, we all have written as much as we can in our graph. There is an algorithm, we can do all the algorithms inside it is a very good question for doing best practice, so if we read this question, then we get to know the information which is given to us, we have to do a flight. There will be an air inside it, there will be a 2D arrow inside which will be the inner area, inside that we will have three values, one will be from 2 and price will be there which will tell us that from this position we can go from this position to this position, its price will be this. Okay and also we will be given the source, the destination will be given, so what we have to do inside this question, we have to go from the source to the destination, if we can go, if we can reach the destination, then tell us. What is the cost for us to complete the entire route? That cost should be the minimum that I can bring and we have to find the minimum cost by taking that many questions. Okay, but what is the twist in this when we have the given number of This means that all the stops we have in between should be the same i.e. they cannot be more than k, they can be the same i.e. they cannot be more than k, they can be the same i.e. they cannot be more than k, they can be less than k, they cannot be more than but this was a rough definition in our problem. So let us understand this problem, how will we solve it, so first of all, if you look at it, what is given is that we have done one flight, we have an Iraqi van, okay, what is the source, our zero, okay, so and everyone from the position here. Which position to start? I have to go to the third position. Okay, I start from zero. I went from zero to whom did I go to the van? Is there any other way to go to zero? I went from 0 to the van. What? The cost of this route becomes 100. Okay, then I go to you by van. What does it cost? If it becomes 100, then I take down 100 notes. Then I went to whom from 2nd to 3rd. What would be the cost? From here it is 200 ok, so what is my total cost, in this case it is 400 ok. Now the day is back to me. If I look at the van, what option do I have? I went from zero to van and from van to three. Okay, apart from this, there is no option in the graph that I pay three, you are okay, what is the meaning of this 01 and 3, the cost in this will be 100 and here it will be 600, what will be the total cost of my 700, so which cost is less? If you see, the cost is our above cost which is four hundred, it is less, it is okay, but what they have given, what did they say about the stop that they have given, how many should be the case strokes, there should be vans, it is okay. How many stops do we have in the case, one stop is here, the second stop is here, so we have to mince our 2 It's too much greater, give van, so we ca n't do it this morning, see in this punch, how much we have, 1 is given, ours How much is this happening? Okay, so it's min's which is our police path with stop will be 700. Okay, so what will be our answer? The one with 700 will be our answer. So if we talk about its solution. So this is our problem, this is our direct graph, so to solve this type of problem, we have many short cut algorithms, so we use any of them, so here I will use the best one, how to do it. Like it, propose it, what will I do with it, I will take out all the notes, zero, one, three, these are the notes, so what do I do with them, initially I set them to infainite, okay, these values ​​have become infainite, now I values ​​have become infainite, now I values ​​have become infainite, now I look at the van cup from zero position. What is its cost? So I will update it. When will I update it? When I have the initial cost like joinfayeight, what should be its value? It should be given greater. Sorry, it should be given greater. The new values ​​are ok to give credit. So values ​​are ok to give credit. So values ​​are ok to give credit. So I updated. Made it to 100, now I ca n't go to any other position from just zero, so I will go by van, go to 2nd, I will go to 3rd, okay, I will go to 2nd, I will go to 3rd, okay, what will be their position, will it be from you, will it be 200, and give it will be done. 600 is fine, this is from van, so I will check with you, which position can I go to, can I go on three, what will be the cost, will it come by nickel, here the initial cost was 700, so now what will be the cost, will it be 200 + 200? It will what will be the cost, will it be 200 + 200? It will what will be the cost, will it be 200 + 200? It will be 400, so this is the minimum cost, so with this type, we can calculate all the distances from the first notes and know which note we have to go to. By doing this, DJ casts like this, but whatever is our question, put it inside the question. What we have to do is, we have to keep in mind that whatever our stocks will be, what should be the stops, whether they are less or equal, it is case, okay, so what do we do, we will make a matrix of zero, one, three, this is my source note. I take these values ​​to this is my source note. I take these values ​​to this is my source note. I take these values ​​to infinity and I do, from zero I went to the van, then how much will be mine, the van will stop, ok, if I go from the van, how much will you get, from 22 I will go to three, how many stops? 2 will become 2 and 2, when I go to three, how much will be there in this case, 3 will become stool, what will be the minimum, what will be 2, okay, we will make a matrix of this type, okay after doing that, but we will keep this in mind whenever we If there will be stops, okay, what will be the stops, what if that is if it is greater than k + 1, in this case, we will than k + 1, in this case, we will than k + 1, in this case, we will not check it further, it means that whatever, if we implement this thing inside the loop, then we will here. What will we do? We will get him to continue because we don't have to check further. Okay, we will do this and one more thing will be that we have to pass the minimum courses, so we have to take care of that also, so what will we do, we will make it a priority, okay? It's done brother, it will be on priority, okay, on what basis should we get it done, on whatever basis, whatever arrangements we have, we should get it done at this cost, which will be its price, okay, then why should we make it a priority, wait type? Okay and who will arrange it, on whose basis will they do it, on the basis of its cost and priority, when and what will it store, it will store our cost, okay, it will store which location it can go to, okay and apart from that what does it have? How many stops are there? Okay, so let's do its code. Okay, so let's write its code. So first, what will we do? Inside this, we will write the flight from which we return in the form of a graph, then our graph will be Has Map, Wait and List type, okay. This will be our graph new, okay, now inside it we fill the value of flats, instead of 4 ind i, you do this, our type will be okay and flights from , what to do on cute absent, which one is this? We have to check the value of the new brick, okay, the position inside it, the position of F1, means which destiny we are going to, what will happen after that will be the price, f2, okay, this is our hash map, which we have stored inside the graph. Now we create it, we call it PK, new priority, okay, we will keep in mind what we have to do inside it, there should be a price check Why did we become a priority, let's get a set inside it initially PK off Okay, what has happened in the new and values, within this, ours will be the first, what will be the cost, on which we will stand, on this national zero, it will have zero cost again, then whatever will be given from our source, okay, how many stops? It is zero, it is okay, on what basis will this arrangement of ours be, what will be the cost, it is okay, so we make an error in the stop, okay here the ant, this will be our stocks new and its size will be our N. Okay, after this, what will we do inside it, we will get it full What will be the value, what will it be, it will be the maximum Okay, now I will update these and how long will the updated code run until my will loop until it is not a priority Okay, so wait here, not in a second, I have made it here, I have to graph it, this is my graph, you put a wire loop in the file, it has to run till my PK is not there, it is okay, do you post IMD? It is done that what we have on our flight, at the 0 position, what will it become our cost, okay, then what will be our joint, which will be at the van position, what will it be our cost, okay, after that, what will our joint, which will be at the van position, what will be our note, it will be the disposition. But we will go to the flight van, it is okay and whatever our ID is, it will be our stock, how many stops have we taken to reach the position, first okay, the light will come on here, you are okay, now after this we will check here. What will we check if our stop is higher, if it is not higher, is it higher than the plus van or what is the stop metric we have, what is its value in it, what is the stop of the note position? The value is ok, what will we do in these two conditions, what will we do, will we get it continued here, okay, now what will we check after this the country will be continued from here, what will we do, our stop The note is stop dot, what will we do in it, we will update the value of these stocks, ok, now after this we will check if this note of mine came out, is it not destiny, DSP, if it is, then what to do in that case. I will give the cost, I will get it returned, okay and if again, what will I do now, if this is not my course, the cost means it is not my destiny, then what will I do in that case, let me return it from here, again below. After going down, what do I have to do here, I have to grate all the neighbors it has, okay then I will tell you okay, where will I get the neighbors from, I will just bring it from the graph, so the next node of mine will be from the graph. Graph dot get will come, which position is the note holder ok? These positions will come from my graph, ok now what will I do with them, I will add PK dot of new in, ok, accurate. Initially, what will be the first pay, what will it be for me? The cost which I have is the cost + which I have just brought, the next note I have is the cost + which I have just brought, the next note I have is the cost + which I have just brought, the next note which I have added will be on the first position, I will have the price, okay and now what will be the next note will be mine from the van, the next note will be okay. And after this type, what will happen inside the step, the van will increase, what will happen inside the stops, the van will increase, okay like this is done and one more thing keep in mind if I don't have any on this note inside the graph. If the value is not there, then it will be run in the case also. If it is there in this case too, it will run and give an error. So I will have to check this also. If the graph of my graph dot content is not running then it will be called case. What do we do in this case too, let's get Continue. There is no need to check this value. What will we do here? Returns because if we don't get any answer then the value will get lost. Returns OK on line number 20 What am I storing inside the note? 1 second from here, I got the PK flight van inside the flight, I have got the stock not zero and the source is right, it is the note, whose value will come on the note, the value of the flight will come, okay. Here OK, what mistake did I make, I reduced it to zero, I had to store it here, it is ok, let's run it is ok, all three of mine will run successfully, now let us submit it, so here my code is also successfully submitted. So that's it for today's video, see you again with another video, till then bye
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
946
hi guys welcome to algorithms made easy in this video we will see the question validate stack sequences given two sequences pushed and popped with distinct values return true if and only if this could have been the result of a sequence of pusher pop operations on the initially empty stack so in the example one we are given a pushed sequence of one two three four five and a pop sequence of four five three two one so we need to find out whether these sequences match or not since we have first element popped as 4 we can push all these elements till 4 in the stack and then pop 4 from the stack after this we have 5 and we haven't pushed 5 yet so we'll push 5 again after we have pushed 5 then we have a pop sequence for 5 3 2 1 and we also know that our stack would also contain 5 then 3 2 1 in the stack for being popped and so the order of operations would be like this and so we can return true in the second example we can try putting 1 2 3 4 in the start and then pop 4 and 3 so now we are left with one and two in the stack after that we push five in the stack so we are left with one two and five then we can pop five which would give us one and two in the stack but after this i want 1 to be popped but there is no chance of popping 1 before i can pop this 2 and so we return false so this is what we need to do in the question so now let's go ahead and see this with an example and how we can solve this so let's take the first example and here as we are going to mimic a stack we'll take a stack while we take a stack we'll also need two pointers one is in the pushed array and second is in the popped array and we'll iterate over this pushed array so since this popped array is not equal to the value or the top of the stack we are going to push the element in the stack so one gets pushed into the stack and after pushing one also we are not getting a value which is equal to our first popped value and so we need to push some more values in it so we go ahead and push 2 and now 2 is also not the element that needs to be popped to form this popped array and so we'll again go and push 3. similarly we push 4. once we push 4 this popped element value and the top of the stack matches and so we can say that we can pop this top element so we go ahead and pop it now we again check whether my top of the stack matches the current index in the popped element and as it does not we cannot pop the element but we need to push the element and so we'll push 5 in it now in the pushed array we have reached the end there are no more element that can be pushed into the stack and over here then we'll check for popped element and the top of the stack as both are equal we pop the element again as these both are equal we pop the element and similarly we keep doing till the end now we have a empty stack and we have also reached the end of the popped element array that means that we have popped all the elements and so we can say that this sequence is possible and we return true now what if i just change the sequence of these last two values in the popped array if i did that this would have been my condition while i reached this one and we can see that this one is not equal to the top of the element so we would need to push some element into the stack and check whether i get the element that i need to pop but since our pushed array is come to an end we have pushed all the elements in the stack we cannot push anymore and we cannot pop anymore because these are not equal so here we can say that these sequence is not possible as we were not able to pop all the elements from the stack and that's how we'll be solving this question so now let's go ahead and quickly code this out so we'll need a stack with this we'll need two pointers i and j and we'll iterate over each element in pushed array so we'll take a for each loop for pushed and we'll take a pointer j for our popped element and so we'll initialize that to 0 and iterate over our pushed while we are here we initially push the element into our stack and now i'll check whether my top of the stack is equal to the element that needs to be popped right now and while that is true i need to keep on popping the elements from the stack so i'll take a while loop so over here i am checking whether my stack is not empty and whether my jth index that is my popped index is still within the range and my stack dot peak or my top element is equal to the element i am referring to in my popped if that is the case i will be popping an element from the stack and with this i'll also need to increment my j finally i need to return whether my j pointer has reached the end of my popped array or not so that's all about the question let's run this code and it's giving a perfect result for all the sample test cases let's submit this and it got submitted so the time complexity over here would be o of n and the space complexity would also be o of n as we are taking the stack to mimic it so that's it for today guys i hope you like the video and i'll see you in another one till then keep learning keep coding
Validate Stack Sequences
smallest-range-ii
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
Array,Math,Greedy,Sorting
Medium
null
1,727
hello hi guys sub I hope that you guys are doing in problem largest submatrix with rearrangement and we going to see three follow-ups as in we going to see three follow-ups as in we going to see three follow-ups as in two more follow-ups with the actual two more follow-ups with the actual two more follow-ups with the actual implementation so whatever videos you're going to see on YouTube will be the normal explanation which is obvious but Google has asked its followup questions also as you can see it has been asked by Google and direct TY but its follow-ups Google and direct TY but its follow-ups Google and direct TY but its follow-ups are much more important ultimately we will be solving it in O of M into end time and O of n space when I say space I will not modify the array itself cool let's see uh how we can do it and what the problem says right so the problem says and yeah if you have not joined our telegram just go and join it we actually have discussions here cool now just says that largest submatrix with rearrangements now we are having a binary Matrix called as Matrix of size M cross n and you allowed to rearrange The Columns of Matrix in any order so basically for me I can just rearrange the columns I cannot rearrange the rows I can just rearrange the columns itself I can bring this column here that is what I can do cool now return the area of the largest submatrix within the Matrix where every element of the submatrix is one after reordering the columns optimally now I have to return the largest sub Matrix within a matrix so this is the Matrix inside this Matrix what is the largest sub Matrix where every element of the sub Matrix is one so you can see that I can just bring this column here and I will obtain this submatrix and is the largest submatrix with all ones Aran what if I would have bought this row down or something like that no you cannot bring the rows you cannot shift the rules you can only shift The Columns so yeah uh you cannot have this as the submatrix because this is a zero which you don't want you can have you cannot have this as the sum matx because again it's a zero here and you don't want so ultimately you saw that we kind of have this as the only option and the answer is four now uh one very generous General thing which comes in our mind is and we have also seen such kind of similar problems that our Matrix was this and I and yeah I have taken this pictures from lead code because it was very hard for me to draw it um and I wanted many pictures for you to guys see so this was the input Matrix you saw that we shifted this Matrix like this and obtained the answer now I'll ask you can I do this operation step by step I'm saying okay shifting is one thing which we wanted but can I'm saying can I do this shifting operation step by step I know one thing for sure I cannot shift the rules so I can just startingly just see okay in my zero row I have 0 01 so if I only consider my zero row as the only row which I have let's say I have this only as the one row in my entire matter I only have this one row then for sure you will see that the maximum Matrix size sub Matrix size I will have this one so the maximum sub Matrix size I can have is this one that's it so right now the answer is one cool now what if I ask you okay now my rowes are two now my rows are two you saw that okay I've already considered the above row so now the thing which I can consider right now is I can consider this row or maybe the row like this right so I can consider either this Matrix or the Matrix considering above row also so what you will see right now is okay this will contribute just one because above there is nothing this will contribute one because above again it's nothing this can contribute a two for sure this can contribut a too oh yeah that we can see for sure yeah that is obvious so uh what can I say in this I can say for sure that this I'm again I'm only considering right now the columns itself so this is contributing a two to me so for sure the answer can be a two Aran but you did not consider the straight One cases like as in I can also consider this right which is the horizontal one yeah you can consider that horizontal one also that is also for sure but even if you consider that you will actually get a three which is this three oh yeah but let's say for now I just considered that I have my array was looking something like this 1 one and two right because you can see the height of two so I just accumulated that into just one array and made it like one and two now for sure if I just consider this as the only part this is the only part so it will give me a 2 into 1 as the number of boxes if I consider this as the part it will give me a it is a two it is a one so for sure I can only take the minimum so minimum is one itself I'll take the minimum which is one but the length is two itself the length is two this length is two so okay it's again a two so it's again a two what if I consider this again minimum is one which means you will see it is two it is one minimum is one but the length is three now okay 1 into three that is actually a three oh so with this fact firstly I was able to figure out I was able to convert this Matrix into a row and then using that row to find the maximum blocks I can have with ones that is with this I can get okay three as the maximum number of blocks cool let's move ahead and see what else we can do now we will go on to the last R for sure again uh with the previous answer which we had been building so far with this the previous answer had been modified to a one and two for sure again as we contributing this so we can just simply add this up and the last row will actually become something like two now it's a zero oh it's a blocker for us so it will remain a it will boil down to a zero it cannot just become a one or I can just simply can't add it because it's a zero is a blocker for me okay make it a zero itself if it's a zero make it a zero it's a three now you will see that okay uh with this fashion my row as we saw previously also we made a fashion of row as 112 but with this fashion my row would look something like as 203 now in this row 203 can I do the same way I did previously which means ier I just try Okay uh for the first if I just consider only the First Column this one so I will get the three rows three blocks okay his answer can be 1 into three what if I consider the next one oh next one is nothing so I cannot consider that minimum is zero so it will be a 0 into two length is two into two so okay right now my maximum answer is three now I have a block of two but again minimum is again a 0o so 0 into three again the answer is zero so answer would have been three but you saw that the answer was a four what we did wrong that we did not use the fact that we can also rearrange the columns optimally what I can do is I can shift this because I know the column was Zero I know that there had been no columns so I can shift this column two to this side and then the column Z to this side so I will make sure that it is decreasing although you can just start from the end also and you can start from the very beginning also but you will make sure that it is decreasing your this column which you have made right here it needs to be decreasing you can make a 32 0 or a 023 and you can go from this end or this end anyways so with this reordering fact you will get to know oh yeah I can actually shift it now how to shift it simply you know that you have made this array uh you have been building this array which is kind of a prefix sum array which you have been building for every Row for every you have been building this prefix sum array simply sort this prefix some are out Simply you can use a simple sorting and you know that you have let's say n columns you have n columns so for short this row array will actually be having n cells now to sort n cells it will take a n log in time so by this fact you can simply firstly compute this particular part which is firstly you will compute this part it will be a 0 1 then you will simply sort it down let's say you get a 1 0 then you will simply compute what is the answer at every Point okay I'll take this 1 into one or I can take the starting two which is again minimum value into the length which is two and so on and so forth you can go okay when this part is done you will just go on to the next part again you will use the previous values to find the new prefix sums because you want the heights so you will have a one and two now you will simply again Sal this entire stuff out you will get a 21 1 again go and find okay for this my value will be actually two into one okay two now this as minium value has one it will be 1 into two length is two now this has minimum value of one but the length is three 1 2 3 so now my answer would have been three now when this is done cool at every point you know that you are maximizing your answer that is what you want you will just compute this simply sort it down you will get a 3 2 0 and simply compete the same stuff now with this fact you will know that uh you and again um to find this prefix some kind of stuff you will use another array or maybe make a copy of your entire Matrix and then copy The Matrix again uh you can do any which ways which means you will if you have this Matrix so initially 0 1 then you will modify it to a 1 2 then you will modify it to a 203 so you saw that you modified the input Matrix so for sure the space you will need is a n cross M it is a normal space which you would need because although you will say R I'm modifying the input Matrix but yeah if you modify it you will have to make a copy of it that you can assign it later on and the time will be for every Row the time is n logn for sorting that row and how many rows we have M rows so the total time will be actually o of M into n log n and spaces o of M into n let's quickly see the code again it's not the optimized code we can optimize it and you can and you have got a hint how we can optimize it so uh let's see but you will see that firstly I just made the copy of the Matrix because I cannot modify the input matrix it's not like it's not a good practice for code of production so I you will see that I have in the end assigned my Matrix as the Matrix copy because I don't want to modify my input Matrix I just got my m and n as the values again for the most optimal approach we'll code it up but no worries that the these are just the standard ones now for the every row I am going on to every column first and then just checking if that is not equal to zero and for sure I can just check back the previous row then I just do a kind of a perect sum to get added the current row value into my this Matrix of row comma column when this row is being computed for all like for this row all the columns have been computed I'll go on and check and simply sort my current row down because I want in the sorted order and in the sorted order I'll go and check okay for this current row at every value if I have this i+1 indicates if as you saw if I this i+1 indicates if as you saw if I this i+1 indicates if as you saw if I have a 3 2 0 three is the height but how many number of blocks it is just one block right here okay 3 into one number of blocks I can have which is the length this length now if I have these two as consideration you'll see I equal to 1 so I equal to 1 says I have two blocks so far minimum value is two itself because you know it is decreasing so this will be for short the minimum value so 2 into the number of blocks like the length it is actually a two so answer is four and if I would take this three I know the uh length is three but the minimum value is 0 so it is a 0 into 3 is actually a zero so you will take the maximum at every point so you'll take the maximum so answer will be four so that you will give a four and you can simply return the answer time is O of M into n log n and space is actually o of M into n now this was one way but while you were actually solving it you realize one thing that you are actually using 01 then you actually used okay this you can consider as the previous value then you just found out the current value right now this current value which if I had to find I can only use this previous value and I can find as one and two this is the current value and you also remember that we sorted this current value out because firstly now R in why can't I sort this array itself because you have to assign this current value to the previous value later on so just copy this current value to a sort when I say current value I mean the current row I mean the previous row current row sorted row so you can simply just copy this current row into a sorted row and simply sort to this row down so that you can actually apply your operation which you wanted because you only know that you don't require M into n space you only require these n cells because you know the columns are n so you only require these n cells now you require previous rows n cells current row N cells and sorted row N cells because and ultimately when you have sorted down everything is done you can simply assign your previous row with the current row and that how you can simply get this solved so ultimately you don't need the entire space here we are optimizing in approach two in approach followup we optimizing the space and using the O of n space only and using a actually three into o of n space right so yeah let's quickly see the code it's going to be same pretty same uh we actually used the entire again uh we don't need to copy it because you are actually making new rows itself you are not modifying the input are itself you got the m&amp;n and you got are itself you got the m&amp;n and you got are itself you got the m&amp;n and you got the previous row right previous row at 0 now you went onto the actual all the rows you will get the current row right you'll get the current row whatsoever current row is there now to find the answer for the current row you just checked for the previous row as you are doing the prefix sums for the with the previous row itself when this part is done you copy the current row into a sorted row and just sort this row down when the row is sorted for you know that now you can actually go and find the answer in this sort SED row by just saying sorted row of I into I +1 I +1 is the sorted row of I into I +1 I +1 is the sorted row of I into I +1 I +1 is the length so far and sorted row just says okay right now it is the sorted element now again it can be decreasing increasing in any which ways you can just simply sort this up it is up to you cool now uh when this part is done like again if you just sort in the decreasing order then you can go from the very beginning if you s from the increasing order then you have to go in the from the end to very beginning so just modify according the that now I know that I have got the entire maximum answer I can simply return the maximum answer but before that make sure to assign your current row to the previous row you can do the same thing here itself as mean like you can if you want you can still use a two into n space But ultimately it's actually o of n space itself if it is a three of n like 3 into n or a 2 into n it's more or less same way so time is still o of M into n log n but space is actually o of n so you have a optimize the space now comes the more interesting part another followup can you again optimize it with this fact you might still think that maybe not because for sure I think sorting is required I will okay I cannot optimize more than o of M into n that is for sure I know that space cannot be optimized because I want the previous row information for sure because I want to compete the next row I want the pr I want the previous information uh so M into n will be for short because I have to go on to every cell because the mat itself as o of M into n now the Sorting part looks like okay it can be optimized but we saw that we want the order we want the elements in these increasing order itself now I'm saying rather than sorting at the every Point can we make sure that we are building this row the row array which we were building this row aray which we are building can we make sure that we building this row array itself in the sorted order that is what we're going to do now how we will try to just remove the Sorting part now we want to build this row particular array in the sorted order itself now when we say row array and in the sorted order what we would need like sorted order of what of heights you know that we actually in the row what we were collecting Heights right we are collecting Heights okay what is the height as you can see what is the height so far you will see it's a three height it's a two height so we have been collecting height inside my row every row right this every row now I'm just saying that if you're collect the heights inside my every row is it sufficient information because now I'm planning to not sort it down so uh I will be using this Heights itself so okay if let's imagine okay it was a height of three it was a zero it was a two so if or let's say let's take the other example 1 one and two as we saw row number one if the indexing is Zer B so row number one had this Heights so when at the next moment I have to go and iterate on my Matrix which means the row two of my Matrix then it had a values of zero as you remember it has a value of 0o sorry 1 0 and one this is the row which we were making and this is the Matrix input of row number two so uh you should be make sure now when you are planning to Simply sort it down so in your mind it is sorted in your mind it is virtually sorted it is a 211 so if I have this input can I add a two to this one and a zero to this and a one to this no because now it is sorted you also need to keep track of which column it belong to so this height two belong to a column two this height one belong to a column one this height one belong to a column zero so this is I also need to make sure that which column it belong to why I needed that because next moment when I'm going to use my actual input Matrix to increase the heights I should only be height I should only be adding the height okay I'll add this height one to this cell only I will not add here so that is the reason you need to uniquely identify okay height you were maintaining previously also but now you also have to maintain the column so you will see that we will use a pair of vector earlier we were having a vector representing a row now we have a pair of vector having okay uh it is the count which is the height and the column also corresponding to that height so this count says okay it is a height to me now initially you'll see that your prefix height now your prefix height will only keep track of the active elements in the previous row again make sure previous height will make sure you keep track of the active elements in the previous row currently for the row zero there are no active elements so for sure uh it will be empty now first I make sure I process my previous height but my previous height is itself empty in the beginning so I need to process this current row itself now you will process this current row okay when I like when I said to process you only mean to process a nonzero cell so you will process the cell which is one so what you will do is you will just push in the heights this height will show you using the previous height and now the current height whatsoever you have processed this Heights with you okay so Heights will have only the height as one with a column of two will be pushed in so you will see that in the code what we've what we will be doing is we'll go on to for the corresponding row we'll go onto every column for every again we will write that code in the code pad no worries on that part but just for explanation I'm just showing you the code side by side that what is about to happen and what is happening so far we have bu intuition we have build intuition it's just that we will see theod code side by side also for the much more clarity we code also in the end no worries now uh I'll just see okay if that has been false which means now R in why you are seeing it has been false we will look into it but it just says that I will keep track if that cell is visited or not but are in visited by whom visited by the previous height because I told you firstly I will pass this previous height and then I will pass my current height current row right so this previous height will make sure that okay what if I have passed this column inside my previous height I'll show you what it means but yeah this is for that part but then uh for you right now I it just shows that if the Matrix is equal to one oh just simply push this one because now the height is one and the column is there height is one column is there AR in what if the height would have been accumulating we will see that part also but right now you saw for the First Column I will simply add a height of one and a column of two now I will assign my current height to the previous height so that it can be maintained now you will see that my previous Heights have become 1 comma 2 corresponding to this cell I am currently on the rule number one now comes the interesting part firstly I'll go and pass like last time you remembered we started passing this particular Row from the very beginning because we had no previous Heights but this previous height will say bro hold on you have these Heights in the order so please par your previous Heights first it is the maximum height you have got obtained so far so I'll just go and pass this previous Heights first so firstly I'll pass my 1 comma 2 I'll go on to a cell one I'll see okay bro right now so I'll go on to a cell two I'll say bro right now it is one oh yeah I have an element simply add this in my previous value like previous value was one simply add a one I'll get a two so it will show me the current height is two out the column two and you will see it will be in the sorted order because I am passing this previous height first and previous height is actually the heights which are having some value and it is all always I have again I'm always maintaining that in the sorted order itself now again uh when this is passed this is entirely done now I can go on to my input array of heights how I will do I simply go and check okay if now you saw why this was required as seen why this required why this was required as seen because now this you have passed column two you have passed so you don't need to process column two while you are processing this column again while you processing this row again so you don't have to process this column too that is the reason we just make sure that we are marking if something is seen or not seen now when this is for short um like seen so I'll just go on from the very beginning and say okay bro this one is not seen but yeah it is one so bro simply push this in my Heights bro this one oh bro it is also not seen just simply push this in my Heights and also marking the corresponding columns so now that is done so you will see that inside your code firstly you have to process your previous Heights and then you will process your for that row you will process your all the columns again firstly you processing your previous Heights and then you are using this code this is the same code which I wrote above and you will see what is the significance of this scene is actually being made True by the previous Heights so that you don't process this again this column again now cool when this part is done you have got the new heights with you and for sure make sure that when you are getting this new heights it is always in the descending order of their height so also at every Point keep on parallely getting your answer as in the same way just imagine that you have a row with a value 2 1 simply as previously you were doing which is let's say you have a i as zero so it will be nothing but height of right now I do first because it is a pair having this height as the first value multiplied by the length which is I + 1 for you so you length which is I + 1 for you so you length which is I + 1 for you so you will keep on maintaining this as a maximum answer so this is one thing you have to keep on doing now at the last step of the dry run what we are doing is we have this is a previous height now we are currently at the rule number two firstly as I told you have to process the previous height first you will process the previous Heights 2 comma 2 so at column two I have a height of two at column two bro I have a one yeah bro I have a one simply just increase the height at column have increased the height bro at column one sorry at column zero I have a height of one bro yeah I have a one bro I can just simply increase the height I can simply increase the height at column zero now at column one I have a one okay but hold on at column one I have a zero bro I cannot push this in my Heights right now because for sure I cannot use this as my answer of heights so bro this will not be pushed because it is actually zero height I can push it and say okay a column to height of Z but that's of no point I can still push it but that's of no point for me so I'll just not push it at all because it's a height of zero it will give me a zero as a result so you saw that at every point it is still being maintained in the decreasing order and because why is that a reason because you're always processing the maximum height from the previous Heights and then you are for the remaining Heights you are processing from the from this array and from this aray when you're processing it will always be either a one because it will start with the one itself when you're processing from this array not the previous Heights so yeah you will get this Heights as the input now simply as I told you earlier also keep on tracking your answer as the high shot first with this value of I + 1 just shot first with this value of I + 1 just shot first with this value of I + 1 just giving me that what's the maximum number of blocks you can have and ultimately return that maximum answer code is right here we actually code it up but yeah complexity is actually o of M into n and space is actually o of n let's quickly code this up and see that what we have learned so far so uh you will see that firstly I want a m uh just saying that um I have uh my matrix it's a matrix so Matrix of size and I will also have a n which just says mean that I will have a matrix 0 do size so I have got M to n now you saw that I need to maintain what one thing which is the previous Heights so I for that I would need a pair of int in uh that will be of prev heights uh prev Heights now this should be of size what this should be of size n itself now okay uh this is done or like what you saw in the beginning it was empty itself so let's keep it empty itself in the very beginning now I can just simply iterate on my entire row because ultimately I should go on to all my rows so I'll just go on inside my row and I should say as row Plus+ you also and I should say as row Plus+ you also and I should say as row Plus+ you also remember that we wanted an answer as the Min as a maximum answer so simply initi the answer with zero itself now I am going on to every row now again as you saw that if I'm going on to every row uh I need to find the answer for the current row so what I will do is I can simply maintain the answer again that should be a pair of int Comin and this will actually maintain the heights current Heights so I'll just say it is actually my Heights saying the current Heights itself now as in the code we saw that we have to iterate on all of our previous Heights itself so I'll go and say okay previous height and column are corresponding to what previous height and column corresponding to my previous Heights I will go on uh but you remember that we also need one thing which is actually saying that if something is seen if some column is seen or not so I'll just keep track of let's say visited or seen for this case and I'll just say that if that particular column was visited now columns are actually for us in as you see the columns are actually in for us so I just say okay uh right now that is like by default everything is false now when I am at this particular height and this particular column I know okay I am at this row and this column for me so let's say it is this column for me now when I am at this particular column um I know that firstly I'll check bro if that column is actually a column like actually having a value of one so I just asked bro Matrix of this row and this column if that is a true uh so only I can actually go and check my values so I'll just say uh bro if that is the case then that's great bro uh simply do one thing that you have your new height as being pushed in so just say uh heights. push back now you will just push back a new height which is actually H + one new height which is actually H + one new height which is actually H + one because it says Okay I have that corresponding uh value of Matrix and I just simply push this particular height now when this height of previous Heights is done uh you don't need to sort the entire stuff out you can just simply say that my previous Heights are there for me I just have to make sure one thing I have to go into my entire columns again because maybe I some maybe I missed some columns but Aran uh if some of the columns are visited I should also mark them as scene right yeah just Mark the scene of that particular column as true because you don't want it to Travers again so when this is done you will just now can go onto your entire columns again so what you will do is you will just go onto columns again uh as simple as that uh as you have your M columns so it is actually you have M rows and you have n columns now you will just do a simply Plus+ when this part is done you simply Plus+ when this part is done you simply Plus+ when this part is done you just simply go and have a quick check if that is seen if this columns is actually not seen if actually not seen and also the Matrix of that particular row and column is a one so then only you should actually push this in your Heights so I'll just say heights. push back and push back what value it's a one height new height and the current column is this called now I have just got the answer now simply just do one thing iterate on your Heights in the order of itself so I'll just go and I'll just do from IAL to z i less than heights. size and I do i++ heights. size and I do i++ heights. size and I do i++ now with this fact I will know that my answer will actually be I want the maximum answer so simply do a maximum answer comma Heights uh Heights of this particular value which is I but you know that this Heights is actually a pair and the first will contains the height but you know that we want the number of blocks it's just a height we want the blocks so I just simply do I + one so blocks so I just simply do I + one so blocks so I just simply do I + one so with this uh we okay with this we should be able to get the answer uh and simply ultimately return the answer itself now let's quickly see that if you have not made a mistake uh okay we have let's quickly figure out what is the mistake okay um so we just forgot to assign our previous Heights this previous Heights because you know that you need to maintain the previous Heights and this is the heights for us so now it should work because we just forgot to assign that value yeah and with this you can solve it in O of n into n time and O of n space cool thanks back bye-bye
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
92
hey everyone welcome back and we'll be doing another lead code problem 92 reverse link list 2 we have already done reverse link list one this is the medium one given the add of the singly link list and two integers left and right so rever the left two right nodes and where left should be less than right so we are given a head of the link list and this is the link list for example 1 2 3 4 five and we are given left is equal to two right is equal to 4 we have left and right uh no node uh which is from 234 and we want to reverse these nodes and the nodes between them so 2 to four all uh all nodes before uh all nodes in between these nodes are going to be reversed so that's it so first of all we'll making a dummy pointer which will help in the case what if they say reverse one to 4 no so we have a dummy pointer that will be having the address of the head so we will just change our head accordingly and we'll be having a previous let's call it l previous I will tell you why we are doing this which will be pointing to dummy and current will be pointing to the head so previous by the name it shows it will be going behind the current node so for I in range we will go till left minus one because if you are starting from the very first then we are not going to take two steps L is equal to two if we take two steps we are going to be at three current pointer is going to become at three but we'll be doing is just doing minus one so L should be here at two left should be at two but we are not going to be at two we will be just stopping at one so starting from one and then stopping at two so I got confused for a second there so L previous uh will be the current because it is going behind and current is equal to current dot next so our current at this position uh this point is going to be at two and previous is going to be at one we have found the left you can say the left limit or the left node from where we are going to start our reversal we will be making a previous pointer which will be pointing which will be just none empty nothing so for I in range we want from here we will start our reversal we will go till right minus left plus one because right is going to be four and if we do 4 minus 2 it will be giving us uh two so the current will only be updated two times four uh 2 to three one time 3 to 4 two times and we'll be doing plus one because we want to go one node ahead whenever we reverse a link list we always go till the end not to the last node so that's why we are going to do plus one so the current at the very end of this for Loop is going to be at five so now just doing our reversal just make a next in which you can say like current dot next is equal uh next is equal to current do next and then current do next is equal to previous and previous is equal to current and then the current should be pointing to the next node so current is equal to next okay so we are basically done but we have to do uh this uh because the reversal is done but we know that in the left previous which is left previous was at one and it will be pointing to two so this two should point to five so left dot left previous which was at one is pointing to two and now we are at two and if we do dot next it will go like a two do next so it will take like the reference of five and just put it in two so we will say like current so L previous at one its next is going to be two and its next is going to be appended by five which is the current and we want our last node which was four uh so L previous dot next now should be so this L previous is at one so this should this node should point to four which we luckily we have this for node references previous and after that we can just return the dummy. next so that's it uh previous current next what is the current okay again a type mistakes so many type mistakes so if we have a link list like this let's just take this example and run quickly run through it so we have a tummy pointer at the very first and previous is at the dummy pointer and current is next to it so we'll be moving it for one time because left minus one obviously and then we are going to have our current on the Node which from where we are going to start our reversal we will be moving uh we will be calling it LP because it was LP was behind the current one so now our current is at two LP is at one we'll be making another previous which is going to be at none and till the uh this uh previous uh no this previous but this current is not you can say null in the reversal we say null but it is just going through the limits left minus right + one current limits left minus right + one current limits left minus right + one current will reach five and previous is going to be behind Five the previous note we just made here and now we know that this LP is pointing to two so we will do the uh LP do next which will be two do next should have the reference of five so it will luckily we have five uh at current and lp. next should be equal to previous because LP itself is one and now the link list and previous uh you have four so now the link list will look that like uh 43 25 so that's it
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
1,049
all right let's talk about last one weight two so you're given the array of integer of sums so if the two stones are equal they are going to be destroyed if they are not equal uh you want to generate a new stone which is going to be y minus x weight for the stone right and you have to return the smallest possible weight of the leftover stone so uh in this question it's a little bit hard to explain and it definitely a little bit horrible code and then uh let's think about this all right so two seven four one eight one this is a rate so i can probably just say okay two seven four one a one so two seven when they come here and this will give you five this will give you three this is giving seven and then you can still compare so this is gonna be one five and three you compare is gonna be two right seven and two if there's gonna be it's gonna be five again so at the end it's five so this is not the optimal solution right uh again if you want to know how to do this you want to find out like when you compare for the first two comparison so it's going to be first half and the second half right this has to what this actually goes to and over two so what does um so n represents some of the uh stones so eddie so that's a legislation some equal to 2023 i think right so if this is s1 this is h2 right so s1 minus h2 has to uh has to be the output right so this won't be a result right so if this is going to be true so s1 so h1 is close to what sum over 2 but s2 is also close to sum over 2 right but x y is greater than x 2 for sure right so you will get the optimal solution result right so if you understand this part then we can move on all right so let me just redraw the diagram okay so now we need to get the sum for the array it's going to be 23 right and then we need to create an integer so uh the individual array is going to be what uh so when it's matched together right uh the optimal solution i'm in the worst case on behalf of this right so uh you need to create a problem that i would say target probably equal to 23 over 2 so it's going to be 11. so if you still remember i'm going to just um write down my s1 minus s2 is going to be a result and it turns out this is actually equal to what sound minus since this is uh both of this is close to some over two right so uh when i uh and then this is going to be probably right some over two is a target right so it's going to be two times target but target is what is the integer right and i need to put it into the array so i will be able to know what is the target at least array value is so uh this is going to be what i'm going to say just say dp dpt dbt is the following right so uh i'm just pulling to somewhere uh somewhere else so target is going to be y lemon right now uh here's a problem how do i actually need to do this i need to create a rate a rails array of integers from zero to target right from zero to something that's important it's just because for every single time you come here you want to pick the maximum that maximum value for the current index so here is it zero one two three four five six seven eight nine ten eleven all right i'm out of space but they just feel with me so and for every single stone right you can only use once for each iteration so when it goes from beginning to the end you are reusing you are repeating using the previous value right based on uh based on each traversal right but when you traverse from the end to the beginning right you only use once for every single traversal this is because we don't rely on another index in the array right so okay so let's pick two so starting from the m uh so for the current value i'm just writing my current value this is all zero right you will you agree with me this is all zero all right now so for the current value how do i pick my maximum it's gonna be what 11 so current index is 11 right 11 minus 2 which is 9 right so it's going to be this is a dp so dp at i minus stone right dpi minus from process stone you have to pick the maximum between the max between the dp at high and all of space but whatever so you have to say dpi comma dpi minus x plus x is maximum between these right uh so this is i mean this is too much information for sure but they just keep going so uh how do you actually keep track of the value this is based on this formula you have to know what the current maximum value you can take for the current index fdp so when we do the math at the end we can just say sum minus the maximum value and you have to multiply by two this is because x1 and x2 are all close to the sum over two right so you'll return the smallest possible weight right so they're just diving and i'm going to just do some iterate i'm going to do a few iterations and you'll just do a rest okay so 11 is occurring that's either 11 minus 9 okay 1 minus 2 is 9 so 11 minus 2 which is 9 plus the current stone which is 2 right so 0 plus 2 is actually about 2 right so i'll put that into 2 again everything is going to be 2 right until what until here right because if one minus two this is all about right i don't i mean i don't deal with all color bounce uh situation and let me do another partner so again this is going to be what seven so 11 minus seven which is what which is four current value is two plus seven is nine and you have to pick the maximum nine and two so i'm definitely nine and nine minus seven is two so this is nine and rest of it is actually what uh it's actually you know so i'm gonna move to here nine right all right let's uh move on to uh the four eleven minus four is 7 which is 2 plus 4 is 6. so 9 is 6. which one you want to pick is that definitely 9 right so i don't change this value right all right 10 minus 4 is 6 which is 2 plus 4 right and i'm still not changing 9 no changing how about this 8 so 8 minus 4 is what four i mean a two value two plus four is what six i will change to six and change to six right and what else uh nothing right but i just can still going down right five minus one okay so five minus four is one zero and zero plus four right this is four right and this is four right you'll just keep updating right updating your value and then at the end uh you just have to pick the largest which is target the largest value in the db target and then multiple by two and then subtract by the sum right and then you will get the optimal solution so this is actually an abstract problem and it's a little bit hard to follow for sure so probably you have to write down on your paper and you'll be able to understand so i'm going to say bb but i'm not going to generate it i have some right so i'm going to do for in stones some plus people do something right and in target it could be some divided by two right and at least does not matter is there even a number for the target this is going to be your exactly the same thing you need to plug one you should because the best index started from zero right so we need to go all the way to the target value so you have the plus one and they should sum divided by two times dpa taught me right and then we need to traverse the stone it doesn't matter how you traverse but divert to the beginning right to the beginning and you can actually just say what uh to the last one which is not all along right but it doesn't matter because i will say if i minus stone so i is the current that's an array stone is the zone if this is really equal to 0 which is in the bond right and now let's say dpi equal to mass of mass ppi comma dd i minus stone plus the perfect thumb weight so you i will use the other stone once right i started from the back starting from the background and then this is going to be pretty much it right hopefully i don't make a mistake and again this is uh this is really hard to understand so still i'm going to talk about my timing space this is going to be time so this is all of s represents n of the stones this is going to be all of s times out of t represent the target so the worst case is going to be all of s times t for the space this is going to be all of t and this is not constant so just for a quick note uh this is the timing space capacity and again and why is two times dp target this is because again you need to pick the two piles the biggest pile you can pick and then subtract together and then get optimal solution and then this will give you a little uh give you the optimal output for sure and i'm done with the explanation and if you have any questions leave a comment below subscribe if you want it and i'll see you next time bye
Last Stone Weight II
minimum-domino-rotations-for-equal-row
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the smallest possible weight of the left stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We can combine 2 and 4 to get 2, so the array converts to \[2,7,1,8,1\] then, we can combine 7 and 8 to get 1, so the array converts to \[2,1,1,1\] then, we can combine 2 and 1 to get 1, so the array converts to \[1,1,1\] then, we can combine 1 and 1 to get 0, so the array converts to \[1\], then that's the optimal value. **Example 2:** **Input:** stones = \[31,26,33,21,40\] **Output:** 5 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 100`
null
Array,Greedy
Medium
null
390
now is coding tech today we are doing legal question 390 elimination game in this question we are given a list of elements 1 2 3 all the way until n we first eliminate every other element from left to right and then we eliminate every other element from right to left i will keep repeating this left to right and then right to left elimination process until there is only one element left in the list the goal is to find out who the last element is when n varies first let's observe this case when there are two k elements in the list versus there are two k plus one elements in the list so the first round of elimination is always from left to right and we eliminate every other element and from this we can see that the first left to right elimination is essentially getting rid of all the odd numbers in the list so after this round of elimination what is left in the list is exactly the same so we can conclude that when we want to eliminate 2k plus 1 numbers is exactly the same as when we eliminate two k numbers with this important conclusion in mind now we can just focus our energy on solving the case when there are even number of elements in the list given this input after the first round of the elimination we're left with 2 4 6 8 10 and these numbers are exactly 2 multiply one two three four five and now we have to find out who is the last element left when we run the elimination game from right to left first on these five elements with this we can conclude that running the elimination gain on input 2k from left to right is equal to 2 multiply running the elimination game on k from right to left we can write it as elimination from left to right until input equal to 2k is equal to 2 multiply running elimination from right to left on input k this is a very important observation because when input is 2k we're dealing with 2k numbers and is a bigger problem but when input is k we're dealing with a much smaller problem this observation allows us to reduce a bigger problem into a smaller one and this reduction is the essence of recursion now let's try to see what's the relationship on running in the animation game on the same input but with different initial directions when we run the elimination game from left to right the first element to the left is the first one to go and the third element to the left will be the second element to go and when we run the illumination game from right to left the first element on the right will be the first to go and the third element to the right will be the second element to go so essentially the i element to the left have the same experience as the eighth element to the right in those two games so in the elimination game from left to right if we end up finding out that the i element to the left is the last one in this illumination game then in the elimination game from right to left we should find the same pattern we should see that the ice element to the right will be the last element left in this game this conclusion can be formulated like this when we run an elimination game from left to right on input k we get the last element in this elimination game and we're trying to find out what's his relative location to the first element and at the same time we run the elimination game from right to left on the exact same input we find out who the element is and we calculate the relative location of this element to the right and these two should be equal and now we just need to combine all these three conclusions together and we can arrive to a very elegant one-line recursion solution one-line recursion solution one-line recursion solution first let's combine these two conclusions together we have left when input is 2k is equal to 2 multiply from right to left and with half of the input and we see from here that running from right to left with half of the input is equal to k minus from left to right on half of the input plus one and now let's combine these two conclusions when we have 2k plus 1 input or be equal to as if we just have a 2k input and that'll be equal to this guy as well and one thing that is very interesting to notice is that 2k divided by 2 is equal to k but 2k plus 1 if we do an integer division is also equal to k so these two formulas can be combined to be when we have input n we can reduce it to an integer divide two minus running the same function but on half of the input plus one and this is our recursion function another important thing about recursion is that we have to define a base case so over here the base case is when n equal to one so when a equal to one we only have one element in the list so the result will just be one now we can code it up let's say that we want to return one when n is equal to one that's our base case otherwise we do a recursion and it works that's it for the question thanks for watching bye
Elimination Game
elimination-game
You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`: * Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. * Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. * Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer `n`, return _the last number that remains in_ `arr`. **Example 1:** **Input:** n = 9 **Output:** 6 **Explanation:** arr = \[1, 2, 3, 4, 5, 6, 7, 8, 9\] arr = \[2, 4, 6, 8\] arr = \[2, 6\] arr = \[6\] **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 109`
null
Math
Medium
null
1,203
Hello friends welcome to code Sutra in this video we'll be solving lead code problem number one two zero three sort items by groups respecting dependencies and one of the prerequisites of this problem is that we know topological sort and in this video I have explained topological sort in depth and at the end of the video I have shared couple of problems just related to topological sort so that you will get an in-depth sort so that you will get an in-depth sort so that you will get an in-depth understanding these are actually medium level problems and we also have a dedicated telegram Community which you can consider joining where we'll be discussing about these problems right so now let's get into the product in this problem we are given in now let's assume what does this n mean today we have to perform eight tasks we have to perform a tasks and we have two groups right for example these are the eight tasks that we have to perform today and what is minus one indicate minus 1 indicates that these task doesn't belong to any group let's say for example task 0 is watching Instagram task one is say you want to hang out and task 2 say this is belonging to a group so let's put it out separately task two and task five if you look here belong to a group and these are individual tasks which can be performed separately that is watching Instagram hanging out and let's code this is 0 this will be 1. now again three four six are grouped together that is three four six are grouped together now again there is one more task so that is seven which is again not in a group so we have zero we have one and we have seven so these are the different tasks that you have to do today that is 0 1 7 3 4 6 and 2 5. Now what is the group what is the meaning of group is that you have to perform all the tasks together all these paths have to be together performed that is while performing this task say you are preparing for an exam while performing this you are not allowed to watch a Instagram reel only after you have completed you can go for another but the thing is you have to complete all of these three and only then you can go to the next step similarly this group also only after you are completed with this group you can go to the next group or next individual task that is the tasks within a group have to come together so these three have to come together these two have to come together and these can come up anywhere this can come up anywhere now what is expected in the problem it is expected that is we give an output stating in which way we will be performing the task so that is what is given that what that is what is expected out of the problem so how do we get that so we can just give it out right no we cannot just give it out why because there is a condition in the problem which states that before you can perform task one you should perform task six that is this is a sub task of preparing for your exam before you can watch your Instagram reel you have to prepare for your exam that is what it means right similarly task two say for example in this group within the same group only there is a dependency that is before performing two you have to perform 5. right so that is one of the dependency now again four three there is the inter dependency say you are planning to record a YouTube video you have to prepare then upload then you can do the other things right so that is what is mentioned in this finally what we have to give an order in which all of this task will be performed that is the expected output now let's look at what is topological sir we will just understand what is topological sort and if you know already know topological sort please do skip this section and you can directly dive into the ah other section of the problem so now let's understand what is topological sort this is the basics of topological sort now let's think there are three tasks sorry there are four tasks zero one two three these are the fourth tasks that we have in front of us that we need to perform right now it is given for task zero there is no prerequisite that is you can do this task individually so what we'll be doing are task zero let's form a graph zero now in order to perform task one these are the nodes of the car in order to perform task one you should complete task 3 as well as task zero this is what it means which means there is a dependency for task one that is only after you have completed 0 and 3 you can complete or start test one this is what it means now again to complete task two we should have completed task zero and in order to complete us two we have to complete task for three you have to complete as two so now this will be our graph now what is the order of the output that is the way in which we can perform the test to do this we'll be using topological sort based on the idea of in degree now let's understand what is in degree means how many points are pointed towards that point if you're right here if you write here while constructing this graph only what we can do we can write this for 0 what is the in degree is zero for one how many in degrees are there are two in degrees for one there are again one and one so now what do we do how do we get the order we use a stack for this and we put all the elements that have zero in degree because they don't have any dependence and this can be performed first so now let's perform zero this is the only one which is having zero so now let's perform this now after you have performed this the in degree of 1 and the in degree of 2 will be reducing why because this task completion will free one task for this so the in degree will be 1 now the in degree will be 0 here now this doesn't mean we can perform one right so again what do we do since this is 0 now again this will be adding this task that is Task two now what did we pop first zero what are we popping up next two so now once we are done with 2 once we are done with two what is the next that we can pop is one why because this will again get converted to zero that is the in degree will be subtracted so again we add 3 to this stack and we will clear this out finally once we have completed this three this will also become zero that is all the Neighbors in degrees are reduced already so let us write the graph first to have a more in-depth understanding to have a more in-depth understanding to have a more in-depth understanding from 0 what are its neighbor one and two are its neighbors from one what are its neighbor there is no neighbor for this that is there is no outdirected graph for this from 2 there is three and from 3 there is one right so now once we have X clear something from the stack will be going to its neighbor and it will be reducing the in degree by one that is when it got converted to 1 and 0 and if one of the in degree is zero we'll be adding it to the stack once again and we'll be popping it and then once we are done with all this things this will be the relative order of the things that is you have to perform test 0 2 3 and 1 now thank you now let's understand the pseudo code of topological sort what is the input of this the input is we are given a graph that is in the form of a map we are given the graph then we are also given an in degree array say for example we formed the in degree here right so this will what be the in degree of 0 is 0 that is there is no directed point to 0 that is there is no dependency for zero this will be the 0 1 this are the two inputs for the problem now what we will be doing for every we will check for everything if it is a 0 we'll be adding it to the stack now we will be adding 0 to the stack first 0 to the stack and we will check if this stack is not empty if the stack is not empty what we will be doing we will be popping this from the stack will popping this from the stack and we will add it to the answer that is 0 this will be our answer now yeah this has to be answered dot add current that is this node has to be added to the answer or visited in this case now after we are done with that we have to go to Every neighbor and reduce the in degree of that what are the neighbor of 0 1 and 2 so we will reduce it to by 1. so this will become 1 and this will become 0. now there is a check if the in degree is becoming zero what does this mean this means we can add it to the stack once again so we'll be adding task 2 now is the stack empty no so we'll be popping this and we'll be adding this to the answer now again the same thing what are two neighbors true neighbor is three and we can reduce the in degree and once again we can add it into the stack so remove once again three and finally we'll be doing the same thing so this will be our answer now there are some scenarios where this length will not be equal to the actual in degree length for example there are four tasks here but in some cases we will not be able to perform the task in that case we'll be returning an empty array will be returning an empty array but in this example we will be able to perform this style so we'll be returning this order now let's dive into the actual problem in this problem we are given n equals height that is we have 8 tasks and there are two groups right and these are the dependencies now the first thing that we should be doing is to change the group of this minus one why if all of them are having minus 1 is it is confusing right that is they belong to the same group it indicates that they belong to the same group but in fact they don't belong to the same group but they are individual group so in order to write that what we are doing since 0 is taken 0 group number is taken one group number is taken for all the minus one we are changing the group number from Two and so on so this 0 will be given a group number of 2 and this will be given group number of 3 and finally this will be given a group number of four so that is the first step that we'll be doing now what is the second step we will be doing the Second Step that we should be doing is to form the item graph and the group graph right it is not given in the problem we are not given in a hash map or a graph way so the second step we should be doing is to form the graph so first let's form the item graph these are the eight nodes or the eight tasks that we have in our hand right now for zero is there anything no right for zero there is no input now for one there is a input from 6. that is we have to complete 6 before we are completing one so there is a graph from here and I have added an extra node here extra edge here so that the problem will become much more intuitive or understanding now for two there is one from five actually they belong to the same group so that it's okay now from four three there is again from 6 again they belong to the same group for four there is one from three one from six and four five there is one from six this is the extra Edge that I have added so that it will be coming now there are no more edges so these are all the edges and this will be arga so this is the first step that we have to do that is we form a graph on top of that we should also be forming the in degrees of this in degrees of all of this what is the Integrity of zero the in degree of zero is zero then for one it is one and so on so whenever we give this input to the topological sort will it be able to give us the output the first function that we wrote topologicals are yes it will give an order in which these tasks have to be performed so this is the idea we formed a graph and we also formed an in degree array and we will give it to that function and it will sort and give but now the second case is not only the items have to be sorted but the group also have to be solved have to be sorted right why because this may be very haphazard way of telling for example we can do 0 then we will do say 4 then we will again go to 2 and so on so in order to avoid that what we will be doing first we will be sorting the groups as well that is we'll be forming a group graph as well so how do we form a group graph now we will look at on the right hand side that is on the red color I have written the group for group 2 is there any input no for group 2 there is no input for group 3 is there any input yes for group 3 that is one belongs to group three and from where this is coming from 6 actually where does 6 belong to group 0 so from 0 we have a graph to group 3 group number three so this is what will be writing from group 0 there is an output point to group three and who is in group 3 on group 3 we have one so this is what it is indicated by this now let's look at the next thing that is for 2 which is belonging to this group do we have an input no it is the same group 3 and 6 again belong to the same group four three six they belong to the same group so no issues now five and six do they belong to the same group no five and six they don't belong to the same group so we should be writing a graph once again now how do we do that which group does 6 belong to group 0 and 5 belongs to Group 1 so again there is a graph from 0 to 1. now again we should be forming this graph is done these are the only two edges that we'll be having and now again we'll be giving an in degree for 0 it is 0 for 1 it is one zero and so on so now what we are doing we formed an item graph and we also formed a group graph these are the two things why did we form because there is a criteria in the problem that the group task should be performed together and it should also be performed prior to some other group test so we did a item graph and we also did a group graph so that will be the second step of the problem that is the second step of the problem the third step is we have to topological sort both the group as well as the item now let's look at what will be the topological sort of the items let's do it very fast now zero can it be performed individually yes zero can be performed if you look here now zero can be performed individually now one can it be performed individually No 7 can be performed individually why because the in degree is zero now six what is the in degree of six there is nothing coming inside so 6 can also be performed now as soon as you perform six which is the next task that can be performed one can be performed after you have performed one is there any other dependency no three can be performed now after three you can perform five as well and finally we'll be performing two now three four five six seven one more is remaining zero one two three four is remaining so four is the last one that will be performed or this can also be performed before two but the cry thing in topological sort is this order can be a little jumbled also and that will also be accepted I will show you at the end of the code how that will work so now this is the topological sort of just the items that is you can perform the items in this order but now there is an additional step that is the group now what will be the order of the group zero two four one three simple zero two four one and three now what do we have to do we will be creating a hash map we'll be creating a hash map what we will do in that hash map 0 is our first item and to which group does 0 belong to 0 belongs to group 3 so we will be adding in group 3 let us write all the groups these are the groups and now we'll be adding 0 here this is the first task that can be performed in group three now we have seven to which group does 7 belong to 7 belongs to group 4 so we'll be adding 7 here now which is the next one six belongs to group 0 so we'll be adding 6 here now again we have one to which group 1 belongs to One belongs to the group three so sorry one belongs to yeah one belongs to group three and here we have to add 0 and here we have to add one now which is the next one three five two let's look at three belongs to group zero three belongs to group 0 and similarly let's write it first six three four then for one which comes first Phi comes first and then comes two so if you look here all the numbers are written three four five six seven eight all the eight numbers are written now what is the group order is this what we will be doing will take zero because this is the first group that can be performed now six three four we will perform all the tasks that is six three four first what is the second group we can perform 0 at the Times uh what is the fourth group you can perform the seventh task now we can perform the first five to then the last group that will be one this is one of the expected answers so there will be multiple answer for this for example this group can also be interchanged right for example this four and this one both have in degree zeros so that can be interested so there will be multiple answers for the same thing so all of them will be accepted this is one condition in topological sort now let's look at the pseudo code to understand this problem the first thing that we did was to change the group IDs that is for whichever was minus one we assigned them a group ID in order to avoid the confusion that is 2 3 and 4 that is what we did now again we form the graphs and also the in degree for both of them we form graph that is group and item and we also form the in degrees for what we will be doing we will be going through all of this before and we will be forming both of the crap what is the criteria for every item before we will be adding to the graph that is for example if 4 is the before of 2 what does this indicate this indicates there is a graph from four to two so it is reversed here it is before first and then we'll be adding it that is the criteria here and the in degree of I will be increasing in degree of I that is this two is increasing that is the first thing now not only the items we have to do we have to also do the group the first thing is we will check this if both of them belong to the same group do you have to change anything related to the group no we don't have to now if they belong to a different group again the same thing whichever group is before we will take that first and we will be adding to the current group or the ith group just like this here also it is changed and we will also increase the group index so this is the first way of forming the graph that is this will be our second step next what is the third step is where topological sort items separately real topological sort groups separately right now after we have topological sorted both of them what we will be doing we'll be getting every item and we will be adding it to that particular group in the hashma this is what we did right we took all of them and we added it to particular group and this order will be maintained this order should be maintained why because this is indicated from this graph this order should be maintained and after we are done with that particular creation of hash map what we'll be doing we'll be creating our final answer that is in the group order if we look in our group order 0 2 4 1 3 that is how exactly will be going we'll get group 0 and all the items will be adding it to the answer we will go to the next group we'll be adding all the items and finally we'll be returning our answer and there is one Edge case here and this is one Edge case in any topological sort problem that is in the output if there are not enough items say in the input there are n items but in output there are seven items which means we are not able to complete all the tasks say for example there is an interdependency seven and three there is an interdependency like this we will be able to perform this test you know this is one Edge case scenario where the output size will be lesser than n in that case we will have to return an empty list that is will not be able to perform the task that is one Edge case scenario and these are few similar and quite easy problem to understand this is direct topological sort so if you haven't understood the problem first go through this problem and we have a dedicated telegram group I have mentioned the link in the description and only after you have understood the problem very thoroughly come and watch this video once again or try to solve this problem by yourself you will be able to understand this quite fast thank you for watching the video please do like share and subscribe
Sort Items by Groups Respecting Dependencies
print-in-order
There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: * The items that belong to the same group are next to each other in the sorted list. * There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`\-th item in the sorted array (to the left of the `i`\-th item). Return any solution if there is more than one solution and return an **empty list** if there is no solution. **Example 1:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3,6\],\[\],\[\],\[\]\] **Output:** \[6,3,4,1,5,2,0,7\] **Example 2:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3\],\[\],\[4\],\[\]\] **Output:** \[\] **Explanation:** This is the same as example 1 except that 4 needs to be before 6 in the sorted list. **Constraints:** * `1 <= m <= n <= 3 * 104` * `group.length == beforeItems.length == n` * `-1 <= group[i] <= m - 1` * `0 <= beforeItems[i].length <= n - 1` * `0 <= beforeItems[i][j] <= n - 1` * `i != beforeItems[i][j]` * `beforeItems[i]` does not contain duplicates elements.
null
Concurrency
Easy
1187
897
um hello so today we are doing this sleek code challenge part of uh late good april lady challenge um so the problem says that we get a binary search tree we get the root of it and we want to rearrange it in order where the leftmost node becomes the root of the tree and every node should have no loved child and only one right child so if we take a look here um so if you go here take a look um so what we are doing is that so one becomes the rut which is the leftmost child and then its parent becomes its right child the parent of that the right child the left child becomes the right child and then so you can see you are doing um an order travel so and then their parents becomes the right child and so basically left most is the root then its parent is the child and then if there was another like right a node here um let's say zero then we will put it um after it as well right zero can be here because two it has to be bigger but if there was another node here then it will be after it and then we'll go to the parent so left node right which is the n or the traversal um so that's um the idea and then we go to the right side six um and then we go to its so sorry first we would have went to the left child of six but since there is one nun we go to six after that the left child of the next one the love child of its right child and so seven and then eight and then nine so this is the idea um so the first um simplest solution we can do actually is um just instead of doing um is to just do an inorder traversal of the tree right just during all the traversal of the tree which means uh which will get us assorted list so it will get us one two uh three four five six eight seven nine and then once we get that just construct the tree where each node where each value in the list becomes the right child of the previous value right so very straightforward solution that we can do right away um so um it's not the most optimal but it should be straightforward so what do we need to do um we need to have our in order function first so we have node and then we need to call in order on the left side in order on the right side okay and now we need to have the values in order right so we can just actually instead of doing okay let me do it first with the values so when we need the values right so let's just assign them to self we'll get rid of that later and this would be just values append node value so this is it normally in order traversal and if no node uh we want to return nothing just return because we are assigning here so we call in order with the root first so this will give us the values in the right order that in the right sorted order left node right each time um okay so now that we have this we need to just construct the list so let's define a function that does that and so that function would need the current index that we are looking at in the list right and for that function we just need to each time when we call it we need to do i plus one right now how do we set the node um okay so we need to call i plus one right um we also need to create the node with the value before calling the next so the first element is the root right so node we need to create our new node um and then it will have the value at that position right uh because if we take a look here in our first example what we'll have is we'll have one two three four five six this will be the result of our eight nine this will be the result of our in order traversal so our values will be equal to this and so what we do is we make this first the root and then we set its right child to the tree that we get from this which will have the root two as well right and so the right child is not that right is equal to this um and now we want to return the node each time so when we are cursing here we want to return the node to one to the node one uh and then at the end of the last call will the node would be one and we want to return that's our return node here now what should be our base case um of course when we reach the end of the list and the values right and so we want to check if i is equal to the length of values then we should be done what do we want to return when we are done we should just return none so that the so that nine which is the last node in the result uh gets assigned the value no right because it's the leaf node and so we just want to return that here um yeah and so now here we need to call it what's the first uh value for i it's just zero the first position is the root right um and that's pretty much it we want to return what we get from that so let's run this uh so this is self.values uh so this is self.values uh so this is self.values same thing here um if we wish we could also pass it so yeah that would be cleaner so let's pass it and we need to pass it here as well um this is soft values and okay so that passes test cases last submit and that passes successfully um cool okay so now um one sm one optimization we can do here is this here with soft value is not nice right so what we can do is just return the list that we get from the left side and turn this into a list so we can add it so this is just the list of the node value so we can append it so that would be just adding it like this and then on the right side the list from the right side and for each sub tree we return left node right as a list and so here when we reach the end we want to return an iphone so that the concatenation and adding here works and so we do this and now our values are equal to this and we pass it to our in order traversal okay so let's run this uh this is no longer self values this is just values okay and we can submit and this passes this case as well okay so now the next optimization or the next thing we can improve here is that instead of creating this extra space because this is has over an extra space because of the values okay so instead of creating that can we just do it while doing the inorder traversal so that we don't have to uh we don't have to do two passes and then also we don't have to um we don't have to create an extra space so how can we do that so first i'll just separate these like this and then put this back here and now we need to do something with our node values not davao um so first we don't need this construct anymore we can remove it but first let's just comment it out um and now we don't need this we need to still call in order but we don't need to call construct so what should we return that's something we need to figure out here um so what we can do first is let's create um a placeholder for our initial node for our new basically we'll create a new tree we'll not do it in place we'll create a new tree uh that gives us what we want here with the with this uh this format here okay um so we need to create just some placeholder for it so i'll create a sentinel just to make this easier for us and it's a tree node with whatever value you want and then at the end we want to return sentinel dot right on the right side we will set our tree um the other thing is i will have a current value that traverses so that basically when we are let's go back here so that when we are here we hold reference to carrot here and this is so that we can set the rest of the tree as its right child and as we move when we move to the next uh node three here we set that current there right so it moves the tree and we will keep sentinel pointing to one so now we can return it at the end right okay so we will have current which does the traversal initially it's accent you know okay uh and now we go here and what do we want to do we want the right side to be assigned so self dot character right we want that to be the node volume and we want to advance sofkin so that's pointing to the new right so that the next one will ascend to the right side and so we'll do self we'll move current so you can think of it as a linked list because the format is like a lengtheness we would have one two three four five six and so this would be current right and then we would move to the right okay um and this is exactly what we are doing here so before the value was then each time we add to the list node val and then after that we go ahead here and make it the right side but instead of doing this in two passes we just each time we make the right side the node value um so we can get rid of this and now that should be pretty much it we just need to um so we are already returning it here so that should be good um yeah i think that's pretty much it so let's run this the only thing here is that we should no longer return a list we are not returning anything anymore from in order so let's remove this um and this says that so the right side this shouldn't be a node value each time we'll be creating a new node so this is tree node for node we don't want to assign node because node has a reference to the original lists left and right side um and that seems to work so let's submit it and that passes test cases as well um yeah so instead of doing it in those two passes we can do it this way um yeah i think that's pretty much it for this problem thanks for watching and see you in the next one bye
Increasing Order Search Tree
prime-palindrome
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\] **Example 2:** **Input:** root = \[5,1,7\] **Output:** \[1,null,5,null,7\] **Constraints:** * The number of nodes in the given tree will be in the range `[1, 100]`. * `0 <= Node.val <= 1000`
null
Math
Medium
2202
143
Hello everyone welcome to this technique in this video we are covering a problem statement reorder list in this question we have given a single linked list and what we have to return look like our linked list is like this, we have explained in such a way that our linked list That's the first note in L zero L1 is my second note SSC kar L and minus van my N - 1 SSC kar L and minus van my N - 1 SSC kar L and minus van my N - 1 net no dat and L What is my node OK so what do I have to do with my zero which is the node next to it Pay I have to attach my nh3 to someone, I have to attach this and Nahal, next I have to attach someone, I have to attach my first list, the first is my second last example and four, whose address will he have, the first note guide of my link list. And whose address will the first one have? Whose address will the second note have? So now I have to return something like this. In 14, I just want to show you how I will approach it, so like if I have my input list, it is something like this. 1 2 3 4 5 and 6 but whatever output list the van will point to, if it points to six then it will be the output because van will point to six and if it points to you again, then you are fine and to whom will you point to me, it is fine. Which one of mine is it pointing to? Will it point to 3? Will it point to four? So if not which one is this one of mine? This is the output list. Okay, so if I look at this list carefully, this one is you and Three, what are these three, they are in the correct order, the order in which my input list is, okay, but which is my what, 6, 8 and 4, see, 684, what is mine, is in the reverse order, and 1 2, 3, what is my, is in the correct order, so I What have to be done, it looks something like this is the line of the first, in the first, this is my side, so you can see something like this, till this half, I am doing it from left to right and in the half, I am doing it once, so I What do I do if I erase the middle of my link list, then the middle and mine will remain like this, okay then what do I say to the next of my mid, what will I do to me, if I tell it to reverse, then it will become reverse like this Six will point to five, 5 will point to whom, four will point, and my new head will point to whom, six and my head will point to whom, van, and this one is reverse in English. So it will be in this format, okay, so my English has become something like this, so now I will show you, I want to take one point C1 and one pointer, I will take it as you see, whom will my van point to in the link list? Head and C2 will point to the new head, so what do I have to do? Look, in my output list, next to Van, I have to put the last note, then in the neck of this, if I give you a direct dal at the last, then this point will be my loss, so I make a forward point and if I get a forward pointer made, I will attach it to someone next to my C1, I will attach it to C2 and whatever is my C2, I will attach it to someone next to C2. I have attached my F1, it's done, and then after this I will move both my C1 and C2 points, C1 point and C2 point is my C1 point, I will point a point on the forward van and C point will be on my F point. Point will do ok again which is my forward van and forward tu because if the points have to be changed then I have to preserve the forward van and forward tu in the next of life I have to attach to someone In the next of life I have to attach my C2 Okay, and next to my C2, I have to attach my F1. Okay, and my C van, where will it go on F1 and where will my C2 go, where will it go on f2, okay now my Which is again F1 and f2, where will both of them go? F1 will go next to C1 and f2 will go next to C2. Again I have to reduce the same, attach the next of my C1, attach C2 and Si Tu Ke Na Is. On F1, what is F1, my null is okay and then where do I need to go to my C1, where to take F1 and C2, okay on f2, my C2 point and C1 point, both of them become null. Look in this, which will be my own re-order list, which will be my own re-order list, which will be my own re-order list, who will be its head, which will be my link, its actual head will be my head, so we will read it, to whom will my van point to the last note and the last note will point to my second note and my second note will point to my second note. Will it point to the second last note, to whom will it point to my third note, and which note will it point to from the fourth note, is my result list something like this or not, one six to five three four angle, so this is our algorithm, how much complexity? Okay then what am I doing for my half, I am driving C1 and C2 pointer again, then ny2 will be used for that, then how much will be my total, N + N, how many of these two are left, N will be N + N, how many of these two are left, N will be N + N, how many of these two are left, N will be then the total complexity. You are N, which is O, the other is okay, equal you and whatever will be my space. In the space, I have taken my four points, C, Van, C, Tu and F1, F2, so they do not matter much, so I, whatever will be my space, it is not oven. Because I will consider these as constant time, then the face I have taken is mine, so let me show you this question by coding it. First of all, what do I want, if I want a function on help, then what will it do, will it calculate the link list note, I will pass it here. I will pass the head and it is a joint note. If you do not understand this, then I have told both Meethi and the one who has to revise in the beginning of my link list that how will we reverse it and how will we get out of it, then it is okay for you to see both the questions. So what did I tell you, what do we do in this list note, in one I take a slow pointer which points to the head and in the other I take a fast point because pointing it initially points to the head only and the next not of white fast is equal to you. Or the next note of fast next is equal, you are null, okay, then I will get my meat in it, I will take slow to the next of slow and fast will go to the next of fast and when these two of mine reach any of them then In that case, it will be my note, it will find whom, it will find the slow one, then this is my simple calculation, how will the cold be calculated and after that I need another one, I copy this because what is my almost format, this is also mine. What will be left for reverse? What head will I give to it? Which head will be the new head? Okay, so what do I do from here? The logic of my reverse was what was mine. I maintain the current pointer of the previous one. You will get my point. And the current which will point is ok and then what I was doing is my current is not = and the TVS where will it go, where will my current go and where will my current go, where will it go in forward and when I return from here you Who will my previous note be pointing to? I have written both point and reverse to the head of my reverse list, so now how will we do our question, okay if I will apply logic from mine that what remains the head of my reverse list remains null. Or next to my head, this is equal, you remain null, meaning there is one note or no note in English, then in this I will return from here that I do not need anything, advertise my re-order list, advertise my re-order list, advertise my re-order list, what am I doing? First of all, my calculator is fine and next I will make it simple because I need two different notes in two different lists. Okay and then what will I call my head which is my English one? Half portion is to be brought in reverse, so this reverse function will bring it in reverse. Okay, so what will happen to me till now, I have broken the English into two parts and have brought my second question in reverse. After this, what were you doing? It is making points because it will point to my head and this is my C2 point which will find the new head, after that my C2 is not equals tu nali laga tha what am I doing list note will point to the next of F1 and f2 will point to this si tu OK, so I took four points. What was I doing? You were doing C1's next. I have to attach C2. It must have been ordered. So let me run it. Accepted and submit. Thanks for that. Watching d video hit d like button and subscribe and youtube channel
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
1,716
hey everybody this is larry this is q1 of the recent weekly bi-weekly contest recent weekly bi-weekly contest recent weekly bi-weekly contest uh calculate money in the lead code bank so this is a simulation problem you just follow department uh and pretty much that's it so we're gonna go over the code real quick because i don't think there's any algorithmic things over here um because n is less than a thousand um or equal to a thousand so you can do a for loop and that's basically what i did um which is that okay we just keep track of the amount that we do on day one day two day three and then we just sum it all together and that's pretty much it um offset uh for me in terms of code uh offset is just the number of uh weeks um that you know every seven days we add a week and that is you know the week number will determine the starting point and then you just uh do the numbers from the other one um i got a little bit you know handle the day seven differently but the idea is still they're still the same so yeah uh cool um let me know what you think uh this is obviously gonna be of n where n is the input which is not quite linear in the size of the input uh but it yeah and constant time so this is technically exponential in the size of the input but yeah uh that's all i have for this problem but you know it is a yeezy so it's a good warm up let me know what you think i'll talk to you later now you can watch me solve it live during the contest next okay hmm that's off by a little bit this is because it has to be seven that's why uh hmm uh a little bit disgusting but that's okay let's try it come on that looks fast enough hey uh thanks for watching uh this was a rough contest um for me uh just because i was being silly maybe i need more sleep but yeah hit the like button to subscribe and join me in discord and i will see y'all later 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
91
hey guys how higher is everything going I hope you are doing well I'm safe please stay at home stay healthy let's take a look at number 91 decode ways a message containing letters from A to Z is being coded to numbers using the index a is 1 B is 2 that is 26 and we're given a non empty string containing only digits determining a total number of ways to decode it input is 12 for example so it might be 12 to self which is L or a b12 and 2 to 6 it might be to 26 SP is e the F 2 to 6 or PB F 2 to 6 it's like kind of pretty straightforward we like we're getting like 2 to 6 with we first get the first digit 2 it might be used as a standalone or combined but it's the first index so it's sorry it would be used to stand asses standalone digit plug to itself and then we could just handle the rest right to sex and then or the next one is 2 we can contribute to 2 as a whole and handle the rest a 6 so this leads us to a naive recursion solution right the idea is simple for each digit we check the next digit if they are between 10 to 26 we need to do some conditional checking for the other for the rest like 30 numbers above 26 the only one there's only one possibility so we don't need to worry about that okay so let so it's recursion we use so we create this walk method say check ok the intermediate result will be the number of the ways so I say count and the next parameter would be the rest right we handle 22 the rest would be six we could passing the rest substring right what generate a new substring so I will just use the index to send for it so we'll just start and fine and so when this is done we can just return check the count of course counter is zero and the start put zero so let's do it we get the character right okay start now let's check what's the possibility of this character if track actor we switch character if it's zero okay is zero there's no matching for zero right so we will just return zero there's no possibility for zero and for one we need to check the next digit because if next ticket is zero then it must be ten if it's not zero there are two possibility okay so if s start plus one equals zero then there is only one possibility as ten combined so we'll return check count start plus two for the other cases there will be two possibilities one itself or one X right so we check first it's one itself count start + 1 + check count start pass - mmm start + 1 + check count start pass - mmm start + 1 + check count start pass - mmm this kind of like Fibonacci fibonacci case - it would be the same so check if case - it would be the same so check if case - it would be the same so check if is 20 if a start plus 1 equals 0 oh it's not number you should be string a return check count start to for the other cases while for - it's a little special while for - it's a little special while for - it's a little special because the possible ranges for combined letters digits will be from 0 to 6 if it's bigger than 7 then it will be only a one possibility so if start cuz one is bigger than 6 JavaScript will do the transformation by itself if it's bigger than 6 there's only one possibility so - seven only one possibility so - seven only one possibility so - seven something like - 7 return check count something like - 7 return check count something like - 7 return check count start plus 1 for the other cases there will be two possibilities like 2 or 2 X return check count start + 1 + check can return check count start + 1 + check can return check count start + 1 + check can start plus 2 for the default defaults well the 40 it's the same right so for the other cases it will be only one possibility yeah for three because it's over three yeah return check count plus one Oh start run start press 1 now we have a problems is that when we win we'll be done when we'll be done and so we might jump one step ahead or two steps ahead so if the index might be over than over float so if the digit is last number it's obviously is only one possibility or it's over that last number that's also but if they surpass the last digit it will be us also one possibility so if start is bigger or equal to s then s 1 then the possibility would be only one but if we do this if the actually the last number is zero this is this will not be good right so I think we need to check here if character is zero because you see if we do something like this it's for a valid input it cannot generate extra zeros so I can safely return 0 here and it returned this ok so we run the code for - 1 - should we turn we run the code for - 1 - should we turn we run the code for - 1 - should we turn - yeah for 1 - 2 6 you should return 3 yes we let's submit and by the same time we analyze the time and space complexity for time we're using recursion for the best cases you see we only encounter problems as case here or here so if not nothing is special everything everyone could be only as is the stand used as the stand alone digit it will be Oh n right so the worst case is that every time we met two that we met two possibilities then for that it would be FN would be Fibonacci right well because we're using we using the we are want to know the worst case so FN it's just use two if we do the approximation uh if we do it approximately it will be two to something like this right so it would need to O 2 to the power of n so it's X potential it's slow as we can see it's only faster than 30% of all the it's only faster than 30% of all the it's only faster than 30% of all the solutions so for this kind of case for any time we meet the not that good solutions with the recursion we might want to rewrite it into iteration with the dynami programming so we try to use dynamic programming so how can we on we understand this problem now I'll just to remove all the code it's because they are not need it anymore let's take a look at the example ok again for 2 to 6 for two - okay let's say if we are doing for two - okay let's say if we are doing for two - okay let's say if we are doing done with all two to two solutions now we add an extra digit which is six so what will happen so four to six and most usual use two extra one numbers digits two to create a combined like 26 right so it will not affect the digits before these two and depending on this number could be used as combined or standalone we can actually derive a formula which will help us get to get the count of ways I'm not sure I am putting is right I mean for this for extra number six there is two possibilities right the first one it we use as a stand alone or combined right if stand alone it will affect facts n minus 1 which means just use the previous one previous result if you combined it will use effect hmm use F effect F and minus 2 all right yeah stand alone yeah so it's obviously let's say for FN which is the nan thought this digit length of this digits FN what it means if we could use this as combined if we use as disk of first let's use at is it a standalone digit if you stand along if will be F and minus one right which would be the same because you use as a standalone plus if you use it as combine it's like this it's we use F and minus two right if can write if can also now it depending on conditions required so if we say s n is zero what will change if it's zero then the previous one must be one or two if it's one or two then we can use FN right so and s n minus one is one or two we use they combine so f minus two or it should be zero yeah if s n is 1 to 6 and we can check SN minus 1 is 1 or 2 we will say if it could either be used as standalone or combined that would be F and minus 2 plus s and minus 1 if we use these as combined so the solution would be here wait a minute there's a problem is that for case here if we use this combined we use F and - - it's okay but if we want use F and - - it's okay but if we want use F and - - it's okay but if we want to add 2 - n - 1 like this actually to add 2 - n - 1 like this actually to add 2 - n - 1 like this actually contains the solutions it might contains the solutions because this one use I think it's right for x4 like this is to the conditions here possibilities here to if it's combined it's one possibility and now plus the possibility here combined standalone hmm yeah it's right and then if is seven for the other one once we need to check s and wow it's trivial s1 minus one if it's one then it could be the same like this if not then it must be used as a standalone so like this hmm okay let's just create use array to store the intermediate results let's say result equals array s and few is 0 for let's I equals 0 we need to how can we handle this start of this problem Wow I think I need to shower sir - empty Wow I think I need to shower sir - empty Wow I think I need to shower sir - empty numbers at the beginning like plus two extra so for the first number it will get zero right mmm feel with one I think yeah nothing means one possibility for this one but remember when we get the result we needed plus two for the index so the way to avoid problem i + - okay so the way to avoid problem i + - okay so the way to avoid problem i + - okay um cost character equals s i this just do follow what we will it here if character is 0 and if s I minus 1 is 1 or 2 1 - if it's 1 2 then you should be or 2 1 - if it's 1 2 then you should be or 2 1 - if it's 1 2 then you should be used as combined so result index would be result index - - yeah be result index - - yeah be result index - - yeah for the rest it should be invalid so it should be 0 actually we should we just we could just return zero to invalid okay for the rest if-elsif captor is smaller than seven if as I minus one it's also if previous one is one or two there is two possibilities so we so results index equals results X minus one plus salt in this - two for the rest there's only one possibilities results index equals result index minus one for the other cases Joseph if is minus one is one anything's possible so this and you could do this finally we return result yes this minus one question I'm not sure I'm really not sure I'm doing this right and it's just around the code of course there's a scientist error mmm it seems as we're doing it yeah okay cool submit oh yeah we're accepted wow I'm really not I'm not really not very confident on this one but it turns out our approach is right we first we did it with recursion but it's bad because for the worst case it was the time complexity is almost exploitation and now we're using dynamic programming we cashed all the results and by analyzing the last two bits of the input so now the time would be time complexity would be you see for every one for each digits we are using constant time to do the calculation so it will be linear time oh it's improved very much and space we use an extra space to store the result yeah it's oh and actually you see be for the most extreme case we only check the last two results right so actually this could be improved to use both sir sorry the recording seems some recording seems broken I'll just continue so the space we're using n OB goin to store all the result battery we only need three of them so this could be improved - yeah Oh - but I'll skip the improved - yeah Oh - but I'll skip the improved - yeah Oh - but I'll skip the implementation you can just do by herself like here we could just initialize with two elements and use push and palm to get to set to result yeah so that's all for this problem hope it helps you next time bye
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
3
so today i'm going to show you the best way to solve this problem in lead code this is longest substring without repeating characters so basically we have a soft string like this i count a b c i find a here it means that we have a repeating character and then it means that the longest so far is this and then we can now start from b this time and count b c a and find another b and the longest repeating character is b c a and then we can start from c and find c again we have this and in that way now if we do it this way it means that we are going to have several iterations so the first saturation is gonna start from this one and scan through the whole string and the second iteration we're gonna start from the second uh character and scan the whole string and that's more or less like a kind of sliding window approach but is also brute force so we are going to use the proper sliding window approach so again you'll be using sliding window approach so some call is shifting window or moving window so how does it work so you are going to set two pointers the left pointer and the right pointer so basically the left pointer is going to start from zero and the right point is going to start from zero so the first time you want to check the substring between left and right which is zero you are going to check if you found it before you simply remove the original one so in this case a have we found a before no so we are going to move next we go to b have we found b before no so i'm going to move next and in this case we are going to be keeping track of the length of the string as we go so in this case we have two in this case we have three so if we have a higher number in this case is three we update some results set we have or some result values so start from zero one two and if we come here we have a and we've seen it before yes so it means that we're gonna take it out from here and move our pointer the left point that comes here and then we continue and in this case we see now bca is a different uh string but we have all these items now we've seen them uh so we have we've seen a before we saw how have bca the length of this trend is three so a is not it's not greater than the maximum we've seen before so the idea is to maintain or reach the length of the strings so far maintain two pointers and simply have a set or a hash table or hash size that you are using you are going to use to remember items you've seen along the line i think it's gonna be more interesting if we write it out in code and let's see how it looks like in code so let me write the code at this time so the first thing i want to do is to initialize something like a sex let me call it t for dictionary but it's actually a set and we need a left and a right pointer so the left pointer is going to be set to zero so it's gonna be set to zero and we also need the count of the current number of uh the current string with the maximum substring so for now this count uh let's call it count is equal to zero for now because we've not stopped it so it's now going to start here and not the second point is now the right pointer is going to move from um from zero to the end of the string so from zero to length of the string and we are going to now check that if the while the current item and the current item is the item at index right so it's going to be item at index right so item at the right index means that the current item which is item of index if we found it before if it's indeed remember that we're not going to remove we're not going to so we actually want to put a comment we are not going to remove that item because he's there yeah is this but we are not going to remove it we are going to remove the original item that was there so basically we are going to remove item that this item here item at index left does the first item which we are sure is there so here we are simply doing a check okay so that item is i at index left so i'm going to just remove it i think i can say d dot remove and specify the item which is s left okay so this is what we have and then we are going to increment our left uh pointer plus is equal to 1 now regardless we are going to increase the right pointer and of course this for loop is already increasing the right pointer so what we are going to do now before we go to the next uh the next titration we are going to simply check if the current substring the length of that current substring is greater than the count we have here so the current substring here is showing from index left to right plus one right in python we have to say plus one because the last item is last index is not inclusive so we're going to use plus one so it's going to take from left to right so i'm going to check if the length of this item actually we are going to check the length of the list array so we are going to check the length of the substring from index left to right plus one so if this lines okay if this length is greater than the count then we are going to replace it actually we are simply going to do it in one line by saying that count to be replaced by the max of the count and actually we don't even need to do this uh line we are simply going to uh just use left actually right plus one minus left so if right plus one minus left so of course you can just say right minus one plus uh left uh sorry right plus left minus one okay perfect i think we should be done at this point so we will now simply uh return the count because what they want us to do is return the count of the items right so this is basically it so we are returning the count which is not the string itself but actual the actual count of the number of characters in the string so let's go ahead to run the code and let's see so i'm going to start by let me just cross check right and hey let's try to move life okay great so i'm going to run it now and let's see what we have and we have a problem ah sorry i made a mistake so uh we actually going to add the item to the set at this point uh before we actually increase so i'm going to say d dot add we are now going to add the item so it's going to be s right okay so we are going to add it to the set okay so i'm going to run the code now and let's see what we have and you can see that it worked at this point so let's go ahead to submit and let's see so i'm going to submit and hopefully this time is going to work and you can see it worked perfectly state use is accepted here runtime is 16 milliseconds 60 milliseconds faster than 81.64 of python 3 online submissions 81.64 of python 3 online submissions 81.64 of python 3 online submissions so i'd like to thank you for viewing please remember to subscribe to my channel if this has been informative for you if you have some challenges you would like me to crack please leave it for me in the comment box below so we see in the next part
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
443
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is string compression so in this question we given a character array called Cs and we need to compress it using the following algorithm so we have to begin with the empty string s for each group of consecutive repeating characters inside the input cards if the length of that group is one we only have to append that like in this case in the entire character array a is repeating only once you don't write A1 you only append A2 otherwise we append the character following the group's length like here in this case a appears twice so it will become A2 in the compress string if it was appearing only once we only app that character like in this third example and the compress string s should not be return separately but we have to store it inside the input character car itself so we have to use the input character only and store the compress string inside it so you have to modify the input array in place so after you are done modifying the input array you have to return the length of the new array that is the length of the compressed string so this is the input array which is having length seven compressed string has length six so we return six as the output and we have to write an algorithm that uses only constant extra space that is O of one space complexity now let's take a look at these examples and see how we can solve this question so this is the input given to us a is appearing twice so it will become A2 B is appearing twice so it will become B2 C is appearing twice so it will become C3 finally the length of this is6 X so we return 6 as the output coming to this case the input character is a so after you compress it Still Remains a but not A1 because this is not compression you're actually increasing the length so if a character is repeating only once you just append that character since that is the only character present inside the input so a will be returned as output so after completion it will have a and the length of this is one so you return one as the output now in this case a appears once so a it is and B appears 12 times so B 12 should be appended as two separate characters the length of this is four so four will be returned as the output now let's take a look at example one and see how we can get the logic so I need a variable index which will be zero and I'll use this index variable to access the index positions inside the input to form the output because we need to store the compress string inside the input array itself now I need two variables start and end pointer start and end both will be pointing in the beginning so this end pointer will go until the end and we iterate from the left to right of the input area now we check if the character at S and E are same so s is equal to 0 e is equal to 0 both are pointing at the same so I move the end point of forward now check if character at both s and D are same yes both are same so you move the end pointer again now you check if the character at s and D are same a is not equal to B now we find the length between them is 2 - between them length between them is 2 - between them length between them is 2 - 0 you can find the count n minus start which is equal to 2 - 0 so which is 2 which is equal to 2 - 0 so which is 2 which is equal to 2 - 0 so which is 2 since this 2 is greater than one because we have to check this case where if uh that character is repeating only once we only upend that character but here it is repeating twice so we append that character and also the count so I'm going to use this index variable so index is pointing at zero so you append that character a first so you append the character at start so a will be appended so this is a integer right we need to convert it into a string and then I convert it into a character array so that we can access it as a character we access that character and append it at index it will append that character there so it will this will become two and now before starting our next iteration we move start to wherever end is there so start also will become here and now we also increment index is two so next insertion will happen here now we check if character at start and end are same yes they're same so end will move forward check if both start and characters are same so move end forward check if character at end and start are same no they're not same B is not equal to C so you find the count is end minus start end is 4 and start is 2 4 - 2 which is 2 again we start is 2 4 - 2 which is 2 again we start is 2 4 - 2 which is 2 again we convert it into a string and then we convert it into a character array because if like in this case if the count of that is 12 we convert 12 into a character array so 1A 2 will be added like that into the character array now we insert at index the character at start is B so B will be inserted and also increment index now we access this and insert it at index is three so this will be replaced by two and in the next iteration again start will move wherever there is a now let's reset the pointers and also reset the index will become four and this is where the next insertion will happen now again check if character at start and end are same yes so move end forward check if character at end and start as same yes so move end forward and now we end the iteration because we reach the end of the character array now we find the difference to find the count start is four end is six again end minus start is equal to 6 - 4 equal to 6 - 4 equal to 6 - 4 again you get two so this is an integer convert into a string and then convert it into a character array to access each character of that digits so insert character at start at index is four so c will be inserted here now move index forward now we need to insert this at index is five so this will be replaced with the count is two start will be reset back to where end is both reach the end we also increment index is six so this is where the next insertion will happen but we reach the end of the iteration so whatever is present inside the variable index so index is now here which is equal to six so this is the length of the compressed string so we inserted six characters into the character array in place so this is the expected output six now let's Implement these steps in a Java program so this is the function given to us then this is the input character array and the return type is an integer let's start off by creating the index variable which is initially zero because we have to use this variable index to insert into the input character array because we need to store the compress string inside the character array itself so this will be our output two so finally we'll return index 2 which will be used to denote how many characters we have inserted into the character array which will also be the length of the compress string now we decare the start variable start is initially zero and the start variable will iterate until the end of the character array now we need to declare the second pointer end which will start each iteration from wherever start is so in end equal to start initially both start and end start with the zero index that is the first character now we need to check if the character at start and character at end are same so until then we keep incrementing and while CS of St part is equal to C of end so whenever this is happening we keep incrementing the end pointer and this while RP will terminate Whenever there is a mismatch between characters like here in this case these two characters are not same so when these two characters are not same this will break and now again we have to check one more condition is that if end is always less than the length of the cast aray because end might reach the end and start might be at the beginning so this boundary check is important to do now as soon as there is a mismatch here we need to find the count of these two characters which can be found out by n minus start now we need to insert the character at this index position with the character at start so C of index is equal to C at start and each time you insert it into the character array you also need to increment it for the next iteration now we inserted the character which is at start now we need to check if this count is greater than equal to two only then we have to append that count also to the compressed string inside the car array so if count is greater than equal to two then we need to convert this count into a string and then into a character array so I declare a character array called frequency and convert this count which was initially integer into a string so after converting this string into a integer we need to convert this into a character array using the two car array method now we have the count inside this frequency character array now we have to iterate through the characters inside this character array and append it using this index position into the C array so use a for each Loop where I access each character inside the freak ARR and then again insert it into the character array using index with ch and each time we increment the index position to move it to the next index position where the next character should be inserted or the next uh character at the Cs of start should be inserted and finally before moving to the next iteration we have to reset back uh start will come to where end is starting so start is equal to end and finally outside the while loop we return the variable index which will give you the length of the character array so let's run the code the test case are being accepted let's submit the code and the solution has been accepted so the time complexity of this approach is O of n where n is the length of the character array and the space complexity is O of one because we not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
String Compression
string-compression
Given an array of characters `chars`, compress it using the following algorithm: Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: * If the group's length is `1`, append the character to `s`. * Otherwise, append the character followed by the group's length. The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. After you are done **modifying the input array,** return _the new length of the array_. You must write an algorithm that uses only constant extra space. **Example 1:** **Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\] **Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\] **Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ". **Example 2:** **Input:** chars = \[ "a "\] **Output:** Return 1, and the first character of the input array should be: \[ "a "\] **Explanation:** The only group is "a ", which remains uncompressed since it's a single character. **Example 3:** **Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\] **Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\]. **Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ". **Constraints:** * `1 <= chars.length <= 2000` * `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
How do you know if you are at the end of a consecutive group of characters?
Two Pointers,String
Medium
38,271,604,1241
854
in 1854 of Egypt site macri similar links passion is what this problem is about is that they are going to give us two strings and for example these two and we have to see how much is the minimum amount of suárez that we have to give to get to one string to the other because it is here we only have to invest see and season 2 swaps I have the same word no so that is what we have to do it we are going to treat this as if it were a problem of crossing a tree where we have to reach to the string quartet for search no sorry brett for search because that is the element that is going to give us the quickest way to get to where we want to go ah well then I'm going to do it as I explain and we have this one we're going in a swing set To know which stranger we have analyzed before, we are going to analyze it again and we are going to make a strings file to make the search for Perez. We are going to put a variable for more in the result and we are going to add it and we are simply going to go through the The problem is not so much and without reality here and well we are going to do it as long as it is greater than or equal to zero so it is tomorrow more and I will take out the touring we are going to put it at 7 mp and we are going to take it out of the curve and here we are going to give it a pointer called l a pointer l like dellert and let's see, for example, in these two let's say that our two words are these so we start here ssl but it in the string is the same so in case we know it is so people point me out success are equal then increase l to something else good at first yes without restriction equal and it is more good as we move forward here is here a different one and we are going to make a new pointer my hero grew that is going to be equal to l plus one That is to say, it will be here as long as it is less than attached links although tmp pointed out that they read that they are exactly the same and the oscars and we are going to search in this string in front of the pointer l for the letter send that we are looking for example, here we find it but let's assume that our two words are these no so here maybe here we find the life that we are looking to provide is the same as this time and then there is no point in changing it because that is already there as where the job comes to us we will look for another one later is this and if we save a step in the draw if you see the difference then we touch here is that and if I have dot chart r is not equal to ante anddot charata the murderer is equal to this that we are looking for 1 if it happens that this is Maybe this then we're going to hit it with cinema because we don't want to move that since we found a letter that meets or doesn't meet these two conditions so we made the swap, let's say it's a I don't know water string or something like that and we're going to pass the iron since we have the strings water in something else you have to put sound here the string swap will be created we have to see if we have already reached that point before so if it feels continuous it is of no use to us is if it is not like that then we are going to add the and The most important thing is we are going to put it in our you to analyze it later to well and other things of course here we are going to increase the result and in this part if its 5.5 als result and in this part if its 5.5 als result and in this part if its 5.5 als red I mean if we find the result then we simply have to return it no and it seems to me that this is all they want to be if I'm not mistaken let's see if it works clear passage increment the smooth function is the function is very easy we're just going to pass the string let's go for it and the int r and the thing is going to be an array of characters in this cancer so chad rey pointed out shower rey and we are going to do this little trick what is the swap with exclusive arches in order to investigate how this method works what it actually does and we simply return string dot value of richard reid I know if it works, they don't exist, visit card you already saw for this one, but hey, the case exists, so we are going to be available for everyone and science for everyone, and this is a good solution. The program can also be done in other ways. There is a very interesting way to do it. which is doing a string processing is very interesting I'm not going to do it right now but if the problem is solved I think it 's the quickest way to do it's 's the quickest way to do it's 's the quickest way to do it's in the statistics go over here and see this is the way they do it 0 milliseconds which is incredible in this giant the migration of pro search but what gives the ponchis that this processing as well as in heat simply what I find that can surpass thus the first view of the open counts how many swaps and then almost with details of the for search reyes I save a lot of draw no so that's why you can do it practically instantaneous there is even the difference of doing it so for example the first time I did it through project for search due to depression and I got 283 thousand seconds or there is not even a comparison
K-Similar Strings
making-a-large-island
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
null
303
what's up everyone today we're gonna be going over leaked code 303 some range query and this is pretty much a kind of a design problem but they'll give you a integer or no index is I and J between this area and they want to know what the sum is between that of course it's super simple if you do kind of like a brute-force but we're gonna do it with a brute-force but we're gonna do it with a brute-force but we're gonna do it with a little bit of dynamic programming and I notice that there's a lot of thumbs down I'm not sure why this is a pretty it seems like a useful problem because in an interview if someone asks something simple like this you give a simple solution but they can say how do we make this scalable or how do we make sure if this is happening repeatedly you know little tweaks like that helps us solve problems like this so I just get into it I am going to use it DP array of the same size and I'll show you how I do that one so and DP into DP is first if a our length is zero we can return yes you can actually return on a constructor otherwise DP is set to new and a r dot length and then D P is going to be pretty much the first one is it gonna be the same thing as a R and then we're gonna iterate over it for int I is equal to 1 I less than a r dot length I plus DP of I is going to be DP of I minus 1 plus a R of I and that's the constructor now what we're gonna do is this let's let me actually write out what the DPR a for this one is gonna look like BP would be negative 2 0 1 negative 4 to negative 4 2 &amp; 3 what they want is 4 to negative 4 2 &amp; 3 what they want is 4 to negative 4 2 &amp; 3 what they want is the summing between say for example is your honor - they want this or they want your honor - they want this or they want your honor - they want this or they want 0 1 - this or they want this some 0 1 - this or they want this some 0 1 - this or they want this some of that these are the outputs now the answer is pretty straightforward pretty much what you want to do is DP of I D P of J the outer bound - the DP of I but of J the outer bound - the DP of I but of J the outer bound - the DP of I but since we want to include the number at I what we need to do is DP of I minus 1 not DP of I so there's going to be one edge case where the I that they give is 0 in that case all we do is return d PF j so DP of 0 - 0 - - is it gonna be d PF j so DP of 0 - 0 - - is it gonna be d PF j so DP of 0 - 0 - - is it gonna be d PF j which is that and is that one so if i is 0 we return DP of j otherwise we just return DP of j- DP of I minus one the reason we DP of j- DP of I minus one the reason we DP of j- DP of I minus one the reason we do this operatives check is we want to make sure that we're not going out of bounds when we do I minus one and that's how we celebrate code 303 is a simple problem but there are so many downloads I just wanted to show you guys that it's not hard or a problem to feel annoyed about at all so anyway if you like this video please subscribe please share and please like it'll one of it me to keep making some more thank you
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
43
hi guys let's do the multiple strings problem lead code 43 and it's kind of a i would say slightly more complicated version of lead code 415 i guess which was add strings and the idea is that you're doing all this addition or multiplication and all that without converting these strings into numbers or integers by calling some library function so we are not supposed to convert them into numbers first and then do that addition or multiplication but rather we are supposed to be doing this without converting them into integers so i guess the exercise becomes more of the string handling in your favorite language and seeing some kind of logic in terms of whether you can make if then as while for those kind of decisions in your code so that is where the problem basically boils down to i would say because obviously they're not asking you to see whether you can do the multiply or addition so anyway before i go tangential on my discourse let me just read the problem the given two non-negative integers num1 the given two non-negative integers num1 the given two non-negative integers num1 and num2 represented as strings return the product of num1 and num2 also represented as a string and as you as i already said is saying do not use any kind of library function to basically convert inputs to integer and then examples he gives you is one uh num one is two is string two num two is string three and obviously the output is six and similarly for one two three and four five six actually string one two three and a string four five six so let's uh let's do this problem and we will use c because that's where all the fun part is messing around with the string so like what we did in case of added strings what we do is first thing we do is we try to find out the length of these strings so rather point to the last digit of each of them so that means we would have something known as num1 htr ln minus 1 then we have j equal to str line num2 minus 1 and so now we are indexing into the last digit of each of our inputs now what do we need in this case it's not just addition of two strings so this actually multiply and as you know the multiply is like let's do a multiply of uh one two three and four five six one two three let us say you're multiplying four five six by one two three what do you get um so basically if you remember your math from your elementary school you would have what is known as eight three times six is eighteen and you get a carry of one and then 3 times 5 is 15 you get a carry of 1 from the previous time 16 so that is 6. again you have a carry of 1 and 3 times 4 is 12 and you have to carry your 1 so you get 13 so basically that is your string that's going to be number one and then you have let us say so what would happen is you would have zero as the for the digit two you will start with zero as the carry because the tens digit for that is going to be starting from the first i would say once it is it will start from zero for that because it's uh it said place is tense digit is actually one and this is tens is equal to zero so anyway you have to start with zero i think you remember already and two times six is twelve so that is two and then you have you get one carry of one so two times five is ten plus carrier one's one you get one and now you still have a carry of one and then you get nine two times four eight and the previous carry of nine so you get this and then you have one more which is this time and now you start with one so 1 times 6 is 6 that's easy then 1 times 5 is 5 and then 1 times 4 is 4. so this sorry this is going to be more like you know i should have probably created more space here so now that we can align them so there you go and now we just have to add these and this will be your final result so that is 8 here right this is 8 and this is again 8. and so you got and then you have six three and one and six so that is ten so that is zero and then you carry a one and 1 is 2 9 11 plus 5 is 16 that's your 16 and carry your one and then you have five so that's going to be a final result so we will follow the same thing basically that's what is going on in the code but it will all be kind of done in a in in a programmatic way so let's uh let's do that so now uh so what do you expect what do you think we need to have we know how to add strings numbers represented as strings so that means in this case instead of adding two strings we'll have to probably add as many of these strings as possible so we would need a way to store these strings that we will add so for that we can have a variable which is a result string let's just call it result strings and this result is strings this will start out as null and as we get more and more of these result strings we will be filling up this array so that's this is basically an array of strings and this is c is the way of doing it because it's basically a pointer to uh this anytime you have an interstar it can potentially become an array and now in this case there's an array of characters which is a string so this is a array of string so now we will have a variable known as wrestling which we would use to kind of keep track of this array of strings and then let's have one more thing we need to have a variable place 10 i call it tenths place but i wanted to have 10 first but apparently it doesn't like 10 in the beginning so place 10 i'm going to call it zero maybe a more suitable name for that this variable could have been 10th place maybe yeah let's call it 10 tenths so equal to zero so that's good now one other thing we may want to take care of and i would come to that later but let's not go right now let's start thinking in a linear in a way in which we would start to solve this problem so as you can see while so let's start now so what's our approach is going to be for each digit in num2 so for each digit in num2 how do we say that while j greater than equal to zero right now we are going to create these strings that we saw this 13th example of this intermediate string so we would have to have a variable to store those and we would call and start out by initializing it to null then we would have another variable to keep track of how big of that s is then we need a variable to have a carry obviously that i can see that you guys can all easily relate to that you will need to carry and now in str land so now we need a variable which is known as i okay here now the thing is this we every time for each digit in num2 we will have to go over all the digits in num1 so actually maybe uh having this eye cold here is probably not even needed but we'll take a look at that later maybe that can be optimized away or we can basically remove that later but right now we need a strlen num1 minus 1 and then so now again we repeat our process this is saying for each digit in num1 so we would carry over this loop will continue this loop as long as we have digits at num1 so we should call it actually for each digit in number and so now let's do that okay so uh how are we going to do this we are going to do that by having a variable known as a which would be num1 i and we can do the subtraction so that our loop doesn't run forever so that's our a and then in b equal to num2 this thing is fixed at this point because we are keeping the digit in what is this trick about dividing it with zero because that's actually a converting ascii representation of that digit into or the number into the actual number so that is a and b and now in the result of this we should say b times a plus carry right now uh now we got our you could say that we are almost ready to have our first uh digit or the number and we need to basically store that so we need to now do a look at some kind of memory education which is on s and we would say that is i just wanted to make it more clear so that's why i'm saying size of cal it's not it's actually needed size of care is always one so times plus length now all we need to do is we need to say s len minus 1 equal to and that is your plus so that's where we have our um first digit is stored so we are start building as now what do we need to make sure that the carry is suitably taken care of so care equal to basically that's your imagine if you added like for example multiplied three times eight you got 18 here result will be 18 and then you basically got your eight out and your one is carry so that's all good and at the end of it so once we are done with all the digits for each uh in num1 then we say if carry is still set if so we just cut and paste our boilerplate code here except that instead of storing the rest mode 10 will actually be storing carry so that is let's take this and we can basically take that out the benefits of cut and paste but instead of this you would have to have it carry okay so i think we are done with s what one of these strings out of those intermediate strings you could say now what is the problem there as you can see that we are storing them uh in a so for example this 1368 it will actually be stored as eight six three one so how do we go back to thirteen sixty eight we'll have to do a reverse so it's very easy to write a boilerplate reverse code we all have done it many times so just we will implement this function later so here we have a reverse s now what is the issue before we go back to our this outer while loop we have to appreciate that this might be true for the first resultant string but the next time we're on we'll have to have zero at the tenth place we have to keep adding these zeros so next thing we need to do is we have to have for each tenth place value we have to add zero so k less than you can say 10 place k plus okay so again we are going to keep adding more stuff to our resultant string depending upon the tens place and what we need to do is we are not done yet by the way we have to have s we do actually have to store that zero so far we have only allocated the place for it so that's where your zero has come now before we move on we have to make sure that the tenths place is actually incremented so that the next time around it has the correct value now we are almost done for with creating our string generic intermediate string but there's a problem we haven't null terminated and that can be done very easily by sticking in a null character and then we would be done so that is pretty much you could say there you go so that's where your one of the intermediate distance is done now how do we go about storing this in the result strings that can be done very easily we already know the tricks now how to keep doing this real logs and right so that is your now this time we do have to have a size of car star and make sense because that's not one byte it could be four byte pointer it could be eight byte pointer depending upon your machine so times plus rest length so here we have wrestling okay so now all we need to do is basically stick that s into here there you go and then we do a j minus b because we do want to come out of our outer while loop so let's see if that seems to make sense so let us see so we started with j while j greater than equal to zero should have been i would suppose because otherwise you will miss one of the digits so this is looking good but what is the problem we have all these result strings but we need to actually add them to actually have a real multiplication result so then we would suppose that we can write a function which is add a string and which returns a carry star this is the final result so resultant strings and then wrestling is the length of our array of strings so i think that's what we need to do but water is remaining first thing i can see we have to implement our boilerplate reverse function this is very easy but what is not easy is going to be how to add these strings so let's implement the boilerplate reverse function and that's for ours us c programmers is a kind of a after having done it quite many times it becomes very kind of it comes naturally to you so basically it's a very well known trick you start by pointing to the in the beginning you have two indexes and this is one is pointing to the beginning one is pointing to the end and then all you're doing is going in a for loop which is initialization is already done you basically increment one and decrement the other until they meet in the middle and you're basically pretty much done okay s i equal to s c and then s j equal to s i sorry time that's your reverse function but we have to implement our big function here which is add strings and how do we go about implementing that is going to be the real challenging thing or left in this program so as we know when we did add strings for two where two strings number and num2 uh in this case we have to kind of have a generalization of that function and be able to add strings which are more than one for example in this case there were three intermediate strings so okay so how do we do that let's implement that so this function signature is going to be it will return a k step which is the multiplica the result of the multiplication and it would take uh a array of strings so that's here okay so it will take array of strings now we can have a variable on the stack which we would okay let's call this outline which is the output length of this s that we would be returning we need a carry obviously because we are adding things here we are adding digits which might result in a carry now let's have it because this time we don't have a very easy way to saying hey strlan on num1 and num2 because you can have any number of nums here so then we need a array and we need actually an array of length of the string so this is going to be dynamically allocated so this is let's do an allocation right here and this is size of int because we need four bytes and then lan and then the lan was the land that you got passed in as an argument for this array of questions so because as many area as many strings as there are in rest is as that many elements we need in our lens array for the length of each of those strings okay so let's assign the values to this by going over our input array and all right so now we have okay so here we are um so that's where we will get the you could say that initiative str land storing is actually storing the last index of that is string so that's because we would when we start adding we start heading from that digit onward so now um the last is it yeah because you know if you have strlan or one of the strings is six then the indices go from zero to five so that's why you need the lens eye as the uh pointing to the last digit in that string now you see what is the next thing we can do we need to do our actual addition here and therefore that as long as we have any only time we stop addition is when the lens array have all negative values as long as we have digits to add we continue to add so we would need a something like this while something like legs while not check all negative values and right we continue to go we will implement this function later but right now we are saying hey it's like what we had in case of two when we had only two strings to add we used to do something like this we remember we did something like while i greater than equal to zero imagine i and j was were the lengths of this string or we used to say or j greater than equal to zero please go and take a look at the problem four one five which i think i did last time this is add string you see that how we used to do that now we are kind of generalizing it because we don't have the luxury of only dealing with two we may have to add as many strings as are given to us so that's why we are saying why not check all negative values so as long as these are you there is a one positive value somewhere that means we have work to do um and now we would have a generalization of the earlier case again where say and then here we would say for loop and then this is where you basically accumulate your you're doing one of these so basically this is like think in your mind that we are doing one of these like eight zero or maybe six one three with the carry added and things like that so you here we say sum equal to sum plus i mean this of course we being very smart c language programmers we can do something like this some sum plus equal to right and then what we do is this we say if lengths i is greater than equal to 0 because see if that particular place in this string is already finished i mean it doesn't even have that particular place in the string we do not have to worry about adding that one right so we have to skip that one in that case we can simply add 0 how do we do that we say greater than equal to 0 we use c is this operator that you guys have all heard of and so this is again rest i and now we are actually taking one of those strings so here now think about it that we have lens i and then minus here and minus we basically get the digit because we need the digit to add so this would be a result if there's anything there otherwise we just return zero when we come out of this for loop we are in amazing shares only thing need to do for us is to add the carry now we have our final sum and we would do the actual work of getting the digits that we need and that would be let's do a yellow on s because we need this space to store this digit and then we would say to now some more 10 that gives us the actual digit to store plus 0 to basically convert that into ascii and that is a store and the carry is basically this and this is your integer division never forget that what does a dj division do so if you have something like 15 by 10 what you get 1 not 1.5 integer division discards not 1.5 integer division discards not 1.5 integer division discards the decimal and anything after that so that is your i would say pretty much your actual digital store now once we are done with adding the all the digits in all the strings what is left over so imagine we have a leftover carry so we'll have to store that one as well right so that is here really unlock and then here we have again this is a very standard tree we have been doing it for a long time now i would say and just store the carry digit okay this could also have been done as carry plus zero but i'm thinking k is always one so we might as well just do this instead of you know instead of doing something like carry plus this in any case so i guess both of them should be all right now only thing remaining for us to do is do a reverse on this and luckily our reverse function that we wrote before is going to be useful and here we are and now before we say that we have achieved our goal we'll have to take any null character in the grand old style of c programming language because without that the string is not actually complete the string is only complete if it is not terminated that's the definition of the c string if you don't know that you're probably at the wrong place right now so then we just return s now do you think that's all we need to do our work is done can we start jumping like code monkeys no you cannot so we'll have to do uh things like what is remaining here i can see one thing which is we haven't implemented this it shouldn't be a big deal but the program will not compile without that so let's do that and we would not use a rule or anything we'll simply use uh the c's convention of anything that is one or anything that is non-zero is true one or anything that is non-zero is true one or anything that is non-zero is true and zero is false so we say in check all negative values and this is a very standard trick anytime you want to pass an array to a function in c you also have to pass its length because the function the quad function doesn't know how much how big your array is now let's start with this is a very easy step i would say to do you start with a flag like all negative values equal to one so let's assume that the array doesn't have any positive values or zero or positive values all the values are negative let's start with that flag then what we would do is we'll walk the array and when we see that and this condition is not satisfied we would just break out and return false so all we need to do is have a check saying if a i is greater than or equal to zero then we know that we can set all negative values to zero false and then we can break order we don't need to go any further so basically all we need to do in the end of the function before the end of the function is just return this flag all negative values return all negative values there you go so with that let's see if our program at least compiles and we haven't messed anything up and it was kind of a little big program but that should not be a good problem let's try it okay so he's saying there's a problem here the problem he said is there's no n i can see that okay all right multiply is saying you have a problem 94 let's see what we did wrong at line 94 he's saying you have tens place expected is saying is expected in did we use the correct variable here 10 tens please looks good i don't see a problem now for into okay i see there's a problem here k equal to zero that was easy okay now he is saying we have a problem we have i think okay that was easy as well so far we have been getting lucky we are only getting into typos okay that was easy as well and see you see the python what happens when you've been doing programming language like python you tend to start like forgetting your statement termination semicolon so wow so that's absolutely amazing that it actually worked fine so i guess let's take some simple test cases that he has given us so that is let's say four five six cool so that's working um absolutely great now what do we need to do suppose take let's take some more simplification very simple basic one that we had first time around two and three so two and three let's see what happens now all right so that works as well so we'll try to do a submit and see if it passes all the test cases we get lucky we are done and we can celebrate our victory today okay so there is a issue is saying address sanitizer segmentation violation what is the problem here have we messed something up um let's see um boy is this problem when we had we just saw this one two three four five six when we gave here it was working fine right so let's do it here one two three four five six it was working fine i wonder what happened when it went as part of the complete test case so in any case so uh one other problem let's try to submit again i want to write that field over there because it is working fine segmentation violation and address and it has a deadly signal have we messed something up what do you guys think i was thinking everything is working fine but apparently that is not the case what about amazing behave something like this one two three multiplied by zero i think let's see that works so we have a wrong answer and we can see why because even though the output is actually correct but you see he doesn't expect you to write so many zeros when you can write only one and that probably we can take care by putting a case and why are we going through all this big hump of code when we can simply do what is known as uh what we should do is say if we should do a stream comparison if any of these num1 or num2 is zero so if strcmp num1 is it's as is basically zero then or compare or a string basically this is c of saying is num to zero or right having done that we said return zero all right so that should take care of this particular case i would say okay so that is accepted as well now only thing we need to see is that why we are getting a address sanitizer issue maybe we may have to declare it here also so let's see okay and one two three four five six we still have that problem but if you give the same test case here it's fine how is it possible i have absolutely no idea what's going on this is some vagary of the okay so i suppose that's cannot be an issue so check all negative values if we screw something up let's go through the whole code again we see that reverse is working fine i plus j minus that should be okay check all negative values this looks good as well and written all negative okay so that looks good as well now let's say add strings did we make something up here so lens equal to moloch size of in that's not okay size of n times length and i less than lan i plus lengths i equal str one that sounds good as well now while um this while not check all negative values you see any issues here i don't see any issues here okay point i equal to zero i less than i plus sum plus equal to length i greater than equal to zero question mark plus i length i minus zero okay or just zero sum equal to sum plus carry okay somewhat 10 plus 0 they can equal to sum by 10 okay now if carry then we save s equal to real log s plus outline and as outline minus 1 equal to 1 looking pretty good and then we did a reverse on s outline okay and then we said as real log has basically stick in a null character um so that is looking good as well as already okay now let's say we mess something up in multiply so we said j equal to num 2 minus 1 the distance equal to null and then we said uh tens place we initialize to okay so we haven't initialized this wrestling maybe that could have been an issue i see what was going on i think that was the problem because you see if you don't then what would have happened let me ask you one question here is plus vast land oh my god that was a real problem i see a point okay i think now it should work there you go so there we have our glorified success and we can hear the sigh of relief at this beautiful problem of multiplying two strings which are actually numbers represented as strings and it basically works so as you saw that this little bit of problems could be these little issues can come to basically bite as we saw that we wasted like a couple of minutes and figuring out why we were getting a problem here and when we do the summit but it was passing for some weird reason it was passing if we run code like for individual test cases but you see if wrestling is not initialized what would happen when is the first time the wrestling used wrestling was used here amazing you are basically doing real lock but instead of you have a wrong wrestling value basically that's what would happen and so you don't know how big of the area of the strings is and the memory she was here and it was really a problem and most likely imagine your wrestling is even like you don't know what value it is you might have access some memory somewhere in resultant strength and that's why we were having an issue in any case long story short it's working fine now and um it was in retrospect i would say it was kind of little bit more involved than i thought because um but it's a very good exercise if you want to play with the strings and see and memorial locations and things like that because ultimately think about it you just this is the generalization of the add strings 415 where instead of adding you're multiplying and for that now you'll have bunch of those intermediate strings that you have to add so you can use previous knowledge and so you have helper function add strings here which calls two other helper functions to check all negative values so you get to also play with arrays and see how our things how to basically return something when some value in a header is not to your liking so it's all looking good i wish you guys all the best and i hope to see you in the next interesting problem that we would solve so do not forget to subscribe to the channel i know it sounds like a very cliche nowadays whichever program i see people say hey subscribe to my channel well i leave it to you if you find it's useful please feel free to subscribe and i would i wish you all the best in your coding journey and in interview appearances and until next time adios hasta manana
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
623
welcome to march's lego challenge today's problem is add one row to tree given the root of a binary tree then value v and depth d you need to add a row of nodes with value v at the given depth d the root node is at depth one now the adding rule is given a positive integer depth d for each not null tree nodes in depth d minus one create two tree nodes with value v as n's left subtree and right subtree root now the n's original left subtree should now be the left subtree of the new left subtree root and the original right subtree should be the right subtree of the new right subtree root all right so if we had this binary tree here and we had a depth of two and a value of one we're going to add ones here at the two and six and now the original left subtree and right subtree are going to be the left subtree of that one and right subtree of that one so normally with these problems i like to do that first search you could do breadth first search you can even use a stack if you want but let's the trick to this question is to think about the different scenarios and there's really three the first scenario is that there is no node so we don't do anything there which we turn it immediately um the second is there is it's at depth one and if it's at depth one that gets a little tricky because what we'll have to do is make the root this new value and the original root is now going to be the left subtree of that otherwise everything else all we care about is we can keep track of the depth and as soon as that depth is d minus one like say for this example here we'll say at two right one two what we'll do is uh take the left subtree here create a new one of one and store that original left subtree to make that the left side and we'll do the same with right after that we can just return the original node or the original root because it's now restructured okay so let's see what i'll do is write a depth first search and i'm going to pass in the node the depth and i'll pass into d i'm not sure if i need to do that but i'm just going to do it anyway so the first thing is if not node we just return none right so that's that now else if the d equals 1 that means we're going to have to create some sort of temp root so we'll make this the tree node and what we'll do is create a value and make the left equal to the original node and now we just return this as the new root right now otherwise if depth equals e minus one we're at the depth right before the level that we want to add these new tree nodes to what will i do then is we'll take the node left and make that equal to tree node value and we'll make the left equal to the node.left and this works the node.left and this works the node.left and this works because this value gets stored temporarily and now it's going to get stored here and it's going to get replaced with this new tree node same thing here do this make the right equal to node.write make the right equal to node.write make the right equal to node.write from here we should just return the node and otherwise we're just going to call our first search with node.left first search with node.left first search with node.left add one to the depth and passing the original d and we'll do the same thing on the right here so now we need to call this function and return whatever returns say passing the route start with the depth of one and the d that's given to us all right so let's make sure this works oops i misspelled into tree node okay so that looks like it's working and we'll submit it so we took care of all the edge cases and accepted great so this is oven time complexity we do use ofn space as well because of this recursive stack otherwise using breadth first search could be a little bit faster in terms of space complexity but i always prefer that for search it's just more intuitive for me so hope that helps thanks for watching my channel and remember do not trust me i know nothing
Add One Row to Tree
add-one-row-to-tree
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`. Note that the `root` node is at depth `1`. The adding rule is: * Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with value `val` as `cur`'s left subtree root and right subtree root. * `cur`'s original left subtree should be the left subtree of the new left subtree root. * `cur`'s original right subtree should be the right subtree of the new right subtree root. * If `depth == 1` that means there is no depth `depth - 1` at all, then create a tree node with value `val` as the new root of the whole original tree, and the original tree is the new root's left subtree. **Example 1:** **Input:** root = \[4,2,6,3,1,5\], val = 1, depth = 2 **Output:** \[4,1,1,2,null,null,6,3,1,5\] **Example 2:** **Input:** root = \[4,2,null,3,1\], val = 1, depth = 3 **Output:** \[4,2,null,1,1,3,null,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * The depth of the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100` * `-105 <= val <= 105` * `1 <= depth <= the depth of tree + 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
142
hi everyone today we are going to solve the leaderboard question link to this circle too so a few months ago I actually I solved the linked list Circle one so I put the link in the description below so today so you are given a head of a link to this return the node where the circle begins if there's no Circle or return no there is a circle in link to this if there is some node in the list that can be reached Again by continuously following the next pointer internally post is used to denote the index of the node that tells the next pointer is connected to zero indexed it is -1 if there is no Circle is -1 if there is no Circle is -1 if there is no Circle note that both is not passed as a parameter so do not modify the increase so let's see the example so you are given three to zero minus four and output is scale connected to Node 1 index so we should return this node as an output I think and uh yeah actually this question is more like a mathematics exercise rather than like an algorithm so let me explain how to solve this question okay so let me explain with this example three two zero four and uh we have a circle from like four to two and the first of all um let's see how we can confirm we have like a circle actually this is a linked list Circle one exact same as adding to this link to this circle one so we are prepared to have two pointers one is a fast pointer and the other is a throw pointer and every time fast pointer moved twice and the zero pointer moved ones so let's begin so now first point I move twice so one two here and then 0. move once here then again first point I move twice one and the circle two here once here and then first point our move twice here and then 0.1s here and then uh two pointer meet 0.1s here and then uh two pointer meet 0.1s here and then uh two pointer meet at node four so in that case uh we definitely show this link to this has Circle so that's how we confirmed that we have a circle in the link to this okay so it's time for mathematics and before that um so I put a b c so between head and uh Circle start node so let's call the no start node so between head and the start node this distance we call a distance so between start node and the last node uh this distance so we call B distance and between last note to start node we call this distance C distance okay and let's think about the fast distance for first pointer and the zero pointer and the throw pointer is moving like a from head to last here so that means so this stands for 0.2 should be a this stands for 0.2 should be a this stands for 0.2 should be a Plus B right for first pointer so first point I move twice every time and then go through the circle and then meet the last meet the zero pointer at rest index that means a Plus B Plus C plus b right and then remember the throw pointer move ones and the first point I move twice that means first point uh moving twice compared with zero pointer so if we multiply 2 for distance as slow pointer distance that means this these two distance are equal and we need to calculate this simple um formula so that means so 2A plus 2B equal ABCD and then so let's uh let's correct a on the left side so move a on to left side that means a equal so we move 2B to right side that means um we remove 2B so only C left on the right side so we get the a equal C so what does this answer mean so we make sure distance a and the distance C are equal and then now first pointer and the zero pointer is at last index so okay uh in this case we can choose one of them so which is first pointer so first point the e so we reset the first pointer and the um start from head so first pointer is now here and there's a 0. stay at last index so we know that a distance a is equal to distance C so in that case if we move uh first pointer through pointer once at the same time in some point first pointer and the zero pointer definitely meet um I got a start point so that is the answer node we need to find right so in that case first point term once and each node two and the third point is now last index so if move once so slow Point goes through the circle and the reach two now first point that's all going to meet at node two that means uh definitely uh this node is like a start node so we should return this node I mean first was first no first pointer or zero pointer yeah that is a basic idea to solve this question so with that being said let's get it get into the code okay so let's write Circle first of all if not had just return now and then after that um prepare two pointer plus pointer initialized with head and the zero pointer also initialized with head and start looping so while two nothing that is like an infinity loop if not first pointer or not first Total next in that case uh we don't have a circle so just return now if not the case I put it first point uh to fast next and the zero point uh equals rho dot next and after that if first point meet zero pointer in the case we break the while loop so after that we know that um so a distance a and the distance C are equal so I choose fast pointer and uh um update the first pointer with head after that um why fast pointer is not zero pointer so we move both two pointers until two pointer meet at some point so first point I equal fast dot next and the zero pointer equals row dot next and then after that the term first pointer so yeah that's it let me submit it yeah looks good um time complexity of this solution should be a order of n and the space complexity um I think we don't use the extra memory a data structure so I think of one so let me summarize step by step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of link to this circle 2 Step 1 initialize the first pointer and the zero pointer with head Step 2 start looping step one if first pointer is no or fast dot next is no return no step to update first point now is first dot next and Dot next and I mean move twice and as the zero pointer with slow dot next mode once step 3 if two point dots meet each other then break the loop step 3 update first pointer with head step 4 move fast pointer and 0.0 one by step 4 move fast pointer and 0.0 one by step 4 move fast pointer and 0.0 one by one and then when the two point meet somewhere that is a node we need to find yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
1,010
Hello Scientific Forces Subscribe My Channel Subscribe subscribe and subscribe the Channel Please subscribe and Subscribe Provident Fund Civil Lines Repair Will Be Created with Live More than 150 Shares Subscribe and Must Subscribe Now to Subscribe fluid This page is directly looted Subscribe The Channel Please subscribe and subscirbe subscribe yeh hadasa formulaic and without which is nothing but in the two subscribe value subscribe video channel subscribe like this voice mail lootti are angry man app for every evening i will have a reality show the number of kar do me novel take care For the balance between one in today no two dooba values ​​into to par a jhal dooba values ​​into to par a jhal dooba values ​​into to par a jhal ki looteron dahej let's create a the function aur sunao baby news photo which alarms inquisitives plate another one pan virendra isko hai pimple hai hello friends good night result date committee is Code that Shergarh Submitted Successfully Time Complexity of Subscribe to that
Pairs of Songs With Total Durations Divisible by 60
powerful-integers
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Hash Table,Math
Medium
null
931
Hi gas welcome and welcome back to my channel today we are going to discuss date d problem is minimum falling parts we so in this problem will be given a matrix and see we have to return d minimum sum of other falling path through matrix what is the Following path Falling path starts other element in d first row so it can start from this element or this element and see you choose d element which is in d next row dat is here directly below and diagonally left or right ok diagonally left And right so for example if we are starting from this van so we can diagnostic ok and we can go to Delhi left and right ok element from position date is this position is your call so d next position so this is what Falling Party And They Have To Find The Minimum Sum Of Following Parts C Can Start From Any Of D Element Which Is In D First Row And C Have To Find The Minimum Sum Of Other Falling Bath Okay Right Matter C Have D This Is In D Last Row Right this is d last basically if see you have reached every what different positions see can see have options from every from d se column previous row and previous row next vijayvar nav let se let's see no d what see need you find d minimum falling path Minimum Falling Path Falling Minimum Falling Fast Til Her End See No D Minimum Falling Part Minimum Cost Which End Five End Its Minimum Cost You Reach The Seven Rich D Seven Will Be What 7 Plus What Ever Cost It Aate Plus Minimum Of This X Because See can reach this seven from six also and See can reach this seven from five also so minimum cost to reach 7 right 7 plus so every see What happens this is a problem right and it depends on previous problems also every see you have options From Her Or They Can Reach From Her Okay This One Also 8412 Minimum But For Tha They Have So No Minimum Same Her Are - 1 - 1 Order You Find The Minimum Same Her Because Obviously Want Minimum Right So Minimum Path Whatever Is Minimum Take minimum of dam and see will add this current ok See will add current cost also so current cost is let from matrix of RC ending at 7 some thing every ok Suno What will d minimum path if see Reach Five From Tu Kos Will Be What Tu Plus Five Seventh Plus Six Will Be Come Vote Ok Nine Let's Talk About Biscuit S Out Of Range If It Bellows Equal To 3 Or Greater Than Three Date Will Be Your Base Case In Date Case Just Return What Are Taking Minimum Her So Just Return In Maths Because Obviously Impacts Will Never It Will Not Hinder Anything Because Are You Taking Minimum Her So That Also Your Will Be There Or Also There Will Be When They Reach Her When They Are At 2 What Will be the minimum falling path year because it first row only right and C are starting from only tu in date case just most basically D column is in the range of the matrix and greater then equal tu zero in date simply return whatever is D value every return matrix OK this is one base case and this is already computer D value for this row and column D simply returns C will store D result of like first will add D current value because current value C will add right current value add And give D minimum of these three recessive calls 3 record OK first call second call and third end also discuss this whole process C will do for H of the element which is in the last row because C does not know where D minimum Sam Falling Path Will And It Jump And Her Also Will Check All DC Okay So Her C Have Just Loop Which Will Pickup D Pick Up Van By Van All D Last Element Of D Matrix Like Last Row Elements and Answer A Second Approach Both Approaches Will Work It's Not Like The First One Will Not Work But Like Date Is Taking Extra Space It Will Only Work If You Are All Out To Change The Matrix So This Matrix Is Given Right If You Are Only Allowed To Change It Give only date on every day will work so what c will do write in state of string d results in dp and all date c will be just take result c can like for this element c can else h from every or every d element write So what will do basically see will run loop from second road every and see will just populate values ​​de min of values ​​like for every for these values ​​de min of values ​​like for every for these values ​​de min of values ​​like for every for these six see can reach it from this you or see can digital from this van so which is beneficial minimum of you And van six plus right previous row next column value and d middle value just above it see will just take minimum of date and see will store retainer see will just basically update are matrix elements seven so this will become seven okay then van see can us from C or C can teacher from tu for this five C will go in else date is C take left middle and right so minimum of 21 and 3 and C will add 5 minutes so 5 + 21 and 3 and C will add 5 minutes so 5 + 21 and 3 and C will add 5 minutes so 5 + minimum of this which is one so six C will Store every in place of five ok then they go every what it will be 4 plus minimum of so this is d last column rate last column so for last column only they will take the above one and d van which is every d loss last column take D left diagonal value and D middle value so it will be minimum of 1 3 so it will be four plus one five OK similarly will go for go to the next row and for the seven will calculate 7 plus minimum of 6 and 7 so 6 And 7 so what is this minimum six so it will come 13 matrix changing is allowed you can use this app just going to care d last checking what is this d minimum element and date see will return this time complex let me know in d comments if you Found d video helpfull please like it subscribe tu my channel and elsa in d experience thank you
Minimum Falling Path Sum
maximum-frequency-stack
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. **Example 1:** **Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\] **Output:** 13 **Explanation:** There are two falling paths with a minimum sum as shown. **Example 2:** **Input:** matrix = \[\[-19,57\],\[-40,-5\]\] **Output:** -59 **Explanation:** The falling path with a minimum sum is shown. **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 100` * `-100 <= matrix[i][j] <= 100`
null
Hash Table,Stack,Design,Ordered Set
Hard
null
231
hey welcome to this video we're going to be doing Leko prom 231 power of two so give it an integer write a function to determine if a if it is a power of two so one is a power of two because two to the power of zero is equal to one so it's 16 right because you do 2 to the power of 4 you get 16 back but there's no way you can get to 218 if you do 2 to the power of a whole number and so there's a lot of ways to go about solving this one way I can think of is we create an array of valid numbers that are powers of two but I want to offer something a bit simpler and it's easier if I show it rather than explain it so I'll do my code editor and if you liked this video be sure to like comment and subscribe and hit that little belt next to the subscribe button so you get you're notified of any new videos I release with that said let's get started so I'll create a variable called I and set to be equal to 1 because 1 is a valid power of 2 and we're gonna make a valid powers of 2 I'll say while I is less than the input number right n then we're going to multiply by 2 so I x equals 2 and then almost a return I is equal to the input number so by the time this while loop finishes I will be either equal to the input number or greater than it and I will always be a valid number that's a power of 2 so that's why I turn return that I is equal to n and if I copy this code paste it on to leap code let's make sure it passes their tests and it does great so what is the power of 2 complexity analysis time complexity is o of log n if our input doubles like the input number then our while loop runs just one more time and the space complexity is o of 1 all right that concludes this video
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
384
hey everybody this is larry this is me going with day 20 of the july lego day challenge hit the like button to subscribe and join me on discord let me know what you think about today's prom i am in l.a right now so things are a i am in l.a right now so things are a i am in l.a right now so things are a little bit messy things a little bit weird my channel is a little weird hope that's okay today's problem is shuffle and away and i usually stop these lives always a little bit awkward or slow just fast forward to whatever you need to do um okay so for this one let's see we're given a little reset in terms of random shoveling of the array okay so this is actually um a kind of a trivial problem in a way because the short answer here is that what you want to do if you don't know how to do this one it's something called the fishery yates album um i and it is just a name but the idea is that um the one thing that you don't want to do is just take and i think this is a common mistake is to take the numbers away and then take any two elements and then shuffle it randomly right because that you if you can think about it um every time you do a shuffle it makes it changes two elements so then that means that it only returns two to the k elements or possible configuration because every time you pick two elements it gives you a new configuration of the two elements right um where for perfect distribution uh you want something that's k factorial or something or n factorial in this case so that's basically the idea here and i'm gonna and i actually do remember this off this algorithm of my head because it's a little bit easy i think a couple of ways to write it um i might not i don't think i necessarily write it in the original algorithm per se because sometimes i mix up whether you do it from the end or the back but as long as you choose from one over n in the first iteration one over n minus one in the second iteration and so forth you should be okay so let's get started uh let's do let's yeah let's get started yeah i'm just looking at food api right now so let's just do self.number just to now so let's just do self.number just to now so let's just do self.number just to go to nums uh reset we just kind of return time numbs and here's shuffle i think this is just depending how you want to implement it because either you can uh let's see is this because either you can allocate extra space on extra shuffle or on the reset i think it doesn't really matter either way um i think you need to do this uh in a particular way what is that hint um yeah what that's a little bit awkward but maybe that's fine i don't know what that means what a weird hint okay so yeah let's just do fischer yates and i think if you have i think just read we don't want the algorithm to be honest but the way that i think about it and the way that i am able to remember it is just like i said so the first iteration will take one over n and then the second will be one over m uh and minus n minus one and so forth dot so then now every distribution would be one over n factorial in that way right and that is you know a perfect shuffle um yeah or perfect shoveling maybe so let's get started so let's just say that answer is equal to do the solution okay this isn't really a hint though this is more like and that's what i'm actually doing anyway i was checking the hand because i'm curious whether there's another way of doing it um because the official yates is pretty well known and fit pretty optimal unless i missed i type booted somewhere yates fish no okay yeah so and actually the key thing about this one is that you can actually do this in place but um so i'm gonna do it kind of in place because we have to reset we'll have to kind of copy anyway so maybe i wouldn't do it that way instead but that is a key point of it so you don't actually have to allocate space per se but i do it on the shuffle maybe i'll change it up actually fine um so yeah that's something that this is let's do no because okay no because okay no because okay because i think the hint tells us to do this so yeah so let's make a copy but then now we go for anything online for index and range sub um and so you can do it in whichever way indexing your uh that you're familiar with or comfortable with i do it from the end so you can do ends at index minus one is equal to um a random number from zero to index right how do i do random in five forget because it doesn't really come up that often see i'm just googling really quick i mean okay so this random dot went in from zero to index i think i'm just checking whether this is inclusive or not this seems to be inclusive so they should be okay so actually let's say um this is not quite right that's not but yeah so all index for random index so then now we have answer of our index and we just swap these two right and the idea here is that you know you have a bucket of n items in the beginning on the first try any of the n numbers could be picked and then on the second try any of the one minus one over n minus one index can be packed and so forth and all of them might equal right so that's basically the idea here uh i think this should be good i mean you can't expect the answers to you go to expected answer because this is a randomized code so you know it's just random right so yeah so this is accepted like i said this is fishy gates um you can see that this is linear time so yeah and i guess linear space because we have to keep track of the original uh array and yeah so and we copy it every time i think that's probably more reasonable maybe depending how you want to think about the api and as long as you support api it's probably fine um yeah um that's all i have for this one hit the like button subscribe on drummer and discord hope you know learn about this one and stuff this is this one is very easy to get wrong to be honest and this is one of those things that looks easy because it's five lines of code um but people have failed many times doing these five lines of code so definitely make sure you practice it or make sure you understand the concept behind it then you can um even if you make a mistake you can go back and debug it right because if you don't again it's a little bit trickier um that's all i have i'll see you later stay cool stay good it's a good mental health i'll see you later bye and i have a doggie here doggy you want to come hang out uh juno okay juno does not want to come so come say hi to the camera okay you get a little juno okay bye-bye
Shuffle an Array
shuffle-an-array
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the integer array `nums`. * `int[] reset()` Resets the array to its original configuration and returns it. * `int[] shuffle()` Returns a random shuffling of the array. **Example 1:** **Input** \[ "Solution ", "shuffle ", "reset ", "shuffle "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\]\] **Output** \[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result. // Any permutation of \[1,2,3\] must be equally likely to be returned. // Example: return \[3, 1, 2\] solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\] solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\] **Constraints:** * `1 <= nums.length <= 50` * `-106 <= nums[i] <= 106` * All the elements of `nums` are **unique**. * At most `104` calls **in total** will be made to `reset` and `shuffle`.
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
Array,Math,Randomized
Medium
null
155
hi friends welcome back today we are going to solve one amazon facebook coding interview question it's only code 155 mean stack so as you can see from live dislike ratio this is very likable problem and quite important problem also if you are preparing for any coding rounds of interviews so make sure you watch this video until end so you will completely understand this uh problem uh i am going to explain you the logic java implementation along with example so you can completely understand the problem uh so we'll go through the problem statement we'll understand this problem uh in today's session and will also implement the problem before we start looking into the details of this problem i want to mention that this channel is to help people in their coding and java interviews on this channel you will find lots of helpful videos that can help you in your coding and java interview preparation for example there are more than 400 different varieties of problem solved and explained on this channel those are essentially coding questions previously asked by big tech companies that includes amazon apple microsoft yahoo netflix uber google and many others so if you are preparing for any coding rounds of interviews or java rounds of interviews this channel can definitely help you in your preparation so please subscribe to this channel now also whenever we solve any important coding problems we create videos on this channel so that we can discuss approaches logics and solutions to solve those problems so that others can also understand how to solve those problems uh java programming data structures and algorithms so make sure you click on the bell notification icon so you will get immediate notification as soon as we create new postings on this channel so let us start this important problem mean stack so design a stack that supports push pop top and retrieving the minimum element in constant time right so constant time means o1 right so that is important uh implement the mean stack class so mean stack is the initialization of stack object and push is we have to push the element into the stack that's fine and pop removes the element from the top of the stack that is fine top gets the top element of the stack that's fine and get mean retrieves the minimum element in the stack so this is uh something new that we are seeing right compared to other stack operations we already know other stack operations push pop um what gate mean is basically we always want to retrieve the minimum element that is in this stack actually present right so that is a new method so this is the example we will take a look at constraints so value can between minus 2 raise to 31 and 2 raise to 31 minus 1 inclusive right so that value that they are going to give us to push that can be in this range and the pop top gateway operations will always be called on non empty stack so we don't have to worry about whether the stack is empty or not right here um because they have already told us that and at most three into 10 raise to four calls will be made to push pop top and gate mean methods so 10 raise to 4 is basically 10 000 into 3 so 30 000 calls may be made right while they are testing our solution so we have to implement the solution in efficient way right otherwise it will not pass the test cases so uh to understand this problem uh in details we'll just go to the whiteboard where i can explain you like more details about what the problem is i created one example for us uh here so that we can discuss the problem so let's first understand with this example what the problem means right and then i will implement uh i'll explain you the logic how we can implement this problem right so mean stack ah means basically they are in this case they have given one two three four five push operations so first five push operations are there so we are going to push some value into the stack right so i hope everyone is familiar with a step concept stack so how stack works so uh if you don't know already right if you are a new java developer or if you don't know stack so what happens in the stack is whatever you push into the stack uh so basically it is lost in first out data structure right last in first out so how does it work so let's just discuss in general right so i push let's say 10 i push here right then 20 i push then 30 i push on 40 i push on through on the stack right so whenever i'm removing elements i'll get whatever i last pushed first right so i pushed last 40 so when i'm removing i'll get 40 first from this time when i am again removing i will get 30 when i'm again removing i'll get 20 and when i'm again removing i'll get 10 right so basically last in first out data structure right stack is like this basically correct so um it is something you can imagine if you are new developer then it is something like a container right let's see this is a container and you are putting some plates here right one plate is there then second then third plate and fourth plate right these are the plates so once you put plates like this then you cannot take this plate first right you have to first take this plate then you will take this plate out then you will remove this plate and then you will reach this reach to this step uh plate and you can remove this plate right so this is how the stack works basically right so now you are clear with how the stack works so now let's go to our problem now uh right so let's uh they have given us first we will understand what the problem is right then uh it will be clear to you so if we are given five push operations what values are we pushing so 4 2 1 10 and 40 sorry 10 and 20 right so let's push this values so four we push first then we push two right then we push to one uh we push 10 and we push 20 after that right so this is what values we have pushed right so now when we are actually calling a get min method right so we should get the minimum value that we have into this stack available right so what is the minimum value available one right so we should get one so this is what we are we have to return here right and when we are pop means we are removing the top element from the stack so this one we will remove so 20 will be gone basically right from the stack now when we call the top method it should return as the top element from the stack so 10 it should return so 10 it is returning it just returns 10 but it does not remove it basically right it's just returning that value but we are not removing that 10 right and when we again call gate min again we will in this four values that are available now into this stack what is the minimum value 1 so we want to return 1 correct so this is what the problem is so with this example now it is clear to you what the problem means stack is right so now we will understand how we can implement this problem right so let me just remove this so what we will do to implement this problem is again this is a stack and we will again use a stack actually to implement also we will use one stack right and how will our stack look like stack will actually hold two elements stack will hold actually two elements and how we will hold it we will create a stack of integer array right we will create an integer array so every element in the stack is integer array so how many elements will it hold in that integer array it will hold two elements correct it will hold two elements so what are those two elements the first element will be the number that we are pushing right for example if we are pushing four right if we are pushing four then the stack will hold like this right four it will hold and the number that we pushed and it will hold the minimum number that we have seen so far right so what is the minimum number we have seen so far four so this is what the stack will hold that's why we will use integer array here correct so now let's just modif let's just go through this example uh and i will show you how we'll just modify now our stack right so now we are actually let's say we are pushing here four we are pushing right so how it will be uh added into the stack four comma four right four comma four it will add four comma four now what is this first is the value and second is the minimum value that we have seen so far right so you got it right so this is the minimum value we have seen so far is 4 now when we um when we add next value 2 right next value we are adding is 2 into the stack so how it will look like 2 comma 2 right why it is 2 comma 2 because as of now we have seen the minimum value 2 right so it will just hold 2 here right after that when we add 1 it will create 1 comma 1 so 1 we have added and the minimum value we have seen so far is 1 right is 1 now when we add 10 right when we add 10 we will add 10 and 1 here right in this array why one because in these values we have seen minimum value one so far right in these four numbers we have seen one so far is the minimum value correct then we will add 20 we will push 20 unto this stack now 20 comma 1 right that this is what we will push and why so what does it mean that 20 is the value that we are pushing and 1 is the minimum value we have seen so far right so that's what we have pushed into the stack so if i just want to show you how it will look like internally so this is a sample right that this is how the values will look internally if i want to show you that right so this is what same values we are pushing 4 to 1 10 20 right so when you push 4 you will see minimum as 4 here when you push 2 minimum value is 2 when you push 1 minimum value is 1 so when you push 10 minimum value is one you have seen so far when you push 20 minimum value you have seen is one right so this is how internally our stack will look like basically correct if i show you so this first element is the actual number right that actual value that we are pushing for example 20 so 20 is the value that we are pushing actually right 10 is the value that we are pushing here correct so that's what it means and this first number one element is the minimum value we have seen so far here also this is the minimum value we have seen so far right so now you got the idea how the stack will how we will push the values here right and whenever we are pushing we will keep always track of what is the minimum value we have pushed we have seen so far right so uh more will be clear when i show you the code but now you got the idea so now let's say if i want to call the gate mean method right get mean method so i will already know using one variable what is the minimum value we have seen correct in these values so one is the minimum value so i can just return one there right as the answer in the gate mean method right and when i pop out so one thing actually is i wanted to say is about the gate main method right how we will implement gatement method we will go always on to the top of the stack we will go here top of the stack and we will read this minimum value basically correct that's what gate mean method will do you got it right so now for example now if let's say i don't i remove all these three elements from the stack right one two three so now i don't have these three elements let's just assume for a sake of discussion when i call get mean method it will go here and then it will read this value right this is the minimum value it will give us 2 because we are now only talking about these two numbers that we have pushed right these three numbers we have already removed from the stack so it should tell us what is the minimum values between these two numbers correct so that is why we will always go to the top stack uh top of the stack and we will read this minimum value here right that's why we always store that minimum value along with the value correct so now you got the idea how the gate mean will work right pop method is very simple pop method just removes the top element right so we just remove this top element from the stack right top element will remove it and top method actually will return this number actually it will just return this 20 number when we are calling it right let's say we are calling top on this stack now it should give us this 20 as the top correct we just return we don't remove it basically that is the difference now right now whenever we call gate main method we will always go to the top of the stack and we will read this second value the second means this value right second value that gives us the minimum value that is available into the stack correct so i hope with this detailed explanation you got the logic clear now how the mean stack we will implement uh so that's why we will always hold two values in that every element one is the actual value and one is the minimum value we have seen so far correct so it is easy now to you to implementation if i show you it will be easy for you to grasp that implementation so we will create a stack but now stack will be holding integer array right integer array because we want to hold two values here in this array correct so now i think i'll just go ahead and i'll show you the java code now then it will be even more clear to you how the implementation will work so let's go to the code so this is our uh implementation so first we will create a stack as i said it is an integer array right it will hold integer array and we just call it a stack right so mean stack is the constructor so here we will actually instantiate the stack right so we'll just say new stack so it will create the stack and then let's take a look at the push method right so we will get a value that we want to push on to the stack so what we do is we will actually just read the current minimum value as a null value right then we will do if the current stack size is zero it means that nothing is there into the stack right like for example first time nothing is there then current mean value will become this value right because that is the first value we are seeing because nothing is there into the stack right so we'll just initialize the current mean as the this value correct now if something is there on to the stack then what we will do we will always look at the top mean value right this peak means we are looking at the top value and we are looking one index one is basically the mean value because we always keep mean value at index one actual value we will keep at index zero and the minimum value we have seen so far we will keep it at index 1 correct so that's what we will do is current minimum is equal to read it from the top the minimum value and this current value that we are seeing whatever is the minimum will become the current minimum correct so for example now let's say um let me just remove these colors lots of colors are there let's say what i mean to say is um if we are here right if we are here as of now we have seen this 2 is our minimum value right 2 is minimum value so when we are inserting 1 we will compare this one and two whatever is the minimum we will take right between one and two one is minimum so we will take one here correct so that's what we are doing right so that's what we are doing here so we are always having the current minimum here and then we will push into the stack the value here and the current minimum so this current minimum we always will get that current minimum that we have seen so far basically correct so this is how the stack will push into the stack this is the value and current minimum two elements we push correct into the stack and that is why our stack is holding integer array right so what does the pop do pop will just remove it from the top of the stack so stack dot pop right we will implement like this pop method and top will give us the top number right top value it gives so how it will give us stack dot peak 0 right because 0 is the value right so 0 will just return here as a top so peak method actually returns the value it does not remove it just returns right and then gate min actually we will again pick it means we are actually looking at the top uh top of the stack but we are looking at the first index right first index holds the minimum value right so that's what get mean how we will implement gate method right so this is pretty clear to you now this is a constant like uh as they said let me show you so this one is a constant time basically correct constant time implementation so now we can just uh um you know and the memory it will hold uh we will need this stack to hold the elements here right so if we have let's say n different numbers in order of n will be the space complexity for this solution so i will just show you couple of examples we can test so this is the same example i shown you right just now so this is the one that we saw right so we can just test this example so we are actually uh pushing 4 to 1 10 20 and then we will call min so min will give us one here right so min is giving us one here and then we will remove it from top so this top will be gone basically correct then we will if we call top then we will get 10 right so we will get 10 is the on the top and again if we call get mean again we will get one here right so let's just execute this test case make sure this approach works so we are getting correct answers as you can see from the output so we can test with their test cases so this is their test case right the first example let me make sure it also works so um we are getting correct answer for their test case as well so um we can just go ahead and submit our code to the lead code now for mean stack so this is one of the popular amazon facebook coding interview questions so make sure you practice this question so our solution got accepted by lead code let's try to resubmit it sometimes the numbers are not correct so now it is showing 68 percent right so now performance is 68 percent faster than other submissions which are done online uh and the memory usage is 59 percent better than other submissions which is a pretty good solution for this problem mean stack a facebook amazon forum questions also asked by many other companies as well so uh i hope you understood this problem clearly now with these examples that i shown you with the detail explanation and this is how the this is the internals how our stack will look like right so it always hold two elements as you can see right 0 1 always hold two elements and always it holds the value and the minimum value like right 10 is the value and one is the minimum value right 20 is the value one is the minimum value we have seen so far correct so um uh so if you are new to this channel there is a dedicated playlist on this channel for lead code problems you will find more than 250 different varieties of lead code problems solved and explained all the problems come with java solutions code where the java could be shared through github repository links are always shared through the video description where you can check out the java code play with the java code with different test cases for your better understanding if you like this video if you find this video helpful and if you like uh the way the video is created with this whiteboarding session examples and java code then please give it a thumbs up to the video give it a like to the video subscribe to the channel your subscription is very important for the channel because that is the way the videos can reach to more people who need help in solving coding problems some people find it difficult to solve different varieties of coding problems through this channel we would like to help them by showing and demonstrating them how different problems can be solved using different data structures algorithmic techniques and java programming so they can also learn from this video more about problem solving using java and data structures so if you like this video give it a like share it as much as you can so more people will come to know about the channel they will also watch these videos and learn from these videos they will also understand how we can solve different problems using different data structures and also get help in their coding interview preparation process to become more and more confident in your coding rounds of interviews try to practice different varieties of problems the important varieties of problems you should try is bfs dfs graph problems matrix problems binary search tree related coding questions related to linked list strings optimization problems using priority queues dynamic programming problems as well as lots of logical problems right so uh if you practice those problems if you go through these videos on this channel you will get like really good preparation for your coding and java interviews whenever we solve any important coding problems we create videos on this channel so that we can explain our logic and approaches to others so they can also learn from these videos more about java programming data structures algorithm and computer science techniques to solve different varieties of problems so make sure you click on the bell notification icon so you will get immediate notifications for all our new upcoming videos keep coding keep learning keep practicing and thanks for watching this video
Min Stack
min-stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto the stack. * `void pop()` removes the element on the top of the stack. * `int top()` gets the top element of the stack. * `int getMin()` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Example 1:** **Input** \[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,null,-3,null,0,-2\] **Explanation** MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 **Constraints:** * `-231 <= val <= 231 - 1` * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. * At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
Stack,Design
Easy
239,716
920
Every Number of Music Playlist Name of the Problem What's in it We have been given a music player and different songs and what we have to do is we are getting bored so during a trick what is our goal that we have to Have to listen to songs If we see what is given to us in the first question that N is your free, G is also your 3 and the goal is also our 3, so whatever we have, we will have to bring all the three songs, this is our goal. Brother, if we read three different songs, we will read three different songs and I too, if we have three, then what can be possible pieces? Simple one, you are three one Ab ki baar kya hai ab Ki Bar and Hamara 3 Sorry, this is our zero, so what do we have to do, then there are simple songs in this, ok brother, there is no such problem, absolutely friend, there is no problem, but if you think, a big number comes like this. Think N is done 20 and 1 minute is 0 now tell me how will you leave now will you keep picking songs one by one that brother what have we done we have made such a big year what are we doing in it we are taking songs from first N If the same can be repeated then we will take it one by one. First we have made it, then we can do it, then we have taken one, then it can be repeated. We always have to play the game with our mind, so we have to concentrate on how we can break it down. If we can then we can simply solve our problem and what can we do brother, if we have such a problem then we will store it and we will store it in such a way that if we think that I have something then in the base condition also in DP where This will stop and whatever is on the story is that ours has become big, now how will we be doing it, we will discuss the same thing, okay if you think brother, ours has become zero, okay ours has become BG and ours have become J. The goal is also zero, it's okay, that means our songs are also zero and ours is also zero, that means the length of our life is zero, we don't have any songs and our lyrics are also zero, then what can happen? Brother, okay, both of ours have become zero, so now what should we return? If we have, brother, what is ours? Okay, I understand, that means in one way, we can do it. Okay, after all, how do we solve it or simple? Right, brother, what can we do, we have two things that we can do, brother, either you do the old song, okay, what we did is we will multiply, if we talk about the old song, if we do the old song. What is there in the old song? We have already put the old song, so what do we have to do? We have to see how strong our children are and give it to us. Okay, so I hope you have understood this. Let's do a little code. And we have to understand this thing from the court, first let's make a vector, friend, I will take it, which will take out ours, in this, now we have made a vector long, first of all, she said, if ours is zero, then we What will we do then we will say brother please return our Momo and then we say ours will remain the same, our goal will be reduced because we are taking the old key and Momo and what will we do with it. We will do these in negative If we are playing then we will say brother solve it, Momo and ji will be in the last and what will we do with this, we will add plus to both of them, here I am late and in this I have made one two three one Do two or three OK and return. If OK, then this is our acceptor. After submitting, there was no problem. Basically, what we had here, we put it up in the shoe mode, here we have to do it, we have to direct sometime. Well, what happens is that due to some issue in the compiler, we were facing this problem, so here we should direct you, okay, and now we run it and see, we have submitted our solution and our solution has been submitted, okay. And once you can see, I did not make any other changes, this was the only thing that we did with the mode, okay then look, you must have liked it
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
230
hello everyone in this video we are going to solve a lead code problem number 230 which is about 0.03 so the number 230 which is about 0.03 so the number 230 which is about 0.03 so the problem is we are giving the row the root of a binary search tree and an integer K we should return the kth smallest value of all the values of the nodes in the tree so for example we are giving that 3 and we have to return the first the smallest one in a smallest value of that in that tree so as we can see here the smallest value a is one so we should return one another example is giving given that three we should return the third smallest value in that tree so as we can see here the number one is the smallest one 2 is the second smallest one and we should return three because it is the third small Stone uh so one way of solving this problem we can um Traverse that array in order way so we can iterate over that over this value in sending order so let's create let's draw a tree for example like this current another one here and a binary search tree is a tree where the left values is less than the root and the right values is greater than the root so for example we might have here number seven and here we must have a value Which is less than seven so for example five and the right side we should have a value greater than 5 which is maybe six and here less than five maybe two here greater than 7 9 greater than 9 Maybe 11. so to Traverse this tree in order way we will start with the left side passing to the root node then we will end up with the right side of the three so the output will be look like to then five then six then we will move a level up reaching to seven then the right of the seven nine then 11. so this is how we can Traverse that tree in order way so as we can see here the values are sorted in sending order so the first one is the smallest one and the last one is the greater one so to implement that to write that in a code we should create a function let's call it in order two others and that function will accept a tree node as a parameter and we will do the logic here so as we said we will print out the left values of that three node dot left then the middle and then the right side of that tree I'm doing that in a recursive way so it is just an easy way of dealing with three questions I also have to Define an array to store these values when I Traverse the tree so here the middle I will print I will push to that array the D3 Dot um three notes sorry free node dot value okay let's get rid of that and here we should return and the because it is a recursive function we should Define the base statement base case which is if there is no root we should return just to return so in case we are heading to let's say for the left right side of the tool and we will should return and get back to two so this is the logic of traversing the array in order way and now we should call that function here and we should pass the root so now this function will get called and we will start with the root node and then the left then we will just end up with no uh leaf with a leaf node then we will just go up a little and go that back and forth till we reach to the right side most right side of V3 to prove that we are doing it in a right way I will show that in ad console log we should now get the these value in and ascending order right so let's test that this should be so for that this should be three node of course don't have anything let's do it so now we are just reversing as we can see here we are getting the value in ascending order the first one is the smallest one the last one is the highest one for the second case as well we are getting them in a in the correct order so now the second step is we should return the key in the case uh smallest value so let's get back to the Whiteboard and like let's take that we are getting now this array so okay and we are supposed let's say we to get the second smallest value so we should return to so in order to return to this is the uh this is a zero indexed array so this is 0 1 2 3. so in order to get return that value as a uh as a result we should decrement or subtract K minus 1 in order to get one so K2 minus 1 will get the index of that value so assembly we should return the Decay minus one Let's test that now it's passing um let's try to submit it yes we are doing it correctly thank you for listening
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
458
hey guys welcome back to another video and today we're going to be solving the leak good questions poor pics all right so i think this question is really interesting so let's just kind of see how we can solve it and before that let's see what the question actually is all right so we're given a thousand buckets and out of those thousand buckets only one of them has some sort of poison inside of it and everything else is going to be filled with water all right so they all the buckets look the same and if a pig drinks the poison bucket it will die within 15 minutes what is the minimum amount of pigs you need to figure out which bucket is poisonous within one hour answer this question and write an algorithm for the general case okay all right so the question here is um so this question over here which we just read out it's really specific right so we have a thousand buckets it will die in 15 minutes and we have a total of one hour for testing okay so those are that's a more specific type of question but now we'll just look at the general case okay so in the general case if there are n buckets okay so that's the n number of buckets and the pig drinking poison will die within m minutes how many pigs x you need to figure out the poisonous bucket within p minutes and again in this case as well there's only going to be one poisonous bucket and we're guaranteed to have at least one okay and only one not at least okay so a pig can be allowed to drink simultaneously on as many buckets as one would like and the feeling takes no time so this point is pretty important a second point is after a pig has instantly finished drinking buckets there has to be a cool down time of n minutes during this time only observation is allowed and no feedings at all okay any given bucket can be sampled an infinite number of times by an unlimited number of pigs okay so hopefully you understand what the question is and i would highly recommend to read it over and first understand what the question really is asking for so now let's kind of draw it out and see how we can kind of visualize uh this question okay so uh we're gonna be given three inputs okay so we're gonna first be given the number of buckets we have then over here we're gonna be given a number and this number over here is gonna stand for the number of the amount of time it takes for a pig to die okay so let's just call this minutes uh to die okay so this number is gonna be how much time it takes to die and over here we're gonna give one more number and this number is the time we're given uh until for making tests right so this is the number of the amount of time we're given to make a test and by the ending of this time whatever it is we have to find out whether which bucket is poisonous all right perfect and again remember the end goal over here is to find the minimum pace needed okay minimum remember that all right so for this case let's just kind of standardize these two numbers so let's say uh it takes 15 minutes for it to die and let's say it takes we have an hour for testing so in other words 16 minutes okay so i'm just uh okay i'm just specifying the numbers so it's easier for us to calculate things and let's just leave buckets as it is all right so let's kind of just go through this and see what is the total number of tests with that we can make so in the beginning let's say we feed a pig okay so we fed a pig and when do we know if something happens to it so the next time we know something happens to the pig given these conditions since it takes 15 minutes for the pig to die only after 15 minutes we're gonna find out whether it's alive or dead all right so we start off at zero then we're going to be at 15 minutes okay or we can just ignore zero so at 15 minutes we'll find out whether it's alive or dead now the next time we can find that is going to be at 30 minutes so 30 minutes is another time when we know it's alive or dead then we have 45 and then 60. all we're doing is we're just adding plus 15 between each of the intervals to see if it's alive or dead all right pretty simple so as you can see clearly we have a total of four tests that we can make and another way to just find this a really simple one is take the total time we have for testing and divide it by the number of ta or the amount of time we have before a pig dies so in this case 60 divided by 15 is going to be equal to four so over here we're basically telling that we can make up to four tests so now let's start off with the base condition okay so we'll just kind of build off of this and you'll slowly understand how there's a small pattern which is actually really unique and once you find it's really cool okay so let's say the number of buckets we have in the beginning or in this case right now is going to be four right and let's just draw each of those buckets so one bucket here two three and four and i'm going to label them starting from zero so zero one two and three right so now we got four buckets now within these four buckets three of them have water and one of them is going to be poisonous so we don't know which one is poisonous but we just want to try out so in this case let's say we have just one pig okay so let's say we have one pig what we're gonna do is we're gonna have that pig go and eat whatever is at the zeroth bucket and let's say nothing happens that means that it's still a light and zero is filled with water then we're gonna have the pig go and eat with the first bucket okay so now it's gonna eat at the first bucket then it's gonna eat at the second bucket and then it's gonna eat at the third bucket so how many times did the same one pick eat a certain thing so it ate once at zero second time at one third time at two and for the fourth time at three so in total we had the same pick eat four different buckets and that is a total of four trials so that actually makes sense because we can make a total of four tests and by doing this we can so we make a test and over here we get the next results at 15 minutes if it still doesn't die we're gonna go over here and then we have 30 minutes then we go over here then 45 and then over here 60. so it is within our time frame of one hour so this is a good approach so now let's actually add one more condition and let's see how that looks like so let's say our buckets now is going to be equal to five since before we have five buckets and the minutes to die and the minutes to test are going to stay the same and now let's draw a fifth bucket okay so let's draw a flip bucket over here and this over here is going to have an index of four so now we're going to do the same steps okay so now we're going to have to pick 8 over here each over here and over here as well but now the problem is after eating for a total of four times we're going to be done with our time we're going to be done with one hour and technically we're actually not supposed to cross that time period so what exactly do we end up doing now so now using deduction we can actually figure out something really simply so let's say we eat at uh the pig eats at zero nothing happens then it eats at one nothing happens two nothing happens three nothing happens so far 16 minutes have gone by and we're done with the testing period but we did not test four yet but pretty simply we can just deduce that if the pig did not die in zero one two or three that means that four is where the poison is so in this case we can take a maximum of four tests which is 60 divided by 15 we can actually be doing five tests because if the four tests actually end up with a live peg we know for a fact that the fifth one or in this case this over here is going to be the one with poison all right so hopefully you understand this condition and now that you understand this we can go on to a bigger number and before that let's just try to generalize the small part over here okay so let's say we are actually given a 100 minutes and it takes 10 minutes for a pig to die so 100 divided by 10 and 100 divided by 10 is going to give us a value of 10. so what this means is that let's say we have a row of 11 values right in one row we have 11 buckets so in that case we can make up to 10 tests and if all the 10 tests make the pig alive that means that the 11th bucket has the poison all right so hopefully you just understand this part pretty well make sure you do understand it and now let's just go on to a case where we have a lot more buckets so we have 15 buckets and now i'll draw it out okay so this over here is the grid which consists of a total of 15 buckets so if you're wondering why there's only 14 it's because we're starting off at zero okay so zero all the way to 14 is nothing else but 15 buckets so now i want you to notice how many buckets are in a row so in one row we have five buckets okay so there's five buckets in each of our rows and why exactly is that and the reason for that is the same as what we saw earlier and that is basically that uh we can check for zero one two and three if we're alive in all of those that means that four is uh the poisonous one okay so now you get that and now let's see what exactly our procedure is going to be when we actually solve this question so we can kind of split this question into two different parts so one part is going to be to find out at what row is the poison actually there okay so this is just going to give us at which row and another thing is going to give us at which column the poison actually is okay and before doing all this i just want to make two things really clear so i'll just go back to our question here so one thing that i want to make clear is the question is what is the minimum amount of pigs you need to figure out whether the bucket is poisonous okay so over here we do not care how many pigs die for all we care all the pigs could die but as long as we find it with the least number of pigs possible then we're good to go so that's one thing you need to understand and the other thing that you want to understand is uh the best condition in this case is you could just put the same number of pigs uh at each bucket right so in this case you could put a thousand pigs and each of them at one bucket but obviously that would just take up 15 minutes right that so that would be the fastest right giving us an answer in 15 minutes but the problem with that is that we would need a thousand pigs which is way too much and not needed okay so that's there's that and finally one last thing is this okay a pig can be allowed to drink simultaneously on as many buckets as possible so we're gonna kind of use that rule to solve uh whatever we are about to do right now okay so what we're gonna do is we're gonna take a pic okay and we're gonna make and for now let's just focus on getting the correct row so the pick is gonna drink at zero one two three and four so it's gonna drink zero one two three four at the same time right so in this case if everything is water then the pig is gonna lift but if even one of them ends up being poisoned then we know for a fact that the poison is in this row all right so let's say three has the poison okay three has to poison so the pig over here is going to end up dying so we wouldn't know uh where exactly it is but we would know that the pig or the poison sorry is going to be in this row so that's exactly what we're doing we're finding out at what row the poison is so after doing uh drinking this we would then make the pig drink five six seven eight and nine so now in this case we're going to drink this entire row and finally we're just gonna do those two we're not gonna make it drink 10 11 12 13 14 because if the poison is not over here right so this is all water we know for a fact the poison is going to be in the last row okay so now this is how we're gonna get our row using one peg now how exactly do we find our column so for the column we can do one thing and the thing that we could do is after checking for the row we could use that same pick and use it for the column but that actually won't be good for us because uh it could possibly exceed four tests and that's not good for us right so what we're going to do is over here we're going to be using one pick and over here we're going to be using another pig so a total of two pigs are going to be used perfect okay so now we have two pigs and let's just look at this so again this is how we're finding the row i already showed you now we're talking about the column and the approach is similar okay so now we're going to make it go at 0 5 10 right like this then we're going to go uh make the pig drink 1 6 and 11 then we're going to make the drink a big drink 2 7 12. let me just write these down quickly so then 3 8 and 13 and that's it so over here we have a maximum of four tests so what's going to happen is the row and the column are going to be happening simultaneously so what i mean by that is this step and this step are happening at the same time okay and by the ending of this we're going to find out at what row and what column the poison is so let's say uh just for a hypothetical we the pig actually dies by drinking 2 7 and 12. so that means we know that somewhere over here we have poison but we don't know on which row but let's say the pig lives over here it lives at 0 1 2 3 4 it also lives at 5 6 seven eight nine so in that case if it lives in the first two rows we know that it is not going to live on the third row so now we know that this over here is the row that we're looking for so really simply the intersection of these two is going to be our answer and what is the intersection well the intersection is at 12 so bucket number 12 has the poison and we want our pick to stay away from that and to do this it only took us two steps now let me try to generalize this again remember two steps is because we're taking 15 minutes to die and 60 minutes to test all right so now let's say we actually have a total of 25 buckets then in that case as well we would only require two pigs and why exactly is that so in this case if you look at it horizontally we have one two three four five right so we have five rows and let's see how many columns we have we only have three columns so to get the most out of two pegs it would be in a condition where we actually have five columns and five rows so by having five by five which actually amounts to 25 buckets we're going to get the best result using two bigs in other words we'll have the most efficiency but after we go past 25 we cannot use two pigs anymore we are going to need more than two pigs now going back to this uh analogy that we're kind of making here let's just say we have five pigs okay or sorry five buckets so when you have five buckets you only need one pig okay at five to the power of one that means that you only need one pig to find out where the poison is in five buckets and over here we have five to the power of two what that means is that we have two pigs for finding out where the poison is in 25 but how do we keep going okay and now let's just say we have 125 pigs so to do that i'm just at excel over here and horizontally we have and one more thing is that remember that the timings are still the same okay we have 15 minutes to die and 16 minutes to test or one hour okay so keeping that in mind over here we have a horizontal of five rows but our vertical goes up to more than five rows we have 25 columns sorry rows vertically and we have five columns right so if you kind of just look at this as it is you could kind of imagine you could put uh one pick for finding the column right so that's pretty simple but then uh on top of that we would need one pick on this row so that's two then three then four then five so we would need five pegs plus one so we need a total of six pigs but we kind of want to think of this outside of the box right so we're looking at this in a two-dimensional way but what if we in a two-dimensional way but what if we in a two-dimensional way but what if we add a third dimensional to this so in this case when you have three dimensionals you would have a cube so what's going to happen is we're going to have one of the rows of buckets over here right so we would have five buckets in the x-axis the x-axis the x-axis then we would have five buckets in the y-axis and we would also have y-axis and we would also have y-axis and we would also have five buckets in the z-axis okay so that five buckets in the z-axis okay so that five buckets in the z-axis okay so that over there gives us a five by five okay so let's just write that down so when you have a five by five that gives you a value of a hundred and twenty five in other words that's basically telling us that we need three pigs to find anything which is below or equal to 125 buckets okay so to find the poison of which is equal to 125 buckets we are going to require three pigs okay and this also results to anything which is less than this but what is the lower bound for this going to be now again remember when we had two pigs we could go up to the number 25 buckets okay so we're gonna need three pigs whenever we have more than 25 buckets or less than or equal to 125 buckets so hopefully you can kind of see the correlation here again this is specific to 15 minutes to die and 60 minutes to test and now we can generalize this using this kind of uh solution that we found out which is basically given 15 minutes we know that we can only take four tests but so we have 15 minutes to die and 16 minutes to test so 60 divided by 15 gives us four tests but we're adding one to this because of that extra case that we saw so the first four are still alive that means the fifth one is it so in this case we're adding one so that gives us five and now we're going to take 5 as our base and in other words to make it simpler we're taking we're only going to be looking at base 5 numbers so you could use logarithms to solve this and we're going to be looking for the base 5 number and we're going to be keep adding on to our account until whatever our value is sits in between whatever this is so let's say we have a hundred picks so a hundred picks needs to be greater than 25 but less than 125 given these two conditions so now let's try to generalize it i tried my best to explain it hopefully it was good enough so yeah now let's try to code it out okay so over here what we're going to be having is we're going to have the number of pigs needed okay so the number of pigs needed in the very beginning we're going to start off with a value of zero so now what's going to happen is we're going to go inside of a while loop now what we're going to do inside of this while loop over here is we're going to take the minutes to test okay and the reason we're taking the minutes to test is because we're doing a more generalized way right so take the minutes to test and we're going to divide that by the minutes to die and this is exactly the same as doing 60 divided by 15. now to this value whatever this value is we're going to end up adding one now the reason we're adding one is like i said earlier right so the exact same reason why we added one to four right so four plus one five and that gives us five things that we could test okay so we have this over here and now what we're going to do is we're going to raise this to the power of how many hour picks we have and this just goes back to the exact same thing which i said earlier so whatever this number is so in this case uh when you have 15 minutes to die and 60 minutes to test that means we're only looking at base 5 numbers so 5 to the power of 0 would end up giving us a value of one so then we're going to increase so then we're going to check against the condition but each time what's going to happen is we're going to increase the number of ticks we have then we're going to have 5 to the power of 1. so that is going to give us a total of five buckets right so we're gonna keep doing this until whatever value we end up having here is less than how many other buckets we have now the second this value over here becomes greater than the number of buckets we have we're not going to go inside of this loop so let's just actually look uh at a condition uh where the minutes to die is uh 15 then 60 and the number of buckets is 125. so first we're going to go inside of this then we would have 5 to the power of 1 but we keep going so then we would have 5 to the power of 2 giving us 25 and then when we have 5 to the power of 3 we would have 125 now 125 is going to be equal to the number of buckets which is 125 and in that case our pigs becomes three and we're going to stop so we're not gonna go inside of the while loop and at that point we can just directly return the number of pigs we have all right so that should be it for the solution and hopefully you did understand how this works i thought the question was really interesting and it was a pretty fun question so yeah thanks a lot for watching guys bye
Poor Pigs
poor-pigs
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: 1. Choose some live pigs to feed. 2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs. 3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time. 4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. 5. Repeat this process until you run out of time. Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_. **Example 1:** **Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15 **Output:** 2 **Explanation:** We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. **Example 2:** **Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30 **Output:** 2 **Explanation:** We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. **Constraints:** * `1 <= buckets <= 1000` * `1 <= minutesToDie <= minutesToTest <= 100`
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test. How many states can we generate with x pigs and T tests? Find minimum x such that (T+1)^x >= N
Math,Dynamic Programming,Combinatorics
Hard
null
1,038
hey how are you doing guys it's ilya bella here i recording stuff on youtube chat description for all my information i do all lit gold problems make sure you um subscribe to the channel give me a big thumbs up to support it and this is called binary search three to creator sum tree um given the root of binary search tree with distinct values modify it so that every node has a value new value equal to the sum of the values of the original tree that are greater than or equal to noted volume as a reminder a binary search 3 is a tree that satisfies these constraints the left subtree of a node contains only nodes with keys less than the node's key the right subtree of a node contains only nodes with keys greater than the nodes key both the left and right subtrees must also be binary search trees um constraints the number of nodes in the tree is between 1 and 100 each node will have value between 0 and 100 the given 3 is a binary source 3. well let's look at this example um what do we got these three and we got you know the root which is four and it's children we can solve this problem uh using like doing depth research i'll show you two solutions uh first we will solve this problem uh recursively and then iteratively in both of that solutions we start at the root then we go right until the current node is equal to no then we start backtracking and we count the total sum by adding the previous sum to the node's volume right so we go here then we start backtracking and we say eight plus zero which is eight right then seven plus eight which is 15. then 6 plus 15 which is 21 5 plus 21 which is 26 then uh 4 plus 26 which is 30 then we go here right we go here then uh again we start back dragging and we say 3 plus 30 which is 33 to plus 33 which is 35 then uh 1 plus 35 which is 36 and then 0 plus 36 which is 36 and we return the route right go for it first as i said i'll show you how to do that uh recursively we create variable which is uh integer 3 is equal to zero then in the case when root dot um left is not equal to null um and here in the case when root dot right is not equal to no first we go right uh we call this method recursively we pass root dot write then we calculate this total sum we say pre is equal to uh and also root dot volume which is three plus root dot value then we go left and we say um we call this method recursively again but we say root dot left and finally we return this uh root that's it let's run this code there we go let's submit success good so um you know we start here then we go right then we start backtracking right we say three which is zero uh zero plus eight which is eight then we set up root.volume set up root.volume set up root.volume 2 to 8 then we check whether its child to your left is not equal to null if it's not then we go left otherwise we uh gone right we return this route and we go on backtracking and we are here again we say 3 which is 8 plus 7 which is 15 right and we set up a root value to 15 then again we check uh if root.left is not equal to no then we go root.left is not equal to no then we go root.left is not equal to no then we go left but it is so we just return we uh gone moving upwards we are here then again like we say um six let's say six root volume plus 15 which is 21. we set up to 21 uh right here and right here as well then we go left here and we start exploring this branch then we say we are we can see that root.write that root.write that root.write is equal to null then we yeah we say five plus uh 21 which is 26 then we go left but it is no so we just you know we skip this condition we return this uh 26 and then we go here right as i said um we say 4 plus 30 then we go here again we start backtracking we go here uh again here and then here and we return this route that's the first solution next i'll show you how to do that iteratively we can delete that and we create a sum or just the result whatever is equal to zero on three node which is uh let's say current is equal to root and we need to create a stack in order to solve this problem you know stack data structure means that we can push the elements onto the top of the stack and then we can pop the elements from the top of the stack as well that's how that works so we say stack of the type integer stack is equal to new stack type integer and the condition is while this stack is not empty or the current node which is current is not equal to null we create another while loop and here we check while the current dot right is not equal to uh or just is while current is not equal to no we say stack door push will push the element onto the top of the stack say current and let's say here we got three not instead of integer three not and here we go as well then we set up the current node to current dot right we go right then uh when we start backdragging we say current is equal to stack dot we start moving upwards from here to here and so on then we say um you know like three is equal to not three we got some here plus equal to um let's say current yeah current dot value and then current dot volume is equal to the sum and we say uh the current node is equal to current dot left finally we return the road which is current right or just current at left yeah finally we return the road that's it um sum plus current dot volume then current value is equal to this sum yeah that's it let's run this code good success so here we do the same uh we go right then we start backtracking and we pop the element from the top of the stack and we add or just let's say let's look from this let's see from this point we got some which is zero then we set up current we create a new node which is uh root then we create the stack of the type 3 node and while any of that condition is true we do this loop we create another while loop which is nested and while the current node is not null we keep pushing these notes onto the top of the stack and we go right okay then we start back dragging we pop the element from the top of the stack we said the previous sum plus the node's value and the current node's value is equal to the previous sum plus uh the node's volume and then we go left right and then again we start by dragging and so on and so forth thank you guys uh for watching leave your comments below i wanna know what you think follow me on social medias on instagram on snapchat and i wish you all the best do your best and forget the rest have a good day bye
Binary Search Tree to Greater Sum Tree
number-of-squareful-arrays
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val <= 100` * All the values in the tree are **unique**. **Note:** This question is the same as 538: [https://leetcode.com/problems/convert-bst-to-greater-tree/](https://leetcode.com/problems/convert-bst-to-greater-tree/)
null
Array,Math,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
47
336
Hello hello si need tu return word i + word a parent like every si need word i + word a parent like every si need word i + word a parent like every si need tu return so si need tu return such a condition can also happen then we will reduce one which If anyone checks, can give only one thing, then we will also take an index of the empty string along with it and if we get a digital one with already-paren drum, and if we get a digital one with already-paren drum, and if we get a digital one with already-paren drum, then we will send it to the special off-the- then we will send it to the special off-the- then we will send it to the special off-the- interest and already vector by mixing both in such cases. What can happen in this, we can have something like ABCD and we can divide it into parts like left, middle, right and we can see like an example, the middle part, both of these like this, we can say this. The empty string is our left part and we can check this While doing this we can check A B C D is the last left part man take what we are left with is the empty string and what has to happen for this to be the right part First you can see its reverse also, like I told it as left plus palindrome, it is right, now see its opposite that DC can happen many times, so what we have to do is to store the reverse value of ABCD in an unloaded map so that Later if we have to check, man take this, we checked and it has in it, so we check the value, do we have this, palindrome already, reverse of this left, is there any other A, if we have A, then Here Dal Denge or Main Lo here Pe Ba Tha Already Left is our Ba so we will reverse check do we have it now and if rate is already then we will connect its right market then we have to check whether its reverse otherwise For this, first of all we will reverse and put everyone in the unloaded map with indices like unloaded map of DCB zero. Its [ zero. Its [ zero. Its What will be the reverse? It will already be like this and when we are checking that it is so then it will show that there is Han at this place. Zero one on three but we can't take it so I also have to check that there is no value from that because we can't net 3 and 3 so what is that time check then you can see from the court in the second part Let me explain this is the function to check whether it is palindrome or not in this we are giving two values ​​left right is palindrome or not in this we are giving two values ​​left right is palindrome or not in this we are giving two values ​​left right which is start and end -1 and it will check whether the value end -1 and it will check whether the value end -1 and it will check whether the value is from start and end as long as both are equal. If the middle value is not there then first adervise return pro then this will return left and right sorry true or false and this is the function which will give our solution all the districts are words then empty string will be same so same string. Do the same indicator and we will have an empty string which we combine to make a candidate and check it for value. From here till here if it is an empty string then put it in the empty strike and index. If it is already palindrome then index it. If not then reverse it and start our for loop second one from here and we can do it second time. First of all our left is empty string plus if it is then the remaining right word has been extracted here and check it. Did we know whether we have that value or not? If we have that value and it was told that there is no other value for it, then we will put that answer. This second one is going from zero to cut mines van, so we are checking in it. For example, if zero to N is checked then first drone plus right value is being checked. This right value will be empty first and later it will be the last value and to check left we will create a left function which will be left and its reverse will be left then cut will be last. What will be till end mines van will be our left value because its reverse we will check we have no if yes then answer is string if we have MTS string then we will check if we have any already first then we have or not if yes So we will combine both of them and first we will return the answer of empty string plus paren drum and second time we will return the answer of MTS string plus parel roll plus mistry. Do n't put any comment in this if you look because many times this tally gives the price and not on doing it. Gives butt she gets a little complacent like it just gave
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
278
And here we are going to attempt question number 278 which is the first bed version, it is an easy level difficult question, India has a lot of downloads also, what is given in the question, it is given in the question that there is a product manager. You are running a company and you are leading a team which is developing a new product but unfortunately what is happening there is that the latest versions of the product are failing your quality check. I am not able to pass and because the versions that are coming out there are based on your previous version, then the version after the next version is also the next version, which means what is given to you here. Here you have been given one, here you have been given that one, okay like suppose you have been given a product in which the first version is its gudda, the second version is go d, the third version was also good because this version is better than the previous version here. But its version support is fine but in between a version came which became bed here, ok now send this also on the previous ones here but what kind of version came in between where there was bed version, now after this also from the version All of them here are bed versions, okay, so here it says you suppose you have n versions, you are given a number here, okay in the input, you are given n here, how many versions do you have here, like One two three do five six plus eight no das I have here the value of N is 10 I have here 10 versions and you want to find out the first one here you have to find out the first bed one here after that your All the beds have been started from version, then from which version the beds have been started at your place, you have to find out the first version, okay, you can find it out, how for this, we are returning the boolean value here, which means it is returning either If there is Dada version, if not then it will return Jal. Okay, let's see the example. If I show you here, you will get the value of N here. If you look here, you will get the value of N from the five versions here and the bed version. That is four here, the example has been taken, you are given only here but okay, so you see this bed version here, they did it here yesterday, you got jealous because the bed version is starting from the whole and when it is done here from four and five. But if I did it yesterday then it has come true here because your bed version has started here from four, so you have to find out from where your bed weight has started, your bed weight den has started from pay force here, like in your case if you If you look at your gas here, this is your version 1.1.3, 1.4 and 1.5, then version 1.1.3, 1.4 and 1.5, then version 1.1.3, 1.4 and 1.5, then version 1.5 which is ours, is the first aid 1.5 which is ours, is the first aid 1.5 which is ours, is the first aid version here, okay, I hope the question is cleared, okay, how will you do it if you look here. Your list is sorted, we had asked a question, if you care, we had asked a question, Rotted Sorted, okay, first you will find it above, what was there in it, 7 and 6 and 1234, which is the input, so I gave you the original, okay, it was okay. It was original, it was like this, but it was given to you in it was rotted, which was given to you in the input, you had this life, here you are just given that, how many positions are here, because of crying, two positions are here. If you are crying then the 7 which is here will come to the front, if the seven comes to your friend, then this 7 will come here, after that all these positions will shift and then your sex will come to the front here, then here Yours will come 6 and 7 and 1 2 3 4 5 So here it was sorted, you had to find the maximum in this question here, find the maximum in this question, I had to find it here but if you see the complete list here then no. The entire list is sorted if you take it here and I am giving it here as a clear indication that binary search is installed here and I am giving it here because it is related to this question of yours, you have the software here. Meaning, the second half of the list is still sorted, so you discard the second half of the D list here and move the dog here and the High Court here and move the dog near your mid. What did you do after this? 7 Your mid A is here, now you are here. In this question, we were checking whether your made element is smaller than your Hi because if your list here, if your supposition is sorted, then any of these numbers will be smaller than your Hi, otherwise, here. Okay, there is a number here which is not smaller than yours here like come of four. If you are comparing here then it clearly means that this part here is the same one here. The question is doing the same thing if you look here, what's going on with me, okay After that, from here till here, if you take this, mother, take this, your own mother, take this. Support is here on the story, you have your mid here, okay, so you will check here, from low to mid, all the elements are here, these are the elements here, these are sorted here, all which are in the second half of D list. So you can discard it from here, so this is the question here, it is doing something like this, okay, so what did you do, you moved people, hi plus one, made plus one, sorry, okay, so after that. When you calculate the made here, this will be your made here, after that you check the element here, that is, I had explained in many terms that this entire list of yours is sorted here, all the water is water, but you Here you will not check each and every element, this is also water, this is also from fruit, this is also water, so the whole list is water, it is not just that you have to check each element, will you check it here or this is from fruit, this is It is true here at this time. If this element is true here, what does it mean that the language is there before and after that, you will check which element is here, is it a bed version, is it true here, which is a bed. The version is absolutely correct, so with that, move the Hi here and then dog again on Made on lower Hi Ka. If you go out here, the Made that will come here, in this way, this will come, which is your low and mate, they are the same element, point. You must be doing this, is there a bed version, if not at all, then you will move the Dr to the mid plus band, this will be your low here, now you will check here that the one who is high and the one who is low is the same element. If you are doing this, then the loop that we put in the binary search method will be broken here in this method. Okay, so this question will be something like this, once we write the code, after that a little more. I will explain it again, it will become a little more clear, first of all, binary search will be done here, what happens here is that all the questions you get here will be one, hey, life happens here, the last element of the era, if we come out here then Aridot Length. -1 comes out, but here Aridot Length. -1 comes out, but here Aridot Length. -1 comes out, but here you have been given the number of elements, there are only five elements, okay, anything can happen, it is possible that the fifth elements can be different, we are not concerned with that, we have just given N here. So here we have assigned it to the last element, then I am checking here until your left is bigger than your right, meaning as long as your left is smaller here, this value will work like Your left will be equal to the right or if it is bigger then it will break, as we saw here that our left and right were pointing to the same element, hence the wire loop we have here. There is a break condition. Why do we come out like this here? I have already explained in many questions, so here I am doing simple right-left. here I am doing simple right-left. here I am doing simple right-left. Ok wait teacher, there is an overflow condition. What did I tell you here that you have to come here? Pay this bed weight with your mid element so here you have to put if and here you have to do the function tomorrow this bed version which is accepting a wait here we can put our mid if this is bed version If it returns true, if here I again show you this question here, if I show you this question, I have water like fruit here and then I have support here, true and this is what I have written here. Three and three and six more, this will go here on support mate, okay, now I am checking the element here, it is bed version, if not, then what will happen in it, if this one is conditioned, then it will go in your S, okay. Exactly when this is what you have to reduce here, if this is not your bed version, then Lo has to move you forward and this has to be given to you on MeddPlus One, Loko has to move you forward and this has to be pulsed on MeddPlus One, we have given further big. Now what will happen here, again your US will be calculated here, okay again your mid here will be calculated, so mid is your how this will come, okay, tax elements are the second element, your mid will come okay, so med is your here, find out this. Now you will check here, in this bed version, you have this element here, it will come true here, so if it is found here, then what you have to do here, which is your right, that means, what is yours here. Okay, so here, if this condition is here, how to put it in your Hi, okay, I am here, people will come here on the left, only then I am with people, Hi Quality, I have this element, who do I have? -What elements are there, now who do I have? -What elements are there, now who do I have? -What elements are there, now I have this element over here, this one is low, this one is mine here, this lower is here with hi, here I will calculate, one of mine here, this will come with me. We will check here again, is there a bed version here which is not there at all, then how will it go to the else, we are putting the left here, so the left will go here to plus one, hi also your same element. Pointing to, Lo is also pointing to the same element, so in this way, this one which is your condition here will be burnt, your loop here will be broken in how, the last thing will happen that you are yours which is on the left here. And here your right side means your lower and right side, both are same element, so you can return any element from here, you can also return left from here, you can return right from here. You can also return this because both your elements are pointing to the same thing. Okay, let's submit
First Bad Version
first-bad-version
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. **Example 1:** **Input:** n = 5, bad = 4 **Output:** 4 **Explanation:** call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. **Example 2:** **Input:** n = 1, bad = 1 **Output:** 1 **Constraints:** * `1 <= bad <= n <= 231 - 1`
null
Binary Search,Interactive
Easy
34,35,374
112
So the name of the question is Path Sam, you will get this question number 112, I will add this question in the description in the link, you can go and solve it, so how has the path been defined in this question, which will start from the root and go to the leaf. It will end, okay, so this is our route which I am marking with pink color and for us, as I am marking it with yellow color, then in the definition of live, I tell once such notes which do not have both children, okay. So in this tree, there are four notes which do not have any children, okay, so they are leaves, we have killed them with yellow, so our total will be four leaves from root to lead, okay, which can be started on pink, okay now. We have also given a target number of 22 in the example, so what we have to do is to add its value. For example, let's take this path. Okay, so in this path, it is okay. This is one path out of four in this path. The number of notes in a path is 5 + 4 + 11 + 2. We have to add all of them. is 5 + 4 + 11 + 2. We have to add all of them. is 5 + 4 + 11 + 2. We have to add all of them. Its value is A. We have to tell that by adding all the notes in any of the four paths, if the target value is reached then return true. If you want to do it then it is okay then this is just for example, the value of one card can be 22, one can be 18, one can be 19, the main low can be only five, so you just have to check this in any one path. Is the value equal to targetsum or not? If it is equal then we have to return true. So this is our problem statement. Now let's move towards the algorithm so the algorithm is very straight forward that I have to traverse this tree and when I go to the leaf here I will come to the note, here I have to check whether the sum of my path is the target or not, so let's reduce one, take the path, first define the path, then we calculate this thing from here from the root note. Let's start, okay, and this one which I hit with pink, so how can we calculate, two ways - 5 -4 -11 -2, so this will go to zero, either -4 -11 -2, so this will go to zero, either -4 -11 -2, so this will go to zero, either subtract it, okay, then after subtracting, it will come to zero and Lastly, check on the leaf note whether it has been completely consumed or not or add the value of these four notes. Okay, then your sum will be 22. So check that it is equal to the target. Or not, what I do is I mostly follow the subtraction method, you can do the calculation in any way, so we follow this subtraction logic once, okay, so this is what I have drawn in front of you, which starts from the root. Here we know that the value of this note is five, so after subtracting it here, we will be left with 17. Now you can pass this 17 to the left sub tree also. You can give and you will also pass the right sub trick. Okay, so that further calculations can be done, we are looking for this thing now, which we have marked with color, then on the left, I will pass, then 17 - 4, here 13 will be left, I will pass, then 17 - 4, here 13 will be left, I will pass, then 17 - 4, here 13 will be left, so here. The time till now is 13. Now let's come down. 13 - 11. The Now let's come down. 13 - 11. The Now let's come down. 13 - 11. The time till now is Tu Hai Against Tu. I can pass the tree from the left. Okay, so here we are left with 2 - so here we are left with 2 - so here we are left with 2 - 20. And what is it? If it is a leaf note, then we have to do checking on the lift note. We will check on the leaf note only and will not check on any other note. And what is the condition of live note, its left and its right are both parallel. Okay, so this will be our check that the left of the note and the right of the note are drains, there we will find out and the leaf is the note and we will check there and this is simple traversal. And by subtracting you will keep passing the value and as soon as your lip noor comes, we will check there, now you can see the court solution, these are very good courses, these are pocket friendly courses, you will go to Java, after that you will get DSA courses. You will get project development courses. These are pocket friendly courses and on top of that you will also get 10% discount. top of that you will also get 10% discount. top of that you will also get 10% discount. If you use this Prakash Tan Coupon Code then now let's look at the court. First of all you have to see this line. We have written like this. That if any note is null then it is okay then return false then in what cases can it be null in the starting If our root note is not taken then it is okay then we will return false in the starting and will not calculate anything but also like this It may be that there is a note, for example, it is on the left sub-tree, but on the right, it has note, for example, it is on the left sub-tree, but on the right, it has note, for example, it is on the left sub-tree, but on the right, it has taps, okay, so this is the part with taps, what we are saying here is to make return false, okay. Right now our final answer is not false, it is still possible but for this question we are saying that false is fine and I will show it to you in the last, here we are coming out with the collective answer of all the posts and we have imposed this more condition and It says that if any thing is true and the rest is false then I will tell you that it is true. Okay, so we will see this in the last. It is okay not to look at it right now, so now you just have to see that tap any note. If there is then return false and if there is no road null then the calculation can be done here. Okay, so see I have written here route dot well. If this note was null then this null pointer exception would have gone, so we have the one with null. If we have checked earlier, now what can we do, we can calculate it, so I have written here that if the left of the root is null or do not take the right, we are talking about a note, okay left and look carefully at this. Target is SAM, okay this is yours while passing, like I had given you the example that in the last, this is your SAM, you are saving 2 - 2 will become 0, SAM, you are saving 2 - 2 will become 0, SAM, you are saving 2 - 2 will become 0, so this is the target SAM, this is basically in every function we subtract. After doing this, we are sending the targets in the last, whatever will be the value of Stargate Sam, okay, this will be the value of the final route in it - we will do this final in that, the value of the final route in it - we will do this final in that, the value of the final route in it - we will do this final in that, the value of the route will be - and if it becomes zero value of the route will be - and if it becomes zero value of the route will be - and if it becomes zero then Here we will say this is the thing about this path, here we will return, okay and this is the last condition that you are seeing, I have imposed one more thing, I have said that left sub tree and right sub tree, if left sub tree Tree man lo turned out to be true, it has punch sum and the answer of right sub tree is false, so in this triversal, we have traversed the left sub tree, reversed the right sub tree and have imposed a condition, if this answer is true then what is false? It is true if I had put an end, then what would have happened if I had put an end, I have four cards which will be correct from the root, then our answer is true, the rest of them are free, okay, I have put another condition if even one single is true. If the final answer is true then all you need is a simple code. There is not much code on tree questions but we have to think a little bit of logic. I hope you have understood this. Let's quickly see the time and space complexity. Time complexity is big. Off n because this is the triversal of a simple tree we are doing okay what can be the space complexity this will be big off other because what is your tree in this of the year it can be something like this it can be an unbalanced tree that in this If there are only such notes, then what will happen in the word that what happens in our recognition that we call strike it, then in the year case, the total number of function calls stored in this call track will be Big of N, okay. So considering this also, let's end this video here and see you in the next lead code solution.
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
409
okay for nine longest palindrome give me a string which consists of lowercase up or uppercase letters find the length of the longest param that can be filled with it with these with those letters this is case sensitive for Cemil uppercase L okay days that concern param here assume the length of the given string will not exceed a thousand and ten for some reason input is just a string okay so one long is fine okay so I think this is I mean I did so yeah this is one of those things where there's a couple of ways you can classify these things for sure yeah there are ways you classify maybe good call it greedy may be good or whatever but basically the naive algorithm I would think which would which I which should work is just pair up to pair up the letters that appear in the string right because you know if any character appears or many letters appear modem well for every two of the same characters that appears we could just put them we could build a slightly longer diagram and it doesn't really matter where the param like there's no ordering like I said like for example in this input this is maybe one of the longest param but doesn't matter if it is on outside the DS on inside well except for the unique case where just one extra one which I actually am happy that he gives you I mean something that was always thought about but definitely even in this example did they kind of ask you to think about it maybe it could have been a gotcha slash like something that so if you up if they had not pulled it out why not oh yeah this is this should be pretty simple so I'm gonna just implement a map of yeah so I'll just be okay yeah so I'm just gonna keep the counts of water cow because I've seen so I'll do something like size 256 is the size or to 256 is the number of possible characters because it's just an okay okay so what I do now is today this is just literally straight counting the characters that show up of course there we don't know in this case they explicitly tell you that we don't differentiate between those we differentiate between the case and upper case so there's effectively different letters and now we can just go straight for okay so now we just go for the way and in the two cases basically and so we just added to the number of caring's right which is just integer solutions and then just type that by two so that would be kind of okay but now that the effect under the odd numbers stuff so I would have some so we don't even come and we just actually just like this to one let me just I okay maybe someone like that's one real quick okay that looks good there's a thousand character I mean I guess in theory we have a lot of time you could test the really long time to me that I mean this is very clear that it wants in linear time there's at this time what so like I'm really worried about running time specially where there's only a thousand bit well just make sure I get more thesis way okay so that looks okay and then finally get some edge cases like the empty string I mean time cynical Frankenstein no pad let me submit it then okay cool so that was a pretty straightforward one I don't know if I need to get into this a little bit more I mean I feel like so because some of these it feels like it's a little tricky in the sense that like if they're like little like it requires like a light bulb type thing where like oh you got to the thing then like it becomes very easy to progress where sometimes to be done it's a little trickier and in this case the observation is that I just don't really matter the order so I saw actually appears to kind of match up then it could be power drums to become and you put them in the beginning and the end each one in some order so that
Longest Palindrome
longest-palindrome
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here. **Example 1:** **Input:** s = "abccccdd " **Output:** 7 **Explanation:** One longest palindrome that can be built is "dccaccd ", whose length is 7. **Example 2:** **Input:** s = "a " **Output:** 1 **Explanation:** The longest palindrome that can be built is "a ", whose length is 1. **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase **and/or** uppercase English letters only.
null
Hash Table,String,Greedy
Easy
266,2237
4
Hello everyone I am Siddhesh Final Air CSC student Nagpur so in today's date we are going to talk about the next question which is Median of Tu Sorted are the official size so before this we have discussed all the problems mentioned above, you bill get. D link of d playlist in d description of d video you can and check out from there let's talk about problem ke bade mein jo ki median of tu sorted today of people size to iski jo us gender ki one hai woh hai find median to In which we have one error life, parents and I have to calculate the median so in this I have only one life and what I had given in the question was find the median of two sorted today of equal size so the one above it. The question that was there was also something like this, ' was also something like this, ' was also something like this, ' You are required to make a minimum number of operations. Hey Pandey, in which we did not have to do any operation in the life of our penis, the same thing has happened here too, so I Which is its actual passion medium of you sorted and median of you sorted are to find out of equal size also I will give you the link of this in the description you can and check out from there so this one which solves both the problems in the video. If we are discussing then firstly it will be the one whose gender we have and secondly this is the actual question which is sounding very similar, the problem is to calculate the median in size, so once let us discuss what is the median? In this median, the median is our center of data. Okay, center update. So, how many elements are there in this data? If there are five elements, then which index will the center be on? There will be a second index because zero one, there are two elements before it as well and after that too. If there are two elements, then this is the middle element, so this is the center of data, so this is our median but this is the color of the same, whenever we talk about the center of data, the data contained in it should always be in sorter order, right. So if we have 1 2 3 5 and 7 then now the element at the second index is 3, this is our median but this is okay, this is the thing, when we have the number of element which is added, then only we will have an element which is There will be a butt in the center when we have the number of elements, okay and the number of elements, if we talk about one, it is 43321 and 6, how many numbers are we taking out, six, so you say, first of all, we will take the data. Go to the sort card because our media is defined for sorted data, so if we sorted the data then what happened to the data 1 2 3 4 and 6. Now you say how many are the center elements, so we have the number of elements and How many six are there so six by you third index where is zero one you three so one is this element and one center element which is this and by you and n / 2 - 1 6 / 2 3 - 1 2 so and by you and n / 2 - 1 6 / 2 3 - 1 2 so and by you and n / 2 - 1 6 / 2 3 - 1 2 so 0 1 2 So these two elements are in the middle because there are two elements before them and two elements after them so these are center elements so the average of these two is our medium so 3 + 3 / 2 how much? If there is three, then our answer is 3 + 3 / 2 how much? If there is three, then our answer is 3 + 3 / 2 how much? If there is three, then our answer is three. Okay, if there was four then what was the answer? 4 + 3 / 2 3.5 four then what was the answer? 4 + 3 / 2 3.5 four then what was the answer? 4 + 3 / 2 3.5 Okay, so it is just a symbolic thing, so when the number of elements is odd, then what is our median? After N/2 elements which are on the index, we find out the N/2 elements which are on the index, we find out the N/2 elements which are on the index, we find out the median but when we have the data and, okay here we are talking about Heroine Taxi, then when we have the number of elements and, then N. / 2 index + n / elements and, then N. / 2 index + n / elements and, then N. / 2 index + n / 2 - 1 is our average of the elements on the index. If you do 2 - 1 is our average of the elements on the index. If you do 2 - 1 is our average of the elements on the index. If you do this then we will find out our median. Okay, A is off and come on, all of them are the same, so let's discuss the problem once again. So what will we do, we directly submit the organism to Paris, it is a very basic problem, so first of all, what we had to do is to shorten the basic thing, we have to shorten the data, so they dot started by taking the cell, we have done the library function directly here, if you want, anyone. You can also write the algorithm here, but our logic is medium now and we have to discuss one more question, so this time, therefore, I am doing it directly as a library function, so here we will check the size of IF or END N JOIN. Off nara kitna nikal aayega widowed size and if this is odd means n mod tu ki value is equal to one then what do you return then return the middle element then r a t u r n return v of n / 2 and r a t u r n return v of n / 2 and r a t u r n return v of n / 2 and if It doesn't mean that our size is what it is and then what should we return? In the last average of two elements, what index will the two elements have, then the first one will be on N/2 index and where will be the second one, then on N/2 index and where will be the second one, then on N/2 index and where will be the second one, then M/2 index will M/2 index will M/2 index will also be there? So let's just compile and run it once, then it is done and after submitting it, let's see what we had to note. Now let's discuss a little better problem, that is Median of two sorted errors by size first. The thing I would like to say is that whenever you hear these words ' say is that whenever you hear these words ' say is that whenever you hear these words ' Tu Sorted Arrest' then Tu Sorted Arrest' then Tu Sorted Arrest' then what should come in your mind that 95% of all the questions are asked and the 95% of all the questions are asked and the 95% of all the questions are asked and the approach taken in this seems to be 2.2.2 approach 2.2 approach 2.2 approach is ok one. You are three four five and one life is 2468 and 10 and that means how many elements are there in it 54 There are also 5 in this then what is the total number of elements, we have 2 more elements so if we have only one Hey consider Oxides you are here And the number of elements will be always give you enjoy will always be one because if we multiply any of this by tu and let's say the value will remain the same then if we get only one then which is 12 / 2 and 2n by tu Minus is one, then the then which is 12 / 2 and 2n by tu Minus is one, then the then which is 12 / 2 and 2n by tu Minus is one, then the elements of index will be there, it means orphan and text pe and n - 1, the orphan and text pe and n - 1, the orphan and text pe and n - 1, the elements that we will extract, the average of both of them will be our medium. Okay, we have discussed a question earlier also that was merge tu. Sorted RS Okay, so the new one here is ours, what will become one tu three four 123468 and 10, so 123456789 elements are the elements of the last and the middle two elements are 10 means 4 and 4 which are the middle elements here, our So what will be our answer? How much will be the average of both 4 and 4? If only four will be found then this is our answer. So what will we do? We will merge both the RS and just take the average of our two elements which are in the center. If we take it, then we have taken out our median button, we will need extra space in it because we are making a new one, how much is the off size required, so can we do it without space, then we can definitely do it, so let's see how we will do it. That's why we you up tu approach I and K so what are we like this? We just have how many elements are there first. This position was N - 1. So this was the position. are there first. This position was N - 1. So this was the position. are there first. This position was N - 1. So this was the position. So we have first N + 1 elements. It is So we have first N + 1 elements. It is So we have first N + 1 elements. It is starting from zero, right at zero. There is indexing and going up to N, so I have to remove the first N + 1 elements and the remove the first N + 1 elements and the two largest elements of the first N + 1 element are ok, the average of the two largest elements in the first N + 1 is two largest elements of the first N + 1 element are ok, the average of the two largest elements in the first N + 1 is our average. What will be the median, so first there are N + 1 elements to be removed, so first there are N + 1 elements to be removed, so first there are N + 1 elements to be removed, so what will we do to remove them, okay, again let's consider the same 1 2 3 4 5 2 4 6 8 and 10. Okay, so now first N If + 1 element is required then where will we now first N If + 1 element is required then where will we now first N If + 1 element is required then where will we do the towers from i = 0 to i do the towers from i = 0 to i do the towers from i = 0 to i &lt;= n and i plus and in this we need the &lt;= n and i plus and in this we need the &lt;= n and i plus and in this we need the biggest two elements. We name the biggest two elements as max one and max tu. I am writing late because then my A will go in the middle later. Maximum is the largest element till date and Max is the second largest element till now. Okay, so we have to first remove N elements, after that the maximum and max is also the value. The average of both of them will be our medium, so now we will do the drivers one by one, so the value of our first I is here, and J, which is ours, is here. Okay, so which is the smallest element among them, one is so. We will process, we will process the smaller elements, because I want small ambulance elements first and the biggest two elements among them, one is the smallest element, one is the biggest element so far and we will inshallah them -1 -1. Okay, now this I is -1 -1. Okay, now this I is -1 -1. Okay, now this I is ours, it has gone here, now 2 and 2 are from both, so we can expand it any further, we have expanded it further, so it has gone here, now it is okay and you are processed, okay this. A process has been done and this has also become a question, so what is the biggest element so far, you are and what is the second biggest element, which will be the maximum value, first it will be you and one, now you and four. Which is the smallest element, you are, then we will expand it further, so this is what you are, this is processed, so what is the biggest element till now, you are okay, so this new element that comes will always be the biggest till now. If there is a big element, then that one will come here and this one which is tu, that second will become big. Okay, and this one will come here. Number of elements: How many drivers have there been Number of elements: How many drivers have there been Number of elements: How many drivers have there been one or two traversed, only one, two, three elements, we have traveled. Done right one tu and humne karne kitne hain so n + 1 elements means n + 1 so how much is n + 1 elements means n + 1 so how much is n + 1 elements means n + 1 so how much is n 5 so first six limits we have to travel ok so six elements means till 5th index and which are elements on fourth and fifth index And if it is the largest element, then what will be their average, then what will be the next element? If the smallest element in three and four is three, then process three, then the largest element so far has become three and what is the second largest element? You and I have done it. Right now, if it is from tax and tax, then we can expand it any further. Okay, so four is the biggest element till now, what is four, what is the second biggest element, its value will be A, three, okay, number of elements. How many drivers are there? One, two, three, we become five and one, we have to travel, so what is the smallest element? If we make four, then if we make four the driver, then the biggest element becomes 4, and the second biggest element becomes 4. Okay, now what is our number of elements? Towers are done, one, two, three, five, six and how many more we have to do. If we have to do 6 elements, then six are our tires and till now what is the value of maximum. 4 and 4, so just the average of these two will be ours, so one. Let us also see the code, so we have to live on the same page below in the DMG, so we understand this code. Okay, so this is the code, so it came here and whatever happened, our 2.2 was counted. happened, our 2.2 was counted. happened, our 2.2 was counted. How many elements have we driven till now, how many elements do we have to drive, N + 1 is fine and what is m1 m2 then m1 is the + 1 is fine and what is m1 m2 then m1 is the + 1 is fine and what is m1 m2 then m1 is the largest element and m2 is not the largest element till now, here it is the reverse considering m2 as the largest element. And m1 is the second element. It is visible from here. Let us see that now the count is from zero to n. From zero to n means n + 1 elements, so n means n + 1 elements, so n means n + 1 elements, so all the drivers we had to do have been done and n + 1 more. The value in m2 will be our median, n + 1 more. The value in m2 will be our median, n + 1 more. The value in m2 will be our median, so if you reach the other instance equal to n, that is, what does it mean that the elements that we have from first zero to n - 1 are that the elements that we have from first zero to n - 1 are that the elements that we have from first zero to n - 1 are all reduced to one element, which means one. Secondly, completely small was completely small, what does it mean, like our value of n is 3, suppose our value of n is something like this, one, two, three and four, five, six, so the first one which comes in increment will be here, then when here, a will be given. So how will the largest element become the start element of the next element? The start element of the next element will come and the one which belonged to Arya One will be extinguished so it will become the biggest element. The next element will become the first element and In the value of m1 in m2, you i means the second big element is equal to n similarly, then it means it is right, it has been reversed, oh one, I have done the instance. If it is not like this ever, then the smaller element is added to it, then i is. Incremented, m1 is the second largest element, so in m1, the value of m2 is added and what is m2, what will be the largest element so far which we drive, if we drive the smaller element then it is one. Similarly, if K is small, then K will go into it and K will be pointed and in the end we will return the average of our m1 m2 values, so this was the problem, I hope you who like the video and understood approach, I will give you a I will also give the link of the question in the description. You can check out from there. Thank you.
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
1,920
the code 1920 build array from permutation in JavaScript this is a tricky question but it's not that hard once you understand it given a zero-based permutation nums given a zero-based permutation nums given a zero-based permutation nums right there it's already bad given an array nums build an array ands of the same length where anzi equals nums at num's eye for each zero less than or equal to I less than nums.length less than nums.length less than nums.length I don't know what the hell that means a zero-based permutation nums is an array zero-based permutation nums is an array zero-based permutation nums is an array of distinct integers from zero to nums.length minus one inclusive that's nums.length minus one inclusive that's nums.length minus one inclusive that's helpful distinct integers means each integer is unique that's what they want an array of unique integers from zero to numbs.length minus integers from zero to numbs.length minus integers from zero to numbs.length minus one inclusive that means that every number in here is different from every other number each number is unique and it begins zero and the last number in there is nums.length minus one so essentially nums.length minus one so essentially nums.length minus one so essentially we've taken every index and shuffled it within this array in some manner now the shuffling could be all in order or it could be out of order could be in any order but they're all in here starts at zero it goes to numbers.length starts at zero it goes to numbers.length starts at zero it goes to numbers.length minus one and what they want is this ANZ I equals nums at nums I so to think through this I've got the nums array here from example one uh and it's a length of six got zero through five just as expected from a length six array Anne's I is equal to nums at nums I so Anne's I if I is zero and zero is going to be let's see what's num's eye numbs zero is zero numbs at num's eye is also zero so this gets to zero and then we get the zero property of nums which is also zero let's copy that and we'll just replace it okay and one is going to be nums one sorry nums at nums one and that's going to be let's see nums at no at nums one is two nums two is one and two is going to be nums so we get nums two zero one two that's one okay nums at one is two and three is going to be nums at nums three numbers three is five numbs five is zero one two three four five is four obviously it's a six length array the last one is index five that's the last one and four zero one two three four is going to be nums at nums four numbers four is three nums three is five and five is going to be nums at nums 5. which is four sorry zero one two three nums at nums five four nums at nums four is three it's easy to get confused on this one because you have to think twice on nums not num's eye numbs at num's eye and then we get into the loop and that's all it is in this Loop and I equals nums at num's eye just as it says in the description after they've confused you with this bad wording a zero-based permutation wording a zero-based permutation wording a zero-based permutation zero-based permutation is zero-based permutation is zero-based permutation is of nums and what they really want is an array and then describe what's in that array in the second paragraph versus what they did here which is trying to halfway describe it here and then halfway describe it here but a little better in the second paragraph but not really explaining that nums is an array of the same length which they did but and they confuse you with each eye equals zero less than numps at length and return it which doesn't explain what the data is okay so we start out in strict mode we get the length of the array we create a new array with that length that makes things a little bit faster because every time a property is assigned to an array a numeric property is given to an array if the numeric property is greater than the length of the array then the length of the array is modified and then JavaScript must consider whether it has to implement a larger array to represent that behind the scenes so that we have maybe some array implemented in some a faster language not JavaScript so that's how the implementation has to work it's not all interpreted so um we create an array and we assign it the length because they're going to be of the same length as stated in the description uh and then we Loop through them and then we return the answer and that's it thanks for watching
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
328
Sooner Length Mark I Plane More Children Dance *With Devgan Not Children Dance *With Devgan Not Children Dance *With Devgan Not Interesting Network Problem Special And De Villiers Software Going To Invest And What Is Subscribe Vidron It's Okay No Problem Yes-Yes Video Link Not Understand What You Can See Hidden Something Like This Benefit Subscribe And Subscribe Amazon TabIndex Of Bomb Basically Phase And Half Will Give In Chronic Last Year Something Like This A Great Something Like Share And Subscribe Do Subscribe 90999 Computer Notes Adjective In Node You A System Where Even Notice Adheen Na Som Will Have To Reduce Something Like Subscribe And Subscribe Solving Problems Very Easy Withdraw It's Something Like This And Fun Health Benefits Tree To Keep The Indian Adhir What Like Share Subscribe 45 Lord Hardinge Aksar Index Asar 138 500 Ko Cut Something Like This And Water Even Indexes To For that in the middle and head between to return this and ok but one thing that you have to keep in mind that no relation with this problem will be decided not to withdraw cases will have to do something like this is or null and held on the Water going when going to create wave all song 2018 point to the point to avoid next point is point next of the next 9 next point next of the next 9 news room that roadways point more than 17.82 that roadways point more than 17.82 that roadways point more than 17.82 request after defeating were this vansh MP3 which alarms pe ok to that And Events Something Like This Point Something Like This And When Something Like This How To The Fourth Done Or Over The World To Keep In Mind The Middle And Creating A Creative World Subscribe To The Channel Button To Point Hai And Head Here Hear Me To Point Blast At Last Not Disturbed Point And Subscribe To The Channel Now To Receive New Updates Subscribe And Share Subscribe And Subscribe Not Quite Amused To Avoid Them Dot Next Pin More Point The Order Of Arts Agri Vid Me Dub Skin Alone Appointed To These Robbers subscribe and subscribe point up and go appointment next to on in president mirwaiz vidron it's not subscribe to that reason were not even going to user experience in this clip question is pet ameer and not go into details and servi seervi subscribe Video Channel And subscribe The Amazing is that a
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
389
hi all welcome to learn code repeat so today we will be looking at the day 24 of the september lead code challenge the name of the problem is find the difference let's look into the problem so the problem says given to string s and t which consists of any lower case shrink t is generated by randomly shuffling string s and then add one more letter at a random position find the letter that was added in t so they are given a string s with some letters answering t and they have mentioned that all the letters will be lower case later so the both s and t contains only lowercase letter and t will have only one additional letter which is not there in s so we have to find that additional letter so this is one of the easy category problem which can be solved simply using a hash table like a hash map or we can also have a array because they have mentioned that it's only lowercase letter so there will be only 26 letters right so we can build the frequency for this s we can go over this as once build the frequency of the letters in s and we can go over the characters in string t and we can reduce the frequency in the table if it exists and if it doesn't exist then add that frequency and then we can go over the table again and check whatever index position doesn't have value as 0 right that is the character which is additional so we can do it that way so that approach will take off and time to go over the array and it will take additional of n space because we have to maintain that array right so the space will be we are using 26 characters so it will be kind of a constant space however it can also be solved without using that additional character array right so let's see how we can solve that so we can use here xor so if you remember the properties of xor a will always be equal to zero okay so for example one xor zero is one if it is two different digits then it will be one similarly if it is a zero x or one it will be 1 but if it is 0 xor 0 it will be 0 okay and similarly if it is 1 x or 1 it will be 0 okay so if it is same digits then it will be zero if it is different digits then it will be one okay so we can use that same logic here so we go over the string s and xor each character then we go a string t and xor the characters again right so eventually a will cancel a b will cancel b c will cancel c d will cancel d and at the end will only have e okay so let's do that here so i'll declare one int variable for end i in s dot to care alright or let's call it ch this is my character so i'm doing a xor so c equal to c xor ch similarly i'll go over the characters in t okay i am keeping the same c variable i have declared it here end because it will convert the s dot to care array it will convert the ch to int and it will do the xor i am using the same variable to store the xor value here also i am using the same variable to store the xor value so first i am going through the character array of s then i am going through the character of t the xor operation i am storing it in the same variable c so at the end c will only have the additional character the rest of the characters will cancel each other okay so i can return here pair of c okay so this should give us the answer so let's submit and the answer is accepted that's it for this video if you like the video please hit the like button and do subscribe to this channel for future such videos thank you
Find the Difference
find-the-difference
You are given two strings `s` and `t`. String `t` is generated by random shuffling string `s` and then add one more letter at a random position. Return the letter that was added to `t`. **Example 1:** **Input:** s = "abcd ", t = "abcde " **Output:** "e " **Explanation:** 'e' is the letter that was added. **Example 2:** **Input:** s = " ", t = "y " **Output:** "y " **Constraints:** * `0 <= s.length <= 1000` * `t.length == s.length + 1` * `s` and `t` consist of lowercase English letters.
null
Hash Table,String,Bit Manipulation,Sorting
Easy
136
10
in this video I'm going to talk about a coding interview ocean in regular expression massing here is the problem statement given an input string edge and pattern P implement a regular expression massing with support dot and asterisk here dot means message any single character asterisk means massive zero or more of the preceding character that means masses zero or more character that we have before asterisk the massing should be covered the inter input string not partial string is can be empty and contained only lowercase character a turgid peak be empty and contains only lowercase character a to jet and characters like dot or asterisk now let's look at some examples we already saw this right dot means message and a single character asterisk means as it's zero or more of the character that we have before pattern here we have on the left side pattern and on the right side string and for pattern a each message only the string a and it doesn't match a b or AAA and for a dot P it message a c b a b ax b but it doesn't match a b y ba how does this match work here dot means any single character we have door in between a and B so we can have any single character in between a and P here we have C in between a and B here we have B in between a and B and here we have X in between a and B so this three string passage the pattern now for this part on a asterisk B it's match B a B eh-eh-eh-eh be but it doesn't match a eh-eh-eh-eh be but it doesn't match a eh-eh-eh-eh be but it doesn't match a our SE b or adb how does this work asterisk mint masses zero or more of the preceding character we have the preceding character here err right it's saying that here mass is zero or more of this character a so here we have B so here we see a appears zero times so it's true then we have a B then B appears dealer or more here we see a appears once so it's true and for districts a appears twice so it's also two and for this string a appears four times so it also true but for this stinks this pattern doesn't match then we have a dot asterisk match old string right every string here we have a BB D DCG whatever sting we have it will match everything now to see how does this work we know that dot means any single character right and asterisk mean zero or more of the preceding character here we have proceed character dot so dot means any single character and dot can be 0 times or more times here we have dot asterisk and for this a B &amp; B a we dot asterisk and for this a B &amp; B a we dot asterisk and for this a B &amp; B a we have to dot because dot can be 0 times or more times whenever we see asterisk after dot now this dot match the first a and this dot match this B so it a match B a so here this first dirt match B and the second dot match a and dot mint any single character alright and we take here 6.4 this scheme here 6.4 this scheme here 6.4 this scheme bb/d CC and the first taught match be bb/d CC and the first taught match be bb/d CC and the first taught match be second dot match the third dot match this G fourth dot mass this D peeped dot match this C and six dot mass this XI so it's a match right frankly speaking dirt as to catch everything and here how it work right and here C asterisk yesterday's can be each match CB because C Qian appears times or more times a can appears zero time times here we see C appears once and a appears zero times and B here we have at the end so it's match be for the string C and a appears zero times and here C a B C and a appears once and for this string C appear straight a appears to eight and we must need to have be at the end and it's match but CL it's not met because we should have at the end b a b so it's not match we should have at the end B and here we have a right but this is not a match because we have here be C X a B here it mass this C at the end we have B but in between C and B we have X and a so this is your unmet and for the last pulse a asterisk B dot asterisk y here we have B oi it's a match why here in the strings it appears zero times and B appears once and dot asterisk means gear times or more times AB dirt so in this case 0 x dot that means nothing so B 1 its match a be oh I hear a appears once then we have B then we have Y and dot after disc as you know dot asterisk it can matter everything or nothing then we have a ap why they appear Stites didn't have big and we have here why here we have a why this is unmatched because we must need to have B and or at the end and also a at B and also this thing is not a match alright now I think you understood how this match works alright now write a function is underscore match that takes a string and a pattern as input and this function should return true orphans if the pattern matches the strings then this function should return true if the pattern does not match the strings then it should return false these function calls should return true because pattern message the skins so it should return true this function calls should return true also because this pattern message the string and for this function calls we should return false because this pattern does not match this straight alright now I'm going to solve this problem using dynamic programming here's how my solution might look likes first I'm going to declare a function is underscore match that takes a string and pattern then we're going to construct a dynamic programming table and here we have is dot length plus 1 and P dot length plus point if we consider a dot s 2 this could be a pattern and a X Y be its string then the dynamic programming table will look like this ok this is our table T now here we have empty string and here we have empty string right empty pattern and empty string is a match so we will put here T deport true by default when you created this 2d array we have valid for all the box faults and will represent if as a fault okay and here we have T zero equals to two because M pristine and empty string is a match then we're going to take E and empty string so a and empty string is not met so here we'll put F then a dot and empty string and a dot and empty string is not a match so here we'll also insert yep then we're gonna run a loop and the loop we used only for this type of pattern we have this fall of only for the patterns that can be matched with empty string so when we encountered asterisk we'll check that in this for loop here for i from 1 to 2 T 0 dot lint and this is the length of the column right 1 2 3 4 5 and here 5 so it will run from 1 to 4 if P I minus 1 equals 2 asterisk for first iterations its points to a right and a is not asterisk and for second iteration it will points to dot so dot is not an asterisk then it will point to 3 and here 3 my h1 equals to 2 so 0 1 2 and here we see asterisk right then this condition is true here t 0 i t 0 so this it this is the row and i equals to 3 in the sketch so 0 1 2 3 and here it will copy whatever we have in here and that is if and 0 3 minus 2 1 so here this is row 0 and 3 minus 2 1 0 1 so that is f so it will copy if over here and then a dot asterisk B and interesting and that is not a match so here we'll have if ok and for this column will have if right here if we this or valor or false because my pattern and a will not match so this is false empty pattern and ax will not match in the pattern and a XY will not match in the pattern and ax y B will not match so all the Velo are false now let's populate value for the rest of the box ok here we're going to run a loop for i from 1 to t dot length minus 1 and this is the length of the road right 0 1 2 3 4 and here we have length 1 2 3 4 5 - point for this for loop will 1 2 3 4 5 - point for this for loop will 1 2 3 4 5 - point for this for loop will run from point 2 4 then we have another for loop for i from 1 to 2 and 2 t 0 dot length - point and this it the length of length - point and this it the length of length - point and this it the length of our columns and that is also 5 and 5 minutes 1 4 so this loop also will run from 1 to 4 ok and this to loop will iterate through until we get to this box now let's see how we can calculate the value for the rest of the boxes first I equals to 1 and J equals to 1 okay so here we have P 1 minus 1 equals to 0 and at tadaryl we don't have dirt so this is false then PJ minus 1 and 1 minus 1 is 0 so it's points to a and here it's I minus 1 I go through 1 right so it's 0 a and a is match right so if we have a match between a and a then we have like this a and a right and this is a pattern and this is your string so we see we have a mass here a and a so we can just remove both of them then we'll have empty string right then we'll copy or rehab am listing vs. empty string and here we have tea and we are going to just copy this tree right over here alright and this is the exact formula to copy this value from here to here then we have dots right and for the next iteration the value of G will be 2 and here PT minus 1 and this is 1 right and 0 1 and that is equals to dot so this condition is true then it'll goes to this line tij so 1 2 this is 1 and 0 1 2 here and here the value we will have if right and here the value will have if now let me clarify this how this actually works okay a door and a right and this dot match it is so we can just remove this dot and this a then we have a and empty string so a and M testing for a and interesting we have here if so we just copied this right over here okay for the next iteration the value of J equals to 3 and this is not match ok so then it will goes to this L tips part here we happy J minus 1 and that is 3 minus 1 is 2 and that is equal to asterisk so this condition is true since this condition is true here how we can calculate the value for this here we can get the value whatever value we have right over here T and we can just copy that here and this is the exact formula to copy develop from here and let me clarify how this actually works we have here a dot asterisk and we have here a now with the Dorton asterisk ok so here if this door and asterisk and may have do occurrence so we can just remove it then whatever value we have for a and a here for a and a we have T so we can copy T from here to here alright if we have Gia minus 2 equals 2 dot ok so here J minus 2 and here we have 3 minus 2 equals to 1 right 1 for pattern 0 1 we have dot right and this condition is true since this condition is true then this court will run this voluma be overridden right here who do you have so T idea whatever well that we have T and then we have your TI minus one so it will go off and it will just copy whatever value we have here so T true or false and that is equivalent to true so here we have two right now for the next iteration the value of G will be 4 right for J equals to 4 this is false and this is false so it will directly insert your faults now for the next iteration of this fall of the value of I will be 2 then it will point to this row okay and then whenever we have J equals to 1 ok so then here we see ya and X and this bit not a match if this is not a match then we'll have here directly false and here directly AB if and this part will run for that we have this value F here and then for the next iteration of jail we have dot and X so here this is a match and tij now let's calculate the value for this box okay so here TI minus 1 so it will go off and D minus 1 and R equals to 2 so it should be 1 so 0 1 whatever value we have here we have your T now let me clarify how this actually works we have pattern e and dot right and we have string a and X and here dot and X match right so we can just remove this because don't met any single character and we have here a and a so for a and here we have your T so we can copy whatever value we have in this box so we have your key so we copied here T all right and for the next iteration J we have here asterisk right and asterisk and X here it comes to this line here whenever we have this condition set then you the it will stay on this same line and it will go back do minus 3 so 1 0 1 it will copy whatever value we have at this position F so if now since this condition is true we have J minus 2 that means 3 minus 2 1 do you know what equals to dot since you have here dot then this condition will run right so we have already here false it will go off and then we have T I minus 1 so it's go up and Jay calls 2 3 so 0 1 2 3 and then fault or 2 equals to true so here this value should be true now for the next iteration of J then we have V and X and this is not a match so here we should have faults alright so for the next iteration of I little points to this row and J equals to 1 it will point right here so here you see a Android that is not a matte so here we have if then for next iteration of J we have a dot here right so here dot then we need to copy whatever value we have so let's calculate that I minus 1 so this it 3-2 calculate that I minus 1 so this it 3-2 calculate that I minus 1 so this it 3-2 so it's go up then J minus 1 so 2 minus 1 is 1 and here 0 1 whatever value we have here it just copied over here how this actually works now lets me clarify that we have here a and zort and a ex-boy so dot can match why right don't ex-boy so dot can match why right don't ex-boy so dot can match why right don't kill match so we can remove dot and boy then we need to match a and X and for a and X we have here if so we can just copied that right over here and for the next iteration of J we have your asterisk right and Europe asterisk and then we have to go back here we have forts right so it will copy just fault right over here since J minus 2 and that is P 1 and that is dot since this is dot then we're going to go off and get the value whatever value we have here we have your T so here the value should be T because if or T false or true is equal to true for that next iteration of J we have value for and it'll point here and B and a is not a match so here we should have if then for next iteration of I in the next iteration the value of I is 4 and it's points to this last row so here this Joe Vella is points to this box and here a and B is not a match so here we can have directly if then we have here dot and B so this is a match so let's go to F here and here we have faults so just copy the value away then you have your asterisk right if we have here asterisk then we're going to go back here and here we have if to just copy it over here since the value of G minus 2 these equals to dot since this value is equal to dot then it's going to copy the value whatever we have in the top here T so it will copy T right over here now let me clarify that how this actually works so we have your air dot asterisk and here we have a X Y B so here dot asterisk so it match with B so we can just remove B as the part of it then we have a X Y and a dot asterisk so for a dot asterisk and for a X Y we have the value of T so we can just copy the develop right over here how simple is that then for the next iteration we have here BN to be equal so this part will run so we'll just copy whatever well we have here so here we should have T and at the end we're going to return is dot length and that is 4 and P dot length that is 4 so 4 and 4 so this value since you have 2 here since you have two here that means this pattern matches with the strings and this solution takes space complexity bigger of n m4 n is the length of string and M is the length of pattern to construct this dynamic programming table and the time complexity for the solution is bigger of nm her n the length of the screen and M is the length of the pattern alright guys I think you have a clear understanding on this problem regular expression massing if you have any doubt if you have any questions let me know I'll be glad to help if you like this video if you want to get more video like this make sure you subscribe to the channel thanks for watching this video I'll see you in the next one bye
Regular Expression Matching
regular-expression-matching
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: * `'.'` Matches any single character.​​​​ * `'*'` Matches zero or more of the preceding element. The matching should cover the **entire** input string (not partial). **Example 1:** **Input:** s = "aa ", p = "a " **Output:** false **Explanation:** "a " does not match the entire string "aa ". **Example 2:** **Input:** s = "aa ", p = "a\* " **Output:** true **Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ". **Example 3:** **Input:** s = "ab ", p = ".\* " **Output:** true **Explanation:** ".\* " means "zero or more (\*) of any character (.) ". **Constraints:** * `1 <= s.length <= 20` * `1 <= p.length <= 20` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'.'`, and `'*'`. * It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.
null
String,Dynamic Programming,Recursion
Hard
44
72
you guys let's do this every second problem at least or add existing giving to work toward one and what to find the maximum minimum number that is why some words one to work to you'll have the Pollux we operate informative on a world in search of collectibility collector and replace a collector so you have to understand one thing but these are the operation is actually a step so we have to crack these operations so for this we are going to use another program bang and have a to the matrix to be a new word one got Lenny / 1 + 1 2 dot new word one got Lenny / 1 + 1 2 dot new word one got Lenny / 1 + 1 2 dot length + 1 length + 1 length + 1 once we are back we will have it complicated of course so and high is equal to 0 why smaller than equal to 4 1 the highest / / what we have to do is we highest / / what we have to do is we highest / / what we have to do is we have to initialize our Sonic program our array so we distinct about it when we take none of the characters from wordless - from the second word then wordless - from the second word then wordless - from the second word then we have all we have to perform as many delete operations as they are corrected so connected in word one so that's why what we are going to do we are going to make vp add that you know word one from a zero similarly for what - if I choose a zero similarly for what - if I choose a zero similarly for what - if I choose no character form for one my work - will no character form for one my work - will no character form for one my work - will require reinforce poi to match it requires I delete operations now the first search that is in I is equal to 1 I is less than equal to word one dot length i slash and for in J equal to 1 J is smaller than or equal to dot length C flash match if not in word 1 dot character at I minus 1 is equal 1 if equal work - darlin I'm sorry not equal work - darlin I'm sorry not equal work - darlin I'm sorry not effective at gay - 1 then we have a effective at gay - 1 then we have a effective at gay - 1 then we have a match we don't have to you know do either insert delete the reflux so we'll just do bc i J like is equal to TB I minus 1 and J minus 1 ok else TP hi my I and J equal match got many DP I minus 1 J minus 1 fallen sir so now this is for an insert Matt's got me I'm D P I and J minus 1 this is for the place and DP I minus 1 J minus 1 8 for a week and then slash one Falls of course operation and we said of the can be played up with you yes and then we just learned if you returned VP of words one got many and word 2 dot length okay it looks good let's run this look at this works to submit the code okay I have another where might the probably line 8 okay oh I'm sorry 33 series but - now okay oh I'm sorry 33 series but - now okay oh I'm sorry 33 series but - now let's go again okay accept it thank you guys thanks for watching
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
1,814
so hello everyone welcome to this new video and in this video i will be explaining the problem count nice pairs in an area so this problem is a little bit easier than medium um because the only difficult tricky part in this is to observe what is actually happening and then if once you get to know that what is happening then to solve this it will be pretty easy so in this video i will be explaining this problem through an example and then the idea to solve this problem and then i will be coding it so what the problem is basically saying is that i have been given an array and i have to do reverse of each element and it should satisfy these two conditions so i is less than j and nums i plus rev numbers j is equal to num j plus reverse of num i so like if you observe this it will look to you something like this for example if this is the nums array its reverse will look like this so 13's reverse will become 31 10 will become 1 50 35 will become 53 24 will become 42 and 76 will be 67 uh 67 so what you have to do here is that like you if you just write it down spend a little time with it you will see that okay i have been given this statement num psi plus reverse of nums j is equal to nums j plus reverse i you can transform this uh like statement into this nums i minus reverse of num size so that i have control uh total control over the left side and the right side like i know what is on the left side and right side so like if you do this uh what you will uh if you do this over an array and calculate the difference so this is basically num psi minus reverse of num psi so you can just write it down here so like if you reverse it you will guess that it is minus 18 from 10 minus 1 is 9 here it is minus 18 and 9 i think now it will be super clear to you and if it is super clear to you please subscribe the channel uh if you like my videos uh but anyway let's go forward uh so if you have now received the difference of the reverse and like the original number so now it is pretty simple what you have to do is that like how uh see how many of them are equal so you can easily do it this by using a map and you have to start from the like right side because you have to take care of this condition also i is less than j so for example you will start from 9 and you will see in the map hey is there anyone 9 here so you will get answered no there is no 9 then you will add this 9 into the map then you will come to minus 18 there won't be any similar one ahead of like -18 like -18 like -18 then you will come here you after coming here you will see okay there one minus 18 exists so you will increase your nice pair by one and here you will see that one nine exists so you will also increase your nine uh my nice pairs by one and then you will come here you will see that there are actually two minus 18s on the right side so you will add two to it so total nice first will be four so i think i am super clear to you now then coding it was not that difficult and okay so i will just code it now so once again like if you enjoy my videos like if my explanations are clear to you please subscribe the channel because a lot of my viewers are not subscribed so let's uh code it so let's first write in n is equal to num dot size not exactly necessary but it uh anyway uh then what i will do is that since in this problem it has been said that the number can be pretty large so i have to use a modulo so i will just write the modulo here into m is equal to what one e nine plus seven uh one in nine plus one e9 is basically ten is to power nine then i will uh write another variable called let's say res this is actually the number of nice pairs res is equal to zero now i will make an ordered map an ordered underscore map sorry map int mp so this will store the count of the what these differences uh then what i will do is that for i will start the for loop from right side so for int i is equal to 0 i sorry i is equal to n minus 1 i greater than equal to 0 i minus and then what i will do is that i will calculate the difference so in int difference is equal to what difference is num psi minus reverse of nums i so here i have not i will make a reverse function that function what that function will do is that it will reverse the num's i for example if the number is 76 it will return me 67 so for that i will write a separate function so let's write that function quickly it is a simple problem uh like simple statement so int what num so to get the reverse so in i will just write another variable in trav okay so interest is equal to initially zero then i will write a while loop so while uh num then what will happen is that ref will become rev into 10 plus what uh plus num percent 10 so i won't be explaining this you can just like write it down see uh do a dry run yourself you will realize that why i am writing it so this is a pretty standard way to reverse the any an integer and then num will become what num by 10 and in the end i will return rev so now i have got my reverse so after getting reverse what i will do is that i will check my map so if mp dot count so i will check if uh there exist this difference already exist in the map or not so if mp.diff is equal to true that is that mp.diff is equal to true that is that mp.diff is equal to true that is that the difference exists in the map then what i will do is that i will increase my res count so res is equal to what res plus mp difference uh and then i will also take a modulo of it from m so now i will add the like the numbers that are already present for example in this case minus 18 i will add the count of minus 18 that is equal to 2 so like this i am increasing my result and in the end i will uh so after every like iteration what i will do is that i will increase the count of that like that difference in my map and in the end i will return res so i think that should work now let's submit let's uh like do a uh what let's compile it hope i have not made any syntax errors so it is working fine it should submit so well it got accepted twenty percent faster than all solutions hundred percent beats in memory so i think this is a pretty easy problem or not much to explain so if you like this video please consider subscribing the channel and thank you and have a nice day bye now
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
1,947
uh this question is maximum capability score sum so you can rest through it so whatever you got you know your student array um array should be the sest uh your Mentor or almost the same to get a higher score because you want to return maximum score right so I'm going to useing the example one and you should be St for enough so this is 110 and then if you look at this oh this is 11 Z right so they are match so every single value over here are match so you got a score of three uh I'm going to skip this one because there's no Mentor uh is you know one but there's Mentor is z one right so I'm consider score three because every element are the same uh so this one will definitely match with this one for the last one you know and one1 and this is 1 Z 0 and only two element are the same so it's score of through so if you add it's going to be 3 two uh 3 + 2 + three right so it's two uh 3 + 2 + three right so it's two uh 3 + 2 + three right so it's eight so in this question you are definitely going to use DFS and back Tru so you're going to Traverse all of the possibility right and to see oh which one is going to be the maximum so once you know once you match you know the rest of thing should you know try for others right something like this right so let's look at this so if this one will definitely select one of them right so it's going to be un possibility right how about this uh if this one is selected right that only two which is a minus one possibility and this is going to be a minus two and then you know and so on until one right so it's going to be un factorial combination but this doesn't mean there are uh the time complexity is in so let's talk about how we do it so we need to recall the result right and also we need to know which one um do we visit right so our visit is going to be represent the size of uh a l so we're talking about student right and result will be zero so I'm going using datas so I'm passing the students I pass in the index for student I pass in the mentors I pass in the mentor index and I'm going to return result right so public voice DFS and then in students and in s index all right in to the array Mentor in M all right anyway doesn't matter all right if the S so we started from zero right if the index is actually um reach the student array it's going to be what it's going to be the last one right so it's going to be result equal to Max either this one and this shouldn't be the and because my mentor I'm traversing The Mentor in the DFS so this should be a score me the you know I have typo and also I say wrong so I have to compare either result or score right and I want to return right away because this is the last index all right let's look at this so I traversing from all the way from zero doesn't matter is you know um which index we have been using but start from zero and all the way to Mentor sub. lens and i++ so I'm you know I'm uh explaining i++ so I'm you know I'm uh explaining i++ so I'm you know I'm uh explaining this again s index represent student I index represent Mentor so you will definitely match right so if I if my mentor index has been visit right visit I has been visit we don't want to reuse it so we'll continue and now there is something that we didn't use so we just make sure we assign equal to true and also for the backdrop we assign equal to false but before we backr we need to call DFS so student is going to be here right and s is going be represent s+ one right and s is going be represent s+ one right and s is going be represent s+ one right and then our Mentor does not change and our current score will plus the score between what the student array and the mentor array so what is the student Ray it's going to be represent what s uh sorry student s right and then I need to add come on so I need to guess score using two you know argument as a input so I need to pass in the mentor say I and also students so yeah this will be it so I'm going to say public in get score between the student array uh student and also the mentor array right so in this one I'm just comparing right and now return result so how do I compare something from the beginning all the way to the end and then result plus equal if they are the same right student I equal to Mentor I and if same plus equal one L zero so this will be the solution hopefully I don't have any type of uh students and S where is my S oh s is represen IND this student. length and S is a index yeah this would be it oh student all right okay cool so um again this question is a little bit challenge so let's think about time and space so again we talk about the M factorial right so M factorial we matchine but we have a full loop right so it's going to be M factorial times all of M right all of M for the mentor right you always starting you always Traverse your Mentor starting from the beginning to match your student uh subar right so uh all of um maybe it would be better if I just paste all right so um this is my time and space complexity so it's going to be all of n time n factorial time n represent L of string s student and represent L of mentors and all of n represent the student right this is the time and space all right so if a Solutions are different than mine and better explanation on the complexity let me know and I'll see you later bye
Maximum Compatibility Score Sum
number-of-different-subsequences-gcds
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]` is an integer array that contains the answers of the `ith` student (**0-indexed**). The answers of the mentors are represented by a 2D integer array `mentors` where `mentors[j]` is an integer array that contains the answers of the `jth` mentor (**0-indexed**). Each student will be assigned to **one** mentor, and each mentor will have **one** student assigned to them. The **compatibility score** of a student-mentor pair is the number of answers that are the same for both the student and the mentor. * For example, if the student's answers were `[1, 0, 1]` and the mentor's answers were `[0, 0, 1]`, then their compatibility score is 2 because only the second and the third answers are the same. You are tasked with finding the optimal student-mentor pairings to **maximize** the **sum of the compatibility scores**. Given `students` and `mentors`, return _the **maximum compatibility score sum** that can be achieved._ **Example 1:** **Input:** students = \[\[1,1,0\],\[1,0,1\],\[0,0,1\]\], mentors = \[\[1,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 8 **Explanation:** We assign students to mentors in the following way: - student 0 to mentor 2 with a compatibility score of 3. - student 1 to mentor 0 with a compatibility score of 2. - student 2 to mentor 1 with a compatibility score of 3. The compatibility score sum is 3 + 2 + 3 = 8. **Example 2:** **Input:** students = \[\[0,0\],\[0,0\],\[0,0\]\], mentors = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 0 **Explanation:** The compatibility score of any student-mentor pair is 0. **Constraints:** * `m == students.length == mentors.length` * `n == students[i].length == mentors[j].length` * `1 <= m, n <= 8` * `students[i][k]` is either `0` or `1`. * `mentors[j][k]` is either `0` or `1`.
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a valid subsequence for x , then the subsequence that contains all multiples of x is a valid one too. Iterate on all possiblex from 1 to 10^5, and check if there is a valid subsequence for x.
Array,Math,Counting,Number Theory
Hard
2106
1,851
hey everyone welcome to my channel so in this video i'm going to try to solve this problem do some left coding work at the same time i'm going to try to follow the general interview steps while trying to solve this problem so let's get started so first of all we are going to try to go through this question and get a good understanding about it think about some ash cases uh and ask some good questions if there is anything unclear so you're given a 2d integer array intervals where the integral i is represented by a pair of numbers it is going to be the left and the right so this represents the interval and it has an inclusive interval the size of an interval is defined as the number of the integer it contains or it could just be right minus 5 plus 1. so you also you're also given an integer requires so the answer to j score is the size of the smallest interval such that the query number is within the interval if no such interval exists then we are going to return the answer as minus one so let's say so return an array containing the answer to the queries let's say for this intervals and the queries uh we are going to return this kind of array so the first number is three that is because for number two the smallest interval containing two is this one which is two four and the length of it is uh three all right so let's see the constraints so the concern says the quarry lens and the uh interval lens both are within one to a hundred k so no empty arrays that's a good thing we don't need to consider that kind of last case like empty anti-input and like empty anti-input and like empty anti-input and each uh each interval is represented by a pair of numbers left and right is anywhere between 1 to 10 million quarry number is between 1 to 10 million as well so having said that let's uh think about how to solve this problem so the first idea to solve this problem is a profile solution what we could do is actually like a two layer of the for loop uh for each of the query number we go through every intervals try to find the smallest interval containing the current query number we are trying to find the answer for so for this one the runtime of course it is going to be l and m so let's say n is the length of the interval array m as the length of the queries array so proof of solution o m of course uh so there should be a better solution regarding the runtime so let's see let's say we have like a smarter way to solve this problem for this kind of problem uh for this array problem one intuitive idea is we are going to solve we are going to do some sorting on top of it so that so we can uh leverage the other number uh to save some runtime so let's say we are going to first sort the intervals and the queries so um for we are going to sort the intervals and queries from the smallest to the largest which means yes any other and for the intervals it is going to be based on the left number and then after the sorting what are you going to do for the next step so what we are going to do for the next step of course still let's say we are going to go through each of the number each of the query number to find the corresponding answer within the intervals so currently because the query number and the interval numbers are both sorted this means we are going to go through the current number from the smallest to the largest so for each of the query number we are going to generate a candidate list for it so let's say we are going to have a candidate list for it by going through the intervals so here what we could do is uh we are going to let's say we are going to have like an index so the index is the index within the intervals array so i'm going to explain why we keep this index here uh and why it is going to save us some runtime so while the interval uh index and zero this is right now this is the left number for the current interval yeah interval well it is smaller or equal to the query number then it means uh this could be a potentially a candidate list so let's say we have a candidate list here i'll decide what is a uh what is the data structure for this candid list so what we are going to do is we are going to insert to the candidate list so after this while loop it means either we go through all of the intervals or the query is actually uh smaller than the interval uh the left number for the current interval which means we already um we are currently at the interval that is to the right of the current query number so after that we need to go through the candidate list to try to find the final answer so that's the juicy part for this uh which is a major part for this solution so if you keep the candidate list like for example let's say we have this as an array or a list then it's actually pretty much the same thing as the profile solution so here what we are going to do is we are going to make it as a manhattan or in java it is implemented as priority queue so for this main heap what we are going to do is we are going to keep two things the first thing is the length of the interval or maybe let's say interval less and the next thing is the right number within the interval so the mean here is going to be sorted based on the length of the interval of course here what we are going to do is we are going to go through the candidate list so well the right number is smaller than the query which means this for this candidate is not actually the answer we are trying to look for so while the right is smaller than the quarry then we are just going to just uh skip it or pop it pop the candidate from candidate list otherwise um if the right number is larger or equal to quarry then actually this is the final thing we are trying to look for then here after this while loop if the candidate list is not empty then we are going to say okay we are going to insert two uh the final answer why that is the case that is because the mean heap is sorted based on the interval length so whatever comes up first it is it has a smallest lens so that's why uh we have this kind of thing here uh like the first thing comes out of the mini heap that is actually the final answer we are trying to look for so that's a pretty much uh the thing uh how what we are going to do so what is going to save us some time that is because for here we keep increasing the index which means we are just a look uh going through the intervals array once uh without looking backwards so that is why it is going to save us the runtime and why it is why this would be a correct answer that is because we keep a candidate list and for this candidate list it contains the interval which act which potentially has the right direct number for the interval to be larger or equal to query but for sure the left number is going to be smaller than the current query number we are trying to look for and it is not going to lose us as any answer that is because for this while loop we just try to do the filter based on the right writing interval so the query number is already sorted if for so for example we have for a for the form on that formal querying query number if it is already uh larger than the red number then for the next number of course the right number for the interval is smaller than the next query number so that's a general intuitive idea how we are going to solve this problem so the run time for here it is going to be o and log n plus m log m that is due to the first part we do the sorting so having said that let's do some coding work on top of it so first of all what we are going to do is we are going to have everything to be sorted so you're going to say there's daw sort for intervals we're going to have interval 1 interval 2 enter interval one zero minus uh interval two zero so after this one you're going to sort the intervals array based on the left number and then you're going to sort the queries here we should have like a copy here because if he's if he messed up the other for the queries then it is going to mess up for the final answer for us as well so we are going to say let's say you have like a query clone mr chorizo clone is equal to and then we are going to sort the clone instead of the arrangement array so after that we have everything to be sorted um like i said uh we are going to have the main heap but uh beyond that i also need to have a map so this map is going to have key as integer and value as integer so the key is the query number because we already uh like we already sorted for this copy of the queries and key is a current number and value is the answer we are looking for which is the length of the smallest uh interval for it so let's say this is like the query on the interval lens then or maybe we just keep it as interval new hashmap and finally based on this one we are going to so we are going to make use of this map and the query is uh integer array to generate the final answer which is like uh this integer array as well so we are going to keep this one and we are also going to keep this index and of course we are going to have the priority queue rit so here i think we need to define a data structure so let's say this is something called um so let's say we call it interval of course let's say we call it interval um so we're having the left okay so this is the hints we have the right and uh we have the lens for it so this one the priority is of course going to be based on sorted based on the lens so let's say we have the public turbo so left right less or maybe just to give it to the left and right so left is equal to left and start right the right is equal to right and the lens is equal to right minus plus one so this priority q is containing the interval let's say we have the priority queue as new prey already here so let's say it has uh let's give it initialize as 10 but it doesn't matter and then we have the comparator let's say this one is still the interval so interval 1 interval 2 is going to be based on interval one dot uh lens minus interval two dot less so that's a priority queue and then it comes to our for loop here which is pretty much the skeleton here which i highlight so we have the query number to be to go through the chorus of the copy of the queries then uh well the index is smaller than intervals outlines and say intervals uh idx 0 is smaller or equal to the query number we are trying to look at then it means we have the candidate list or maybe just have this rename it as candidates so you're going to have candidates dot add so you're going to add the new interval for the this would be something like intervals or maybe you have like another uh do you have another thing another constructor here which is going to be like the interval uh so we go oh so this dot left is equal to interval zero this dot right is equal to interval one and this dots this knowledge is equal interval 1 minus interval 0 plus 1. so this one is not actually used we are just going to delete it so we have the new interval to be added into the candidate last um and then we are going to plus the index here and then after this well loop um we have a candidate list here what we are going to do is well the candidate is not empty white is not empty and also the candidate starts peak so if we pick it uh dots let's say this is uh right is actually smaller than the query um then we are going to say okay we are going to pop it and then after that if the candid list is not empty then it means we have like a final and we have like a answer for it for this query number so if it is not empty uh it means we are going to get uh this would be query interval dot put the query and the candidate dot peak dot lens otherwise it means we need to have insert a -1 for it so that's pretty much it -1 for it so that's pretty much it -1 for it so that's pretty much it and finally we need to turn the uh the hashmap into a list so let's say we have a helper function here so we're going to say this one let's say uh let's how to call it so let's say we call it as translate map to array so we have the queries and we have the map for integer and integer this is core interval so we are going to go through first of all we need to have like uh a an array so this let's say this is the answer register t is equal to new int uh queries dot uh let's for each of the query number you're going to so uh okay so this would be like idx is equal to zero starting from equal to zero so ret idx plus is equal to query interval dot get or default so actually we just need to get because we already push the minus one here but uh we are just going to have call get our defaults for query and -1 for query and -1 for query and -1 and finally we are going to return rit here so if we do that we don't need to insert the minus one here so finally we are going to call return this by passing the queries and we are going to pass this core interval into it so that's pretty much it let's uh depend on this platform to help us do some debugging work so okay so there is a typo here so okay so here we have the all right so okay so this would be like intervals idx all right so this one is accepted let's uh run some more examples through it sorry okay let's see some other test examples all right so seems like it works so let's do a submission for it cool so everything works well and that's pretty much it for this question so if you have any questions regarding this piece of code or regarding the solution feel free to leave some comments below if you like this video please help subscribe to this channel i'll see you next time thanks for watching
Minimum Interval to Include Each Query
maximum-number-of-events-that-can-be-attended-ii
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Array,Binary Search,Dynamic Programming
Hard
1478,2118,2164
7
hello everyone welcome to code for placement in today's question we will see reverse integer so basically reverse integer is one of the easiest topic or the easiest question which we have but it is very straightforward not the easy one it is very straightforward uh the question is saying that uh from question itself we know that to reverse the integer so we have given an integer value and we have to return that integer value with the digit reversed on it means if I'm having one two three I have to return three to one it means one two three the like a the most significant digit as the least significant digit and the second most significant digit as the second least significant digit and vice versa and so on so and so forth so the third three will be coming here 2 will be here and one will be here so we will be just reversing the each of the string and then we'll write the output and one more thing and we have to keep in mind whether it is a negative number or not in case if it is a negative we have to store that particular value yes it is a negative we will be creating a function to check whether it is a negative if it is a negative we will be returning the reverse order with a symbol negative minus that's it this is what we are going to do and it is very straightforward so let's that let's not waste the time and directly jump into the coding and let's finish this so I hope this screen will be visible to you and let me start with a coding this part so basically as we told we will be having one function to check whether it is a negative or not so if in that case let's take that function as a Boolean and it we I'm just naming this function is a negative in case if it is negative I am just first of all I am just keeping this as false okay so I'm just taking this as a negative and if what I'm doing here is I'm just keeping an if condition and just checking whether my X is less than 0 in that case if it is less than 0 I am just uh changing this ah Boolean as is this should be uh subject Auto suggest as a true okay so yeah that's it so in case if it is true I am just going to change my X into minus X that's it okay that's all we have to do so first what I have taken a variable which is negative if this is negative if I have chosen as false in that case if it is less than 0 it will ah true then to the next in Java we are doing this question so I am just taking this long to store the long uh variable uh so there should not be any issue so reverse is equal to 0 I have just taken a variable long which is reverse is equal to zero while my X is greater than 0 in that case I am just going to reverse each of the string so let's reverse is equal to reverse I'm just changing my most significant value to least significant value and vice versa and second most significant value to second least significant value and so on and so forth just dividing with 10 and storing it here once my while loop will finish if let's I'm just taking one condition f reverse is greater than please ignore this value if please integer dot Max so here it is already uh we know that in the question it should be uh Max of value which will give you an integer so let's return this zero okay that's all and once while returning of course we will check whether it is a in negative or not in case if it is a negative we will be first I will just check is negative if my uh is negative value will be coming as a negative in that case I will be um I will be reversing with a minus sign if not let's reverse it as it is reverse that's all so this is what we have if it is negative it will reverse with the minus sign if it is not negative it will not reverse with the minus sign that's all we have and this is what we have to uh return let's run this question and see the output whether we are getting it or not or we will see the console as well so once I am going to run this let me see if we are getting any error or something no it is run and it is accepted 100 percent with a runtime of 1 ms which is awesome so this is one of the best way to uh do it if you like this video do subscribe to code for placement and do hit the like button and share with others let's check the Run console um in this run console I'm just checking a quick question how satisfying this is so it is a design very satisfying so let's finish I will do this afterwards so I'm just running we are having three cases so here we on code four placement and this yeah so it is accepting all of them so that's all so this is one of the easiest way to find to reverse the integer in Java and yeah thank you so much guys thank you for being with us thank you
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
709
Yes, do you need something like a bag from Kate? What is English and the Half of Turtles and reduce the world of work which reflects the winner is her Pretty Happy with Butter better about Everything and illustrates Rita food the wondrous rate of your way to the installed and lightweight please Channel to have in the market to do it stores the systematic and stored adjusted I want the job not afford to see what I see you what you like about the help of yourself for the regime is open Play Store Adidas in I love you so ascii code Which you to person or She stands in yumiko [ __ ] person or She stands in yumiko [ __ ] person or She stands in yumiko [ __ ] free certified ethical good of Plastic and Lucky the Smart way you want to listen to person Unicode all of that your test Suzuki straight and What time is that the small on Smoking is patient with us about you Peace And its position is covered with music and difficulties and deliver your baby Shark International mother care and public of the weather has in value of native In about Of Justice marketing service user or use our faces permission to use this work out acc us for further smoky is about seven A YouTube no test and listed in small it's gonna be Into The First Avenger mod full test marketing according to ap industrial dish to be of market in all special person that will the way to the three We spent more people need to predict what about the Turtles IV Turtles and careful with the Earth is the single sixty five to make and is this What should then sheet sport for you straight to spend the rest of his name is stupid motor mother does is modem Asus ta you'll notice of going with Mortal instruments City and baby Shark and position of the children to stop for dd a passage is mainly Used words which is also have the more you practice speaking of direct eject with its market rather erratic Learn To Love Again about you is expected to specify a steam name wished to measure of mortlake to behave mortelmans roket therefore the rate of sitting still des affaires of Space Squad impact Earth turns into a powerful music when omit of positions and we know that happiness intelligence professional work inflator introspect take a reading about you to present the Art of small you fall is certified and not complain that other Kids with our trip on the way to the nearest Store a show citified first tell it to the threat to stay proud to announce That Is How We take advantage of the weather is just speak in all Isshu me think in today and the witch's kalasnikov screen or music withme start once you find you know of the displayed schogetten find the perfect place for tourists are you are interested in the fog and the first One If you want to What the weather cities of work together And The One That is What's weather in between of Pisa five and Shoulders above and encourage and Earth to be arrested in autumn is the weather in mind a and all that has picked rather that love is war two cities of the world is have read and complete r do you go to work correctly to streets and What's in practice to make and elegant is your Doctor about What people think of the arts park is not the case that Little work correctly on his throat and add it to the main synthesis And The Wheel of Destiny for today and Butter foot and system such anticipation westeast know that person went to court I miss you I love story speak it occurs and is the first and adaptable stillness of the finest We have ended and I have Apple Daily Weather Today We have of the father was compared to respond to eat I have nothing is not One but not Feel The pagoda and we and Pearl I think it's ok to testify which disqualification would allow you to purchase a What does is the city of factors for one and one for you would smexy anh have special should we kiss of Death Infinity prestige carat our best to Vietnamese Justin Angel of all the progressive suspension of value of you I
To Lower Case
to-lower-case
Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_. **Example 1:** **Input:** s = "Hello " **Output:** "hello " **Example 2:** **Input:** s = "here " **Output:** "here " **Example 3:** **Input:** s = "LOVELY " **Output:** "lovely " **Constraints:** * `1 <= s.length <= 100` * `s` consists of printable ASCII characters.
null
null
Easy
null
593
hey guys welcome back to another video and today we're going to be solving the link of question ballot square all right so in this question we're given the coordinates of four points in a two dimensional space return whether the four points could construct a square all right so the coordinate x comma y of a point is represented by an integer array with two integers all right so how do we know when something is a square so real quickly uh something is a square when all four sides have the same distance between them and another condition is that between all four other sides uh they are at a 90 degree angle right so those are our conditions and if you look at this over here so zero uh so let's just imagine zero to be over here in the beginning then we would have one so that would be the top right and we would have one zero and zero one so that does form a square if you want you can just look at it and graph it out and so in that case we do return true okay so let's just look at the note over here so none of these are that important but this one a valid square has four equal sides with positive length and four equal angles which have to be 90 degrees all right and input points have no order so that's pretty important they are not arranged in any sort of special way okay so now that we know this let's just kind of uh look at different conditions and different ways that we can kind of solve this question all right so over here uh we have this over here and what i'm going to do is i'm going to draw an axis okay or axis so we would have a y axis over here and we would have an x axis over here okay x and y all right so let's just label it um okay so over here uh when you think of a square at least when the first thing when i thought of as a square was uh something that looked like this okay so this is the first thing that came to my mind and i'm pretty sure this is what you thought as well okay so one thing i do want to say before this uh just consider that whatever i am drawing is a perfect square it does not look perfect by any means but just imagine or consider it to be a perfect square all right so all the uh the length of all four of the sides are the same and everything is at 90 degree angles okay so this over here is a square okay so if you look at this and just imagine every square to just look like this uh this question actually becomes kind of simple so at least what i was thinking of is the bottom left point over here would have the smallest value so it would have the smallest x value and the smallest y value and the top right would have the greatest x and y value so we can kind of use those conditions and find the distance and all of that and kind of program or make a solution specific to this square but one thing you want to realize is that not every square looks like this and that's something i did not consider in the very beginning so for example what i mean is we could have something which looks like a diamond right so something which looks like this and this over here is also technically a proper square so i did not draw it properly so just imagine that it is a square i'm really sorry so this over here is 90 degrees so everything is 90 degrees and they all have the same length so in this case this over here would also be considered a square so what we did over here is we looked at the bottom left and saw that as the smallest value so in this case if you kind of do that you would actually end up going somewhere over here so this is the leftmost value so you can't consider this square over here the same way you would consider this okay so kind of keeping that in mind we want to be more inclusive for all the different representations we might have for a square and again these are not the only two ways you might have them at several different angles and yeah okay so now that you understand that this is not the only way a square is represented let's kind of come up with a solution and just for the sake of simplicity i will only be looking at this over here since i think it's the easiest to follow along with so what i'm going to do is i'm going to start off by actually labeling these points so i will give them all a direct value as it is so in our question we are going to be given x and y coordinates and we need to find the distance but for now i will just assign it a distance and we will go over how to calculate a distance later so in this case let's say it is a square so let's just say everything has a distance of one all right perfect now i'm going to add one more thing which you may or may not know depending on how well you remember geometry so let's just draw a diagonal so between b and d and we're going to have a diagonal between a and c so if you remember the side or the sorry the length of a diagonal inside of a square is going to be the length of one of the sides so let's just call diagonal so d stands for diagonal is going to be one of the sides multiplied by square root of two so this over here gives us the length of the diagonal okay so kind of using that rule what would the length of this be so the length of ac would be one multiplied by root two giving us a length of root two and well b's d would also have the same length of root two so one thing that we can do over here is we can kind of find all of these uh dimensions and then compare them okay what exactly do i mean by that so in this case uh let's just try to cover all the dimensions okay and once i cover something i'll just put a tick mark by it okay so in this case uh one thing we want to have is a and b okay a and b uh so we have this covered so i'll put a tick mark and that has a length of one so let's just write it down uh similarly we have b and c so let's write it down b and c and that has a length of one okay before that let's just cover everything for eight then we also have a and d so a and d also has a length of one and finally we have a and c okay and that has a length of root two one into root two okay um now let's go through the other conditions so we have b and c and b and d we only took b and c so now let's take b and d and b and d is going to be root two and now the only thing that we want to consider let me just actually do the tick mark so we have bc we have c d we have ac so we have ac over here and we also have bd now the only thing that we don't have is actually cd so let's just add that up real quickly and we also have av sorry all right so let's add cd and cd is going to be y right so what actually can you notice over here so we know that this over here is a square but what exactly do you notice so first let's just identify what the side values are right so by that i mean a b c d and a d so i'll just kind of put a tick mark by it okay so these three values over here are the side values and the other two values a c and b d are the diagonals okay but how exactly do we differentiate from this so what i exactly mean by this is uh as the question says we do not know the order of uh in which we are given points so how exactly do we get these values and know exactly which distance refers to what so to do that what we're going to do is we're actually going to end up sorting this so when you sort this let's just see what happens so when you sort you'll get 1 comma 1. okay so when you sort this i actually i'll kind of generalize it so we will have four values okay so one two three and four so these four values in the beginning are going to refer to each of our sides and technically if we had a square all of these four values would have the same value okay so in this case uh let's just do that so in this case they would all be one so one and one okay now how do we know for a fact that the first four values are going to refer to the sides and the reason we actually know that is because uh the sides are always going to be smaller than the diagonals and if that doesn't make sense it's because the diagonal is you're taking the side and you're multiplying it with root two right so you're increasing its value so all four of these refer to the size and if that is not the case we already directly know that it's not a square so for it to be squared the first four values must be equal to each other and one other small condition that we want to take care of is what if we have a point like just a simple point so in that case they would also all have the same as values but they would have a value of zero since the distance is zero so in that case actually we're going to end up returning false because a point is not considered a square okay so now we have the first four values and now let's look at the other two so now we would have two other values and both of these like i said are going to refer to the diagonals okay so perfect we have our diagonals which are well in this case root 2 and root 2. so what exactly is the condition for our diagonals so the last two values are also going to be equal to each other so this and this are both going to be equal to each other in a square and another thing we could do is just because they're equal to each other does not exactly mean that it's a square we want to see whether this uh these two are equal to each other and they also are the actual diagonals of our square and to do that what we're going to do is we're going to take one of these values right so any of the sides so let's just say we end up taking this and let's calculate the diagonal using that so in this case we're going to do 1 into root 2 which gives us root 2 and we're going to compare that with these values and if they are equal to the same thing that means that we've got a square so hopefully by now you understood how we can actually come up with finding out whether something is a square or not so that over there is kind of the first part and now the other part that you might be thinking about is how exactly do we get these distance values because in our question we're good the only thing we're getting are the coordinates which are x comma y inside of a list so now we want to understand how can we actually get these distance values all of these over here so four sides plus two diagonals using this let's just take a quick look at how we can do that okay so how exactly do we get the four points that we were talking about so now in this case we actually want to be a little bit more inclusive what i mean by that is i want you to think about the other possible square representations that we can have like how i showed you the diamond form or the same square tilted at a different angle so not all the squares look like this so kind of keeping that in mind we want to actually find out all the possible directions that we can find between these points so what exactly does that mean what i mean by that is let's just kind of assume a value for each of them so i mean letters so let's just say a b c and d so by the ending of this we want to get the four direction of the four sides so a b c d and a d and we also want to get two diagonals so no matter in what order our points are given to us it doesn't actually matter to us in order to find our direction because all we're going to end up doing is we're going to find out the direction in all the six possibilities because over here there are really only six possibilities so if you don't want to think them think of these values as a b and c and d think of this as the first point second point third point and fourth point irrespective of at which order we are in we're going to make sure that we find the distance between each and every point and that's exactly what we're going to do so over here we're going to find the distance between a and b and just to kind of clarify the distance between a and b is going to be the stay same as distance as the distance between b and a and keeping that in mind that really means that we just need to kind of find the distance just one time all right so now that we know this uh how do we find the distance so the formula that we're going to be using is the distance is going to be equal to the square root and it's going to be the square root of what so it's going to be square between the change in the x value squared plus the change in the y value squared okay so this over here is the formula that we're using and we're just going to modify it a bit uh as you will see okay so let's just see how we can do this so what we're going to do is we're going to find the difference between a and b so to do that's going to give us the change in x is 0 and the change in y is 2. so in that case we're going to get 0 squared plus 2 squared which is actually 4 and square root of 4 is equal to 2. so i'm not actually going to do this for each and every point so just try to kind of do this for each of the points and you're going to end up with two on all of our sides now for the diagonals you're going to end up with a value which is actually going to be uh let's take a look so zero comma zero and two comma two okay so now if you are doing a diagonal the change in x is two so two squared plus and the change in y is also two so two squared and we're going to square root all of that and this over here is going to give us a value of square root of 8 and another way to write that is going to be the square root of 4 multiplied by the square root of 2 which is nothing else but 2 multiplied by square root of 2. okay now this over here does make sense because i showed you earlier that to get a length of a diagonal you take one of the sides and multiply that with root two so that is nothing else but do two multiply by root two but dealing with the square root of two might be a little bit confusing right because this is a irrational number right square root of 2 is an irrational number so what we're going to try to do is we're going to kind of get rid of the square root of 2 and the way we're going to do that is by squaring this so let's just go back a step and we have root a so a simple thing we can just do is we can just take the square root of that and now we just get the number eight right so we're going to get eight as our distance but that actually doesn't make sense right because the diagonal is supposed to be equal to the side multiplied by root two so if you want to go with this definition we also need to change the distance formula that we end up using so keeping that in mind all we need to do now is we're going to square this okay so when you square the square root the square is just going to get uh get out right so the square root is nothing else but to the power of one by two so one by two multiplied by two gives us a value of one so we're taking this to the power of one so now in other words the distance formula we're using now is the change in x squared plus the change in y squared so now let's just change up all of our values so let's just take an example right so we have zero comma zero and zero comma two so over here we have a change of x and zero and change of y is two so now we get zero squared plus two squared which is four and that is going to be the new distance for our left okay so i'll just update everything with that so now we have four on all of the four sides okay now when we find the distance between a and c or b and d we're going to get a value of eight okay and the reason we get eight is we would actually get root eight right if you were following this formula and all we're doing is we're squaring that right so we actually now end up with eight and how does this make more sense so this makes more sense because we can just directly do four multiply by two and that should equal to eight and it does and that means that we have a valid rectangle and just to kind of show you that uh we would have the four sides right so we'd have four comma four so this means that we have all the four sides they're all the same and they are not equal to zero so the sides are the same distance now we want to check the diagonals right and checking the diagonals also helps us with checking if everything is 90 degrees so for the diagonals we would have 8 and 8. so both of these values are the same so that's one thing that we're checking for and the other thing we're checking for is one of the sides multiplied by 2 equal to this value over here and it is four multiplied by two is equal to eight so hopefully you understand what we're doing and uh i think i went quite in depth in this so all i'm going to do is directly show you the code because the code really is the easy part once you understand kind of the math or logic behind it okay so this over here is our code and let's just go through it real quickly so let's start off by defining a function called disk and this function over here is going to help us get the distance given to certain points and the two points that we're referring to are going to be a and b so now what we're going to do is we're going to find the change in x right so the change in x we're going to go to a 0 so that gives us the x value for a and b 0 giving us the x value of b and again the order of this doesn't matter because we're ending up squaring them so even if it's negative it's going to end up becoming positive after squaring it and then we're going to square the value we're going to do the same for the y values and then we're going to add it up okay so now we're gonna have a list called distances and inside of this list we're gonna find the distance between all the six possibilities okay so over here we have the distance between point one and point two then we have point one and point three and point one and point four okay so over there we got three of them and then really all we're doing is we're finding the distance between each of these four points then we have p2 and p3 p2 p4 and p3 and p4 okay so now we have all of this inside of our distances and now what we're going to do is like i said earlier is we want to sort them so that the first four hour are the sides and the last two refer to the diagonal values okay so to do that we're just doing distances dot sort it happens in place and finally we're going to end up returning this so we're going to check if distance is zero is equal to distances one two and three so basically we're checking if the first four values are the same and we're also going to check if this value over here is greater than zero right so it has to be greater than zero if it's equal to zero that means we have a point okay so uh in that case we're going to return true but we also want to check for the other condition which is the diagonals so we're going to check if four and five so in other words the very last two values uh you if that doesn't make sense you could just refer to them as negative one and negative two the last two values so if they two if both of them are equal to the same thing we're also gonna check if we can reach that value so to do that we're gonna do two multiplied by distances zero or in this case you could actually do zero one two or three you could do any of them because they all represent each of the sides okay so let's just stick with one it doesn't matter so two into distance is one and we're going to check if that is equal to the other value all right so finally we're just going to end up submitting this and let's see what happens okay and as you can see our submission was accepted so finally thanks a lot for watching guys i think the video was pretty long but yeah hopefully you did understand do let me know if you have any questions and thank you
Valid Square
valid-square
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
Math,Geometry
Medium
null
436
Hello hello everyone welcome to my channel it's all the net problem find right in trouble for giving us a topper interview for each of the interval i check is tej us jor start point is bigger than or equal to the point in the interval i which can we Call The Day Is The Right Interval Of High For Interview Neetu Story Minimum Intervals Index Which Means The Amazing Minimum Start Point To Build A Right Relationship Point Above I Is Dowse Is Toe Minus 1.855 Final Unit You 1.855 Final Unit You 1.855 Final Unit You Want This Toe Value Of Each And Every Time Intervals End Points After But Divide Into Its Parts Start Problem From 90 Give A Set Of Values ​​Like A Government Also Have Only Set Of Values ​​Like A Government Also Have Only Set Of Values ​​Like A Government Also Have Only One Travel In That Case Will Not Have Any Right Interpol Because They Have Only One Who Were Present Simple Return Minus One Race For This Point Example from Vighna Interviews and More Recently CD and of the center will spoil and as an instrument starting from fennel and plus sweet is toot - 114 and plus sweet is toot - 114 and plus sweet is toot - 114 Security Central to Three ABCD Additional Judge Jasbir Vishika The End of This to Intervene and Three Stop This Securities Index Shy 12323 Is The Right Interview Important Points Mention Hair Beach Sexual Not Clearly Written Minimum Wage Subscribe Minimum Like This Is The Mid Point Of The Solution Implementation That Brute Force Approach Business Run Over Interval Wise You For Lips Fennel At Interview And Died For Love And Withdraw All the best not to let us know how to check effigy in which is the first Indian to do all the doing so will withdraw into and will also create subscribe button Dhundhu - subscribe button Dhundhu - subscribe button Dhundhu - 12345 subscribe thank you agree to t&amp;c who t&amp;c who t&amp;c who is the time complexity of This solution for this code implemented hair Shoaib Safed Taking it off with a revolver internal Vijay simply written in this - 1000 no entry for the simply written in this - 1000 no entry for the simply written in this - 1000 no entry for the interview compared with and in case of others is VR just going through all the individuals may even in the meeting and Asked by using this help samay tak do samay the first one person the end of the current affairs and compete with stop the internet access internal and vivid and will return do subscribe one rupee every time complexity of dissolution of others like this 200 ft no one notice That Will Have To File Adjust Immediate And Tax Liability Tried To Solve Video Ability Inductive Starting And Research Will Help Crush Logo Ki Fasal Will Solve Dis Start Point Episode Start Points For This Vikram And What Will U Need To Give In This Point To 10 2.2 End Subscribe Our back to three I am 10 2.2 End Subscribe Our back to three I am 10 2.2 End Subscribe Our back to three I am born in whose three four is a message is after shooting and will also have live with computer and subscribe 512 the light is the video then subscribe to the page if you liked the video then subscribe to the page if you are Subscribe to is so here is the java oracle document for degree maths and places to take all the giver and debit so what will oo will stored 21 taking started staff and interval hindi sxy and values ​​in cognitive one of the sxy and values ​​in cognitive one of the sxy and values ​​in cognitive one of the start the value of interview will it In this function beech returns list ki aur tap se research ki notice on jo hair beendhati ceiling ki off beech saunf fail hai usse create 820 be st amused to live without oo want to enter and re-enter start 1234 subscribe now to re-enter start 1234 subscribe now to re-enter start 1234 subscribe now to receive new updates Reviews and will look into the this i.e. subscribe our and into the this i.e. subscribe our and into the this i.e. subscribe our and discant fennel and subscribe this is not acid in also what will be amazed in the response of key from ceiling returning tap inside the sweet - versus no returning tap inside the sweet - versus no returning tap inside the sweet - versus no right interval of the interval similarly special guest will Get Discounts And Will Put 0452 This Will Guide You Wanna Join Us At Mid Day Meal - 101 Share This Video For Day Meal - 101 Share This Video For Day Meal - 101 Share This Video For Implementation Map 200 Cat Store In Teaser Start Integer Sudesh Belated Call Me At Self Map That In Hair Wife Literature On All The Element In middle aged report subscribe intelligible to interview will not like it is equal to one templateton subscribe inter - 1st chapter one templateton subscribe inter - 1st chapter one templateton subscribe inter - 1st chapter vivarvar divine interview in more result will tree again later hai mi plus hai na ho first of all will get into ditties where lucky Effective from mother daughters pay me this piece like hair of swadeshi sealing's father and of current affairs on this will and in the interviews aa i pawan isse no will to sign this to our youtube channel subscribe - why - why - why other will support wap. net Divya Anand Is Vansh Ke Veer Is Not Know What Is The Time Of Running When The Time Complexity Of Dissolution And Complexity Of Using Web Result For Subscribe My Channel Like My Video Thanks For Watching
Find Right Interval
find-right-interval
You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**. The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`. Return _an array of **right interval** indices for each interval `i`_. If no **right interval** exists for interval `i`, then put `-1` at index `i`. **Example 1:** **Input:** intervals = \[\[1,2\]\] **Output:** \[-1\] **Explanation:** There is only one interval in the collection, so it outputs -1. **Example 2:** **Input:** intervals = \[\[3,4\],\[2,3\],\[1,2\]\] **Output:** \[-1,0,1\] **Explanation:** There is no right interval for \[3,4\]. The right interval for \[2,3\] is \[3,4\] since start0 = 3 is the smallest start that is >= end1 = 3. The right interval for \[1,2\] is \[2,3\] since start1 = 2 is the smallest start that is >= end2 = 2. **Example 3:** **Input:** intervals = \[\[1,4\],\[2,3\],\[3,4\]\] **Output:** \[-1,2,-1\] **Explanation:** There is no right interval for \[1,4\] and \[3,4\]. The right interval for \[2,3\] is \[3,4\] since start2 = 3 is the smallest start that is >= end1 = 3. **Constraints:** * `1 <= intervals.length <= 2 * 104` * `intervals[i].length == 2` * `-106 <= starti <= endi <= 106` * The start point of each interval is **unique**.
null
Array,Binary Search,Sorting
Medium
352
373
hey everybody this is Larry still in this pin so hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's problem find Kate Paris with the smallest sums and it seems like I haven't done this before so that's kind of fun it's always nice to see a new problem all right so you're given two arrays and ascending order and an integer K Define UV where one element from one element and an okay we turn the K pairs with this smaller sum uh as soon as we use it um and this is kind of a very um how do I want to say it uh it is a problem that comes up a little bit of often uh maybe not this particular thing but a usage of this idea of like repeating uh almost like a breakfast search e thing where you kind of like find the next possible element and yeah and I think that's the way to do it uh of course the first thing I want to take a look is that there's no easy naive solution because if it if n is like a hundred then just come on do it N squared but given that n is n and M or whatever is equal to 10 to the fifth um it's going to be too slow if you do something really naive it you just to create all parts of player and then maybe sort it or something um however you can do it and uh and better than that so yeah uh oh actually one thing I did for uh just realized is that it's an ascending order so you don't even need um you don't even need to do anything that funky uh because they're already ascending right so but I think that part maybe matters a little bit less in the sense that if it wasn't the same thing we probably would have just sorted it so uh I mean of course that factors into the final complexity and stuff like this but given that they're already giving us that in a structure way that's kind of nice okay so how do I want to do this um the popular couple of ways to do it uh what is km the play a couple of ways to do it uh the way that I think the important point about this problem is just not making silly mistakes uh with respect to double counting uh that's one thing I would look for and then the other thing is just uh it is going to be greedy in some sense SP problems are but you know you don't want to take shortcuts by accident right which I have known to have done from time to time so it happens still even with me um but yeah okay yeah I'm keeping in mind that because in this sense you are trying to um return repeatedly getting the smallest thing is why Heap is kind of a yeah so this is the key and then a couple of ways you can think about it I think so yeah for um I'm trying to proof in my head real quick I do this in the morning in Lisbon so it's not 100 waking up yet but I'm trying to think whether it is always sufficient to only care about one array and not the other okay well I mean okay let's start from the beginning right so the smallest number is going to be the small uh so we can actually start with something like hip Dot page and then maybe something like numbers of one of zero price numbers of two of zero or index of zero but and then we can just keep track of the indexes from the left and right um yeah and then while length of if it is greater than zero and K is greater than zero or maybe we should store it somewhere but that's fine right then we need to subtract one uh hit the queue that hip half of H so we have to total we have I and J for the indexes and then we also have an answer thing right so yeah and then answer you a pair number one of zero uh an array of this comes a tour of silver right yeah and now we want to put in the Heap um like this but not quite yet right something like this but not actually so uh because this is going to run into some repeated numbers uh and that's what I said about double counting uh and of course you have to make sure and make sure that you know this is just an end so that's basic things but it still can be that you're double counting right because if you think about just like a grid um a two-dimensional grid and you're um a two-dimensional grid and you're um a two-dimensional grid and you're basically going up you're going left one and going right one or sorry however you want to do it ready but down and right but then now you go down and right like in a diagonal way then you're gonna do a repeat number right so that how do we do it hmm I guess the way to do that is just how do we do it oh excuse me I mean this would totally work except for it's wrong right uh yeah we can run it real quick uh it gets to see it already repeats that it only repeats because this shouldn't repeat quite like that hmm oh well it really repeat because I'm dumb okay yeah so it looks good here but I think that's just coincidence or like you know bad test cases or something like this uh but that tricks I don't even know why does it take so long yeah you're double counting so it's always going to be one like here you go right uh you can see that I guess dances doesn't have to be you dances don't have to be unique but and they sorted the other way first but you can see that we count two double multiple times and that is just no bueno right so what can we do to do it I mean I guess one way is just like to keep uh a buoy in a way but that seems kind of sketchy right like can we be smarter than that I mean that would be a very uh naive thing to do and you don't even have to keep track of that many of it in a set or something because K is 10 to the fourth right and it's going to only grow to the size of k um but three two brothers and then hmm I don't know that we can to be honest and still you know keep the diagonal I mean I guess we can that would be kind of cool way of doing it I mean I don't know if that is quite true but all right so like I think the idea is just to like exploit um but it's still it makes it even you know it makes it more expensive in that way though because that um because it's gonna end up all of K space anyway what I was going to do is uh you can start the you can start say k diagonals on the like if you think about it's a grid of IJ pairs I mean you think about it the diagonals uh and then we put in initial diagonals and then only diagonals goes down and right where you know if you're the upper half of the triangle you go only right and in the bottom half you only go down so then in theory you can kind of like you know stretch it across um but it's still going to end up taking all of K space only because if you start diagnosing okay you could always say maybe we can start the diagonal but let's play around with that seems like a fun idea to play around with though and today maybe I'm feeling a little experimentary so yeah so we start zero right if I is equal to J then we do uh because we try to go away we try to go down and we try to go diagonal say but um else if I is greater than J what does that mean that means that is on the bottom half so then you only go to the I plus one point and go down uh else we just go to the right something like that but yes this is very yucky though I don't know I mean it basically it's just and this isn't like any special technique or anything it's just me trying to think like okay how what is like uh an heuristic that allows to just do it once from each direction right um so yeah um or like once not just from each Direction but once in all directions so I spoke a little bit yeah I think that's kind of cool actually is it I don't know let me know in the comments if you think I mean this is I wouldn't say that I invented it because you know like who invents things anymore right especially code but I don't think that I don't know I think it's kind of cool I did come up with this like on the spot so it's not like you know whatever but anyway so that's why I feel a little cool about it but you may disagree let me know in the comments what you think about that so yeah um otherwise that's all I have for this one let me know what you think uh yeah stay good stay healthy took on Mental Health I'll see y'all later and take care bye
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
763
foreign coding together my name is vikas hoja today we will see another lead code problem that is partition labels so it's a medium level question and it's a very popular question as you can see from the likes so let's read the problem statement 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 right we have to partition the string into multiple parts and if the one letter appears in one partition it cannot appear in the other partitions right so note that the partition is done so that after con concatenating all the parts in order the result resultant string should be S and the partition should be done in such a way that after concatenating it should form the original string right so return a list of integers representing the size of these parts so let's see an example to better understand the problem so here we are given within a string right so we can partition this string into three parts one is of length nine another is of length seven and third one is of length eight so the first one that is a b c b a c a the first character a and the last occurrence of a appear in this partition only right a does not appear in this partition nor in this partition right similarly with b occurs uh only in this first partition B is not there in the second and third partition right similarly d is in the first part in the second partition it is not in the first and the third party right so these three partitions are of length nine seven eight respectively so let's see how we can solve this problem we will use greedy approach to solve this problem and in this approach in this greedy approach we will be needing an array that we will called a last array that will store the last occurrence of each letter in the string given so for example in this string the last occurrence of a is eight right last occurrence of B is 5 last occurrence of C is seven similarly for D is 14. for e is 15. for f is 11 G it's 13 H 16 H nineteen I 22 j23 K 20 and L 21 so we will greedily choose our left Justified partition starting from the first index so for the current first index itself we will choose a partition where the end of the partition ends at last occurrence of a so the last occurrence of a we will check our last array the last occurrence of a is at 8 so we will have our partition starting from the first occurrence of a till the last occurrence of a that is 8 so the partition is from 0 to 8 so we will have our two variables anchor and J that will point to the start and the end of the partition right now we will check so it might be the case now it might be the case that for the next character suppose B we might have to increase the length of this partition right or it might be the case that the this partition the length of this partition remains unchanged right so we have greedily chosen our first partition and we will check for the next characters so for B the last occurrence we'll check our last array is at 5 so it's smaller the last index of B is smaller than the last index of already chosen a so the partition will remain unchanged now the next character is a so we have already chosen for a for B we have already seen for C the last index of C is 7. so which is smaller than the already chosen last index that is eight right or we can say that the last index of C is smaller than J so we will the partition will remain unchanged right now for B we have already seen for a we have already chosen for C we have already seen and for a we have already chosen this partition for a only now our I has reached J right so it means we have seen all the characters so all the characters in this partition have their last occurrence their first and last occurrence in this partition only right so we will have our we are have our first partition so we will add into the list resultant list so we will have to we have to add the length so we will do J minus anchor plus one so J is pointing to 8 minus 0 plus 1 that is 9. so first partition is of length nine now we will change our anchor from zeroth location to I plus 1 that is anchor will point to index 9. now we'll again do it we will choose our partition greedily with the first character and the last occurrence of first character that is D ends at 14 so we will have our partition from 9 to 14 so the anchor will point to 9 and J Will point to 14. right now we will choose we will check the next character that is e so what is the last index last occurrence of e that is 15 so it's greater than J so we will increase our partition right we'll increase our partition will we change our J to 15. right now we will check for f the last index is 11 so it's smaller than J we will not change the partition for e we have already chosen for E for G the last index is at 13 which is smaller than current J so we will not change it for d right for D also 14 Which is less than 15 so we will not change it and for E we have already chosen so now we have the next partition in which all the elements and their first and last occurrence is within this partition only right so now the J is pointing to 15 and corresponding to 9 and we'll do plus one so it will be seven so the next partition is of length seven which meets the condition now we will move our anchor to I plus 1 that is 16. so anchor will point to 16. and now we will again choose our partition for the First with the first character greedily with the first character so now the partition will end it the last occurrence of H that is at 19. so J Will point to 19. now we will check for the next character that is I so the last index of I is at 12 as at 22 which is greater than 19 so we'll increase our partition and we'll change our J from 19 to 22. right now for J the last occurrence of J is at 23 which is greater than the current J so we will increase our partition and we will cover the last character J as well so J Will point to 23. right now we will check for H so H for H the last index is 19 which is smaller than J so will the partition will remain unchanged for k with 20 Which is less than 23 will skip for L which is 21 last index is 21 so we'll skip for I the last indexer 22 will skip for J as we have already chosen for J and we are end of the string so this is our third partition so we will calculate the length so 23 minus 16 plus 1 that is 8 so the last length is 9 8 and the there are three partitions of nine seven eight that will be added now let's see the code part for it so I have written a Java code here so I've created a class solution I have created a function partition labels which takes the input s and Returns the list of integer we have I've created a very uh array last of size 26 because the or the alphabets lowercase alphabets are 26 in numbers right and this will store the last occurrence of each character of the string so for each character of the string we will maintain the last occurrence in this last array now we will have our JN anchor starting from 0 that will represent the start and the end of the particular partition list for and we will start our for Loop starting from I equal to 0 until we go and we'll go till s dot length right so we will update the end of the partition that is represented by J with the max of J or if there is any character whose last occurrence is greater than J right so in the particular partition we saw that first we chose for the h the index was 19 and then when we when for the next character I who is the last occurrence was at 22 which was greater than the previously chosen J that is 19 then we incremented the J to 22. right and when I equal to J it means we have reached a point which is the end of the partition or IE each characters in this partition have their first and last occurrences in the same partition only right and there is no character whose last occurrence is greater than the current J so we will add in the answer the length of that partition and we will update our anchor to J Plus 1. and will return the answer so let's try to run this solution so yeah test the test cases are passed so it means the solution is working fine so let's talk about the time and space complexity so as you can see we are running one for Loop for calculating the last index and one for Loop for iterating over each character of the string so we are iterating in the worst case the length of the string so the time complexity will be bigger of and where n is equal to s dot length and for the space complexity as we are maintaining the last array and the list answer list which uh which will constitute the space complexity of Big O of n plus Big O of n which will be inverse case will be big off and only where n is the s dot length so I hope you enjoyed watching this video If you like this video please share and subscribe thanks for watching it will keep me motivated to bring more such videos in front of you thank you 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
389
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 channels and hit the bell icon so that you get notified when i post a new video so without any further ado let's get started so problem is very simple we'll be discussing multiple approaches in this video so problem is find the difference uh we are given two strings and the string t is generated by randomly shuffling the string s corrective so and one more extra character is added in the string t so we have to return that letter which is the which is added in t so t will have all the other letters of string s but just the thing is that it will have one more extra character so here if you see in this test case here abcd is there and a b c d is in the in t and e is a new letter which is added in string d so that is the new addition we have to return that so e we will return so very simple problem right um let's see the other test case also so over here initially string was empty and then y is added so y is the output and we are given the length of the string thousand so length of this ring is thousand so uh we can use n square approach also so if we have n square approach that will also work right so let's see how we can approach this problem right see um let's take this test case only so we have a let's take we have string s is given to us and it is abcd and st t string is given so i'm bit shuffling the letters right i'm shuffling so b c a d a e and d so this is string t so if you see all the letters of s are there in t a is there yes b is there c is there and d is there right and one more extra character which is e is in t string so output will be the extra character which is e right so let's discuss the first approach which we can use is that we can we just need to compare now we need to compare which is the extra character so what we can do is we can sort this string so we'll be sorting both the strings so this is already sorted so like this will be this only and we will sort this one also so this one will become a b c d e so we have sorted them at the last at the here the last character uh here we will get uh so when we what we will do now is we will just compare this string and this string so here this is same and this string is done so this letter the last letter will be the extra one so we will return that so this is the one approach like this one approach which we can use that is we will sort the strings both the strings and then we will compare the letters and which one is the extra one that we will return so this is one approach that is sorting so the sorting time complexity for this will be n log n because we are doing sorting right and logging other approach see other approaches generally we see this problem the first approach which comes into our mind is that we will use a hash map we will store all the characters and then we will just compare which one is the extra one right so we can do that so what we can do is we can use a hash map so hashmap will be what see in hash map what we will do we will store all the characters of the string s this is a hash map which we have so we will have this hash map and in this we will be storing all the characters of uh string s so abcd and you can give anything here right then what we will be doing so here you have stored the letter and here you showed the count and then we have this so we will compare whether b is there c is there a is there and e is not there right e is not there hence e is the extra character so just return it so this is one way we can use this hashing and we can use hash map and we can solve this problem so time complexity for that will be o of n but the space complexity since we are using this hash map so space complexity will be length of the string s so let's say it is n one so it will be space complexity will be o of n one right this is one approach now we have to avoid using extra space so what we can do then see another approach which we can use here is that we can compare the see we are given letters right we are given letters so there is one benefit of having letters that we know the sky values right of there are sky values of letters so if a is a sky value is what 97 plus b is 98 plus c is 99 and d is 100 so this will be some let's say x now this t will have all these letters so b c a d these will have some x plus there will be some like some some of this e so that's let's say y so this will be equal to let's see so what we can do is we can have the whole sum of this which is let's say y and if we do y minus if let's say this is x so y minus x so what we will get c b plus what is y is what b plus c plus a plus e plus d this is y sum minus x sum is like all these characters which is a plus b plus c plus d right so see here there is one extra character no rest of the characters are same so some what we can do is we can subtract this sum from this thumb and we'll get the extra letters so a will be get cancelled see bb will get insult see we get cancelled and d will get cancelled and we will get e so we can get we can just return this can we will get the correct we will get that correct let's see the code for this approach so see what we are doing over here see we have this now just a second yeah see what we are doing is we have taken two variables a to show sum of s and b to store some of t so we are going to each letter in the string s and then we are just adding the sum then we are going to each character in string t and then we are adding to b and then b minus a we will do so that will give us this extra correct extract later like sky you can say our sum so that will return and it will get converted to character so we will get the correct extra character so this is one approach see we are using no extra space here just the variables are there so the time complexity for this approach see we are using no extra space so time space complexity will be constant and time complexity will be we have two loops now this one and this one so if this s has n one letters and t has n two letters so it will be o of n one plus n2 we have two loops right and there is one more approach which we can use this is optimized approach but there is one more approach which we can use see we have uh this string a b c d and the string t and string t is what it's uh a let's take anything so e c d this we have right now what we can do is we can use zor because in zor what is there if we have c if we have same uh numbers a and we take 0 of that so we will get what 0 get we will get 0 now that is what 0 is 0 1 is 1 0 is 1 and 1 is 0 so if we have same see if we have same then we'll get the same we'll get 0 for that if we have same we'll get 0 for that so what we will do is we will take 0 of both all the characters of s and t e and then c and then zordi so see this is or a we can rearrange so in zor we can rearrange these so we will rearrange and we will get a's or a and b's or b so we will like same ones we will bring together so b will come to b then store c one will come here c zor d and like this so these are same so there's or will be what zero then zeros or this will be also zero and this will be e now zeros are zero so this will be what all zero e so zeros or e so what will happen uh this will give us e only because anything will be like so zero you are doing zord with like if you are doing some things or with zero so if there is one so once or will one zero will come what one only that letter will only come that number will only come zeros or e will be e only so in this way we will get the extra character we will but we can do zor and the same one will cancel out and we will get the extra character so let's see the approach for this code for this so here what we are doing is we have taken this r variable and then we are going and doing zoro of each letter in s and then each letter of t and then we can just return this r right this will be the extra later so if you submit this it's getting accepted right so these are all the approaches so time complexity for this will be um we are doing two traversals so again n1 plus n2 and space will be constant as we are not using any extra space right so i hope the video was helpful let me know in the comments if any doubt and if you found the video helpful please like it subscribe to my channel and i'll see in the next video
Find the Difference
find-the-difference
You are given two strings `s` and `t`. String `t` is generated by random shuffling string `s` and then add one more letter at a random position. Return the letter that was added to `t`. **Example 1:** **Input:** s = "abcd ", t = "abcde " **Output:** "e " **Explanation:** 'e' is the letter that was added. **Example 2:** **Input:** s = " ", t = "y " **Output:** "y " **Constraints:** * `0 <= s.length <= 1000` * `t.length == s.length + 1` * `s` and `t` consist of lowercase English letters.
null
Hash Table,String,Bit Manipulation,Sorting
Easy
136
415
all right guys welcome to our channel code with sunny and in this video i will be talking about the easy problem you can see over here the problem is basically we have to add two strings as the name suggests its index is four one five as i've already said it's an easy type problem okay so we'll be given two non-negative okay so we'll be given two non-negative okay so we'll be given two non-negative integers num1 and num2 being represented as a string and we have to return the sum of these two numbers and the output should be in a string format okay and we have show we have to be very much careful that we are not going to use any built-in library functions built-in library functions built-in library functions for handling large integers okay what we are going to do is we are going to manually find out the sum in the string format and how we are going to do that let's try to understand this one so suppose what i am going to do is like we have some string being represented over here lets say 2 3 4 and five suppose this is one of the string uh holding the any number and suppose we have another string being represented like as suppose let's say five four nine okay so if this is one of the numbers and this is another of the numbers so in general mathematics what we are going to do is we are going to put up these numbers like that and we are going to find out the sum starting from this rightmost number or you can see the rightmost digit okay then what you are going to do is let's understand the sequence of operation we are going to add these two digits 9 plus 5 14 okay then what we are going to do is we are going to pick up the last digit of this 14 which is basically 14 modulus 10 in programming language okay so in this case you are going to get the value as 4 ok and now initially you should also have to maintain the carry okay i will explain it out what is this new term so you are going to perform this modulo operation then you are going to get the last digit and you are going to fill it over here okay and now the carry is going to be like we are going to hold out some values and we are going to use that for the latter one like for the next case you can see because this number is like greater than 10 it will hold some carry value so our carry variable will going to be incremented by 14 divided by 10 okay so it should be incremented by one so it becomes one initially it was initialized as zero okay so carry becomes one so in general you are what you are going to do 9 plus 5 14 then it comes out to be 4 and make a carry as one again you can you are going to say that 4 plus 4 is coming out to be 8 and you need you are going to use this value is like carry so 4 plus 4 is 8 but carry is 1 so you are going to pick up this value so it becomes 9 so the digit that is being going to be filled over here in our answer is like 9 modulus 10 which is 9 and now our carry is going to be initialized with 9 divided by 10 which is 0 so now the carry becomes 0 and we have the digit 9 over here okay now we are going to do this one three and five so it becomes eight and carry is zero so the number is actually the eight so i will write down the digit here as eight modulus ten it would become as eight okay and the carry is going to be initialized by eight by ten and the integer value that i am going to take over this division so it is zero okay now in the next case there is like empty value because the length of this string of digits is like less than this one so for the case of empty values we would treat it as 0 okay the 2 plus 0 is again 2 and we have the carry as 0 so it would be remain as 2 and to get the answer for here 2 modulus 10 it would be 2 and carry would be like 0 okay because 2 by 10 integer value for this division is 0 so this is our answer so if you sum up this value like 2 3 4 5 and 5 4 9 you would actually get this value and this is correct okay so this is basically the way of doing like sequentially using the help of digits in the similar case to the string we are going to do that okay so let's head over to the code to understand this one in a detailed manner okay so i've already submitted the code i don't know why i'm getting wrong answer for the first time there was some small mistake okay so let me just okay so let me explain it over here so what i've done is like first i've reversed this string okay because the strings that would be given to us actually and like over this format and we are going to start from the very right most case and to simplify our code that's why i've reversed this one and also i would ensure that nums one dot length must be less than num2 dot length because i need to append zeros to the back of it because in the case like when one of the numbers has smaller length i need to append zeros right to simplify or to ease our calculation now let's uh start filling our answers so initially carry is initialized as zero and every time we are going to change this variable as variable value also okay so i trade for this entire string length that is num1.length entire string length that is num1.length entire string length that is num1.length and find out the current value you can see the current value is like the digit current digit of num1 and the current digit of num2 plus carry and to get the current answer like answer what is the current answer at this position it should be like a value mod 10 as i have already suggested and the carry is going to be initialized with value divided by 10 the integer value okay and i'm going to append my current answer it should be like the character format of this c u r that is going to be represented by this one okay and lastly if you carries some uh positive integer like one two three or something else you need to append it to answer also and finally you are going to reverse the spencer string and return it to your answer this is your answer and it will give you a 81 percentage faster code okay so if you have any doubts do let me know in the comment section of the video and i will ask the viewers to like this video share this video and to subscribe to youtube channel for latest updates thank you for watching this video
Add Strings
add-strings
Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_. You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly. **Example 1:** **Input:** num1 = "11 ", num2 = "123 " **Output:** "134 " **Example 2:** **Input:** num1 = "456 ", num2 = "77 " **Output:** "533 " **Example 3:** **Input:** num1 = "0 ", num2 = "0 " **Output:** "0 " **Constraints:** * `1 <= num1.length, num2.length <= 104` * `num1` and `num2` consist of only digits. * `num1` and `num2` don't have any leading zeros except for the zero itself.
null
Math,String,Simulation
Easy
2,43,1031
719
hey everybody this is Larry this is me doing extra bonus question on October 8 2022 I haven't done as many bonus questions as whatever I've been just uh not sleeping well to be honest I have some I don't know uh I'm working on it we'll see what happens but yeah that's the short story so yeah let's kind of do one problem that haven't done before I have about 800 of them that I haven't done before so it should be easy but there is a lot of Premium ones like this one so I have to keep on clicking Let's uh try again uh okay so let's go uh print fubot alternately suppose you're given a code oh this is a this is uh what you may call it this is a multi-fread problem which in Python is a multi-fread problem which in Python is a multi-fread problem which in Python is I don't know how they do it in Python actually um yeah I have no idea how to do this in Python so I'm going to just do another one not gonna lie uh maybe I have to read up how they set it up but uh yeah and of course I've done a lot of Premium problems I have to subscribe maybe one day I'll subscribe just to do it but as you can see there's a lot except for apparently transparency uh cocaine C problems okay there we go 719 find Cape smartest pair of distance okay so you have a and b uh the distance is a minus P absolute um and K find the cape smallest distance between all pairs huh and this let me ten to the fourth so that means that if we try to do the naive and to the fourth and then sort it that's definitely going to be a little bit too slow the question is can we do better right so um so it's going to be pretty tricky either way so I have to think about this is not a easy problem for sure the only wait is it uh distance okay um so I mean so the um the other thing I was going to say is that because of this K constraint meaning that there's no essential constraint on k being that it's just a valid entry um you know you can't do anything based on K like if you try to do a heap based on k or something like this at least not directly um that doesn't matter because K is going to be of n square right so if you have K times even or one that's going to be N squared is too slow um so the thing that I would try to exploit is this thing 10 to the six what does that mean right hmm that means that for me it means that I can do a binary search but let's see if it's going to be fast enough right so let's say we have 10 to the six what does that mean right um so let's say n is 10 to the fourth if we um if we do a binary I mean in this case there'll be two binary search just to be clear we'll do one binary search so 10 is 10 oops ten thousand um so we do the first binary search uh it's going to be around like 15 something 16. I don't even know anymore 2 to 10 times 4 so like 15 right so yeah oops so yeah so times 15 is going to be log n because then now what my idea is that for every number of research for a given answer right and then now we do another log of 10 to the 6 this time and 10 to the six is maybe like what um less than 20 right say so that means that's going to be our complexity roughly speaking and 20 times 15 times 10 000 is 3 million which should be fast enough but this thing lead code and this being uh yeah this thing lead code and python um who knows is the answer so I'm getting like messages from a buddy uh I should say hi because I keep on missing her messages but um uh yeah foreign okay sorry friends this is live so you can kind of see my DOT process and my DOT process apparently said I'm really distracted so let's give it a spin um I know that I skipped a little bit on the details but the idea now is to binary search on the answer um and just to be clear the end I didn't make this clear so I'm saying it for the first time and I'm going to try to say it clearly for the first time and what I was going to say is that the answer has to be between 0 to 10 to the six right um yeah because um because the biggest difference between two numbers is that most ten to the six so the answer has to be ten to six so then now we can do something like left let's go zero why does it go to ten to the six and of course this is why I said um the 20 thing 20 is actually 10 to the 7 but you know this is just a rough estimate right so this has actually even better for us um yeah and then this is regular binary search on the answer okay yeah someone like this right and then of course in the usual fashion I do if good admit um so I haven't done a full binary search video lately so hopefully maybe this is one um I need to set that video out but because I recorded like four months ago this is actually kind of lazy for my part but yeah um so the idea here is that okay if this number is good what is even good mean right so let's actually Define that a little bit so good um of Target right what's it what's the target is such that number of pairs that are we might have to change that I'm not clear on this one because these things are I always get off by one so even yeah we might have to think about this but the smallest number the number appears so we're just finding the cave pyramid right KP means that there are K minus one smaller K minus one or more smarter targets uh or given a certain answer there is less than K things to it I think there are fewer than k pairs that are smaller someone like this one is for me like very hard these kind of things the um the cave smallest because of the distinct value if this thing is easy but if it's not then some I sometimes get it wrong so that's something that I'm only saying it because um I'm just going with my thought processor obviously but my idea is that like this is something that I keep in mind of so that when something or if something does go wrong later I'll be like okay I know that I was concerned about this part and this is about knowing myself so let me revisit that point make sure I understand it but for now let's get to it right if there are K4 pairs then that means that this is um then we have to go bigger right um mid can be the answer so but if I have to go bigger because it may be too small so okay so left is equal to Mid um and then else rate is equal to Mid minus one and of course then we have to add plus one here um and then we just return left in theory yeah I had to think about this one a little bit this I mean like I'm thinking about like this case but we can finish writing it and then we'll see um the idea here of course is um and we forgot to do this and by we is because you know I don't know okay sorting right uh wait what am I doing yeah uh what am I doing okay I think I have an idea but um I forgot right it's not gonna lie yeah um so basically well there's two binary search right um because basically for a Target that is a solution wait um the distance right so this is the target's distance and that means that we're trying to find um for I find minus I and plus I right so basically we have something like this um so index is equal to um well right we have to do it for X in nums right so this is x minus Target um and of course I have to actually this is enough thing this is the thing um index left but I might have to fix some stuff but that this is the idea right someone like that and hopefully this is gonna be fast enough to be honest okay but and then now kind of do an index right um so we actually we won this minus one and then now because we know that by definition X is going to be inside this thing we can just do um total is a count is equal to zero and then we do count we increase by Index right minus index left we want to my uh plus one because we have inclusive bounds and then we're gonna minus one because we have X so this should be maybe good and then we want to count that count is um so this these are the numbers that are uh Target or smaller right so that this is a number of pairs that are Target or smaller so this means that yeah so we want this to be less than K I want to say but I am so not confident about this stuff is hard so let's run it real quick and we got it wrong the first one uh oops see Daisy but that's actually also wrong anyway okay that might just make it slower um expected zero oh maybe we have to do like a minus one thing but that doesn't change the or shouldn't change the answer that much anyway but let's see and here we can actually choose Max of nums just to make it slightly easier did I get at least number two right now I get 10 000 as well no one why do I get one I messed this up so that means that um do it with good maybe I'm uh in worst of what I mean so a good means that we have K or fewer so we want a bigger number right did I say that yeah so we want a bigger number to hopefully get to the other side but yeah this should be right so maybe this part is wrong all right let's see oops what did I click on did I submit I hope I didn't submit I guess I did submit that should not be a shortcut key I think I complained about this the first time I seen it but it made in the old one I think they got rid of it um but or maybe in contest it got rid of it but apparently it's still a shortcut and I made it by accident who needs I mean who is that like needs to save half a second to click on submit and get a five minute penalty instead I don't know but uh okay let's take a look at this one so the first Target is one because it's gonna be zero one these should be inclusive okay that's right so then the first number to try is one uh it's one good six is definitely get higher than six five um I think I did a mistake here because there's not six pairs right I think I um maybe that's why because I'm double counting from the other side and this is unlike n times yeah okay that part is fine hmm I mean I could think of another way of doing uh you know we've sorted list or something but I'm trying to think without it first well I'm also being silly this is not that necessary um I think you can do sliding window right you can find maybe you could binary search for the first time or whatever but then you could do a sliding window from it right you have middle and then just keep on moving the left and away so we can so there's one place where we can make uh we can speed this up but the pair backwards thing is a little bit awkward um okay I get it um I think I was trying to be too clever with this sliding window thing on left and right but actually we only have to look at the numbers to the right of it meaning the numbers that are bigger because of the numbers that are smaller that uh on or you could I mean on the left of it then you can assume that the left pair already took care of it right because of this symmetry we can also maybe just divide it by two to be honest but um okay let's do it by two real quickly um just to kind of uh see but I think there are a lot of places for optimization that we just talked about even though I accidentally could not submit but um but we can kind of start with this um yeah okay this is not great still because three years clearly cannot be the answer what I have here this is just me putting out one again okay what if I do K minus zero one I mean it's still going to be one because it shouldn't be drawing why is it moving hmm we print it again uh Target okay I don't know what shortcut is for submit but that's a very sad shortcut okay so distance of two we have three pairs that's is that true so we have one three let me try to work it out manually right um just to kind of trace the code a little bit so we have one three so this one which we found two numbers this one we found two numbers and then this one we found two numbers so that's six divided by three is two oh uh divided by two is three but that's also true did I misunderstood something one three just all the matter what it doesn't matter right yeah no one three one yeah I guess so there are only three pairs right so and all three is good so okay so then the two it goes okay the three numbers bigger uh smaller um so count is greater than one so that means that we want a bigger number that doesn't make sense right I think I messed up the sign again I guess that's it um because if there are more pairs then whatever yeah okay Larry you're silly goose okay fine I don't know why I said it that way though okay let's see again okay so at least now we make we're making progress we got the first two correctly even though who knows if it's like from Salinas or not I have one six one the answer is so I think this is the part where I was worrying about because four is not a possible thing in here um but we're returning the first case in which the K minus one number smaller I think that's the problem so what we want is actually one the first case where this is true um and maybe that should be good but now maybe we don't need to do K minus one uh let's see because we want to find the first case where this is true and where to subscribe to reduce rating time and also turn off it autocomplete apparently um okay so now this is very well we want to uh this is always troubling for me we want the first number uh this is the part that I said I was going to struggle with and I proved myself well I'll prove myself correct because this is the first number in which um this is the first number in which there are uh um bring this back you know that's an actually a little awkward um the reason why this is four is because this is the first way is it no because this the pairs should be five oh so this is the biggest number where there's two case smaller okay so how do I fix it we wonder so this is the okay to them instead of just as good actually we want this to be plus one and then just maybe this is good I think because we want now is it so this is good yeah we want the first case where this is true okay let's give it a quick submit this may timeout but we have we talked about some stuff to optimize okay well that is just sad it also is the same uh kind of issue so let's see what am I doing here come on 38 is not even oh actually it is a possible answer but maybe I gotta got a number wrong right because 38 is the first one that's true why is that giving me well all right let's see because 38 should be when dirty a count is equal to 1 and K is equal to one well K doesn't change so we want the second number 38 should not I mean the first number is 38. right so then it went smaller after that doesn't make sense right um I think maybe I just have to do this okay yeah I think when I change the signs I should have thought I mean not that I should have thought about it but what I should have done is just tested it to be honest because this is very testable right like this is literally a vanilla three numbered answer but uh but I'm just lazy and this one and yes that one was harder than to expect well I mean terrible time because like I said there are a couple of optimizations that we can do um for example this is log n or n log n uh let's go over the complexity right so this is um the let's say um R is equal to range meaning zero to Max nums right and then you have log R is this obviously there's a number of iterations here good it's going to be n log n the way that we did it right so this is and like and um so then in total so in total the time complexity is going to be all of n log n Times log r and oops I didn't submit again I don't know uh and then space complexity of course is just of n because of this sorting again I mean uh that's how I always say where we saw it then but of course we can actually reduce this uh log n Factor by using a sliding window right um and also just not double counting I think so we can let's do it today I'm feeling optimization D so let's do it of course you still have to do the Sorting so this is going to be plus and login anyway but at least you don't multiply them which is kind of ridiculous but yeah first of all let's we can do index right to kind of look only to the right um and then this is just of course enumerate and then this is of course just like I plus one um but inclusive um right so then you plus one again to include the bell and then of course this cancels out so you have something like this um and then now we don't need this and it should be slightly faster hopefully correct first and then we'll yeah uh let's submit again okay yay we moved from five percent to twelve percent okay but like we said we can still do this with sliding window right um yeah right because basically you want to uh let's say yeah let's see let's say we just do on the first one because I'm too lazy to do it uh and then you have nums num sub zero plus Target right so you have Index right and then here for every new I um what are we doing right so while index right plus one is less than n and um and num sub Index right minus X is less a greater than or less than or equal to Target then we Index right increment by one right this is actually plus one because we assume that the current index rate is good um right and then that's pretty much it I think let's run it again make sure it's right maybe off by one is where I use it off by one and I forgot to do it well I guess I just didn't I usually have it uh write it very quickly but I guess this time I didn't really need until just now I'm okay so that looks good again so let's give it something cool now we're in you know average 56 category I feel a lot better and of course now um you can see that this I mean there's a lag n here but there's only one login it's gonna be dominated by just of n um so this is just going to be all of log r i mean n o of n log R times R plus n log n so that's much faster and much happier for me um you may also wonder why this is like uh this is all and even though the two for Loops essentially but you can think about Index right can only go up to the right like um it can only just this particular statement can only increment off and time so it gets amortized that way um so in aggregate this is gonna be all then um yeah that's pretty much all I have with this one so let me know what you think yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
Find K-th Smallest Pair Distance
find-k-th-smallest-pair-distance
The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`. Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`. **Example 1:** **Input:** nums = \[1,3,1\], k = 1 **Output:** 0 **Explanation:** Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0. **Example 2:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 0 **Example 3:** **Input:** nums = \[1,6,1\], k = 3 **Output:** 5 **Constraints:** * `n == nums.length` * `2 <= n <= 104` * `0 <= nums[i] <= 106` * `1 <= k <= n * (n - 1) / 2`
Binary search for the answer. How can you check how many pairs have distance <= X?
Array,Two Pointers,Binary Search,Sorting
Hard
373,378,658,668,802
856
Ajay Ko Hello Hi Everyone Democratic Setup Coding This Video Pyaar James Ko Parents are going to solve this question let's see what is spraying barfi that the previous one pin is mixed add space only opening and closing date will be there and this trick is some This scoring has been completed according to Russia. You have to tell how much score this train gets. Let's look at the basis of points. The first one says that if there is an opening and closing racket on Shivling, then the one who has it is Let's see on the next one, if this and also both of them were the first Spain Spring Halt Spooch, this guy and Agyeya guy, each of them will form a spring on catination, meaning if you a string would be in something like this form, there would be a balance of 21 velvets on it so that This one which was made a year ago would have been an edition of these two, who has it, OnePlus One, the latest one, we will see the third one here once again, I will stop according to the second one, if there is any Valentine's Day spring hello thought that if I have made this one Doctor Paramjit is surrounded by this, so who has this whole, this one, the current of this one, this is the way, so this time it happens, let us look at this case once again that if there is a spring, this whole And one more swing independent, this guy, Gorakhpur, one against this, the delegates are furious, if both of them are updated, then the whole sting is made, it is okay in this phone, who will have it, itne kasam plus kitne ka s meaning 414 time five This is the problem, garuds, we have seen it, so how do we apply a test and see that this is a test case, so the first closed in this is the one inside this one we know that you will have this youth of 0 so many people's score one now this If I write it again, here one after opening it, this is the point of ignorance like this is our third, it should go according to the rule, all this time, there is one person here who is closed since Valentine's Day and this is the balance. Differences, both of them should go to school for free and this one from outside has done this, Agyeya has done this whole complaint, he will have that complaint about the insider, then if you do Lokayukta, then this is what was to be done on this question, then for victory on the basis of three Russia, you will come out of preserving. So now you can fry it and let's read and how to do that this time if we look at these three garuds then the first rule is this string on it is absolutely independent, meaning it is dependent on some other balance parents. Does not do so and secondly, if we look at these two Russia, then this guy on this one is A and B, which means it is dependent on the score of some other parents, then the third one is also similar to this guy who is complete is on the overall score of A. If it is dependent, then on calling this question, the effort will be to first call the one which becomes independent and then as soon as the independence is complete, we will call these two gases also. Okay, so let's work on this media once. Yes. But then how would this test happen, my father, that this one which is tied here is completely independent from then onwards and this one who is locked is not dependent on anyone else, if I welcome both of them, one will become Play Store and the other one will become It will become one. Okay, now this guy has become Saurav, it was dependent on this voice changer, he was dependent on it. When it became small, it has become a giant, it has got all the juice, it will become stars of one, it has become two more. This is what we had folded, okay, now let's see that the two guys here have been done, so according to rule number two, if something like this happens then it should be long, here it goes to 3 A. Pre pregnancy is complete. We had solved the again lost case of Vrindavan. According to this case, it should remain two times off, the pick will be melted and doubled. If it is okay, then our idea is basic idea, so this guy of this species is independent. But those whose dependency is complete, hand it over to them and then keep moving forward with such process, the entire spread will be solved in a day. Okay, so here for that, parents have to be given priority, call first and then this ancient work will be done. I have taught about this in another video, we minimum remove parents, so its gender will be found in the description, after seeing it, you will understand the algorithm better. Even if you see this, it does not matter, I am going to screen the algorithm here so that we can see it. How do we use that garden? Again, first I saw the guy, Rao, I will put it in one of my special data structures which is going to be a check later, I put it open, now if the net is closed, I saw an opening. There is a racket and then the next one came why Singh again, this is what it is going to be years, both of them will share the rights and we know one, so in this case, I am going to remove them and keep one in their place, do n't think about the implementation right now. These are characters, numbers have different, we will do it later, let's see the accused, will you make it here, I showed it to the next guy, I showed the opening racket to the next Sunday, I saw the opening racket, the next guy saw that Hussain racket, Agyeya, both of them together are making Purva One, so remove them. Do this and put these in their place, A Pun Next Gun Singh Racket Okay, so on the case that this is the whole thing, this year is ready to happen, then I am going to hate Pimpri-Chinchwad ready to happen, then I am going to hate Pimpri-Chinchwad ready to happen, then I am going to hate Pimpri-Chinchwad until I get the opening credits. I will add all the stringers of the temple, right now there is only one here, so I saw that the content inside is completely made up of him, so what should be made of this whole stringers should be the fear of this guy, so double this guy. Here we replace overall, this will be completely removed and will be replaced by that U Now these are two different non juices, the next created project is using back, so ignorance, we have to work till the opening back, this time if If you see, this is a case with two valid parents, this guy will wait for this one, this subscribe, we have to add both of them, only then we will be able to solve the problem, I know both of them, one and two, so this case. But what am I going to do, when the crossing racket comes, I will add all these brothers till I get the opening racket. Okay, first of all, I got this guy, let's offer him now, before the fair-2012, if before the fair-2012, if before the fair-2012, if I make you the head, then it will be complete. The time and it becomes 3, so in this case the whole solution inside is three and when the project is removed, it will be completely doubled. Method, so this is just a mistake, okay, so we are going to do the same thing, let's look at it once again using the track. Okay, we will talk about our current situation and write down all the steps. First of all, let's see what we put on our potato's highest data structure. So, as we saw earlier, the printhead comes. Or the scoring comes. Right, if we look at both of them, this one will always have a positive interior. But this guy is a character. If we look at it from the other side, then it is not right to keep these two as an integer and a character. It is a bit difficult task. What are we going to do about this? Here again if I have positive entries then I can flag the negative values ​​and zero like this. then I can flag the negative values ​​and zero like this. Akbar does the right for the opening racket. I will use the negative like this for flight on this opening night. Once this is done, let's see how to do all this. The first element is tied, so this one is the leader, so let's put it so that it becomes easy to stitch. Your test will go - One is fine. When the becomes easy to stitch. Your test will go - One is fine. When the becomes easy to stitch. Your test will go - One is fine. When the opening racket came, I simply made it happy on the track. After this I did the next opening racket, I made him happy, I am going to top you now, a losing racket, until I get the opening credit, I saw that the first guy is also the opening date, so the case of the agnostic independent one is upset and said like this, the case is its I know that he should be tight so on this case that I will remove this guy from both the places and here one score will go. Okay, so what have I replaced in so many cases? Ajna Opening Racket - Ajna Opening Racket - Ajna Opening Racket - 1m Rocket Minus one project, if this is made by both of them, then I removed it got stuck on the tree, one a, that is so many cases, I have replaced it again vansh, ko again, after this came the closing racket, this time whatever is this case becomes this. So let's be clear, what has to be done in this house, I have to up until I get the opening racket and whoever is in between, I will counter that I will make this one here, this is the one. This time I wanted this tight but I got it, I took out the opening batsman and for this whole, the juice of this whole would have been made that so many cases of Pooja life in a till date, here is the next tied count problem racket, this time we just have to do it. But the answer will not be found, the topic is not my answer, but I will have to add these two as well, right, this is something like A+B, how did you say it, first something like A+B, how did you say it, first something like A+B, how did you say it, first these two will be included, A+B+, she will take the these two will be included, A+B+, she will take the these two will be included, A+B+, she will take the complaint and then if you fold it, then IS Aaf Thi, something like this is going to be made, this will work, if we remove the approaching, then first of all we have to check, how can I become one, it is possible that the male deer has kept the opening on the text itself, meaning - if kept the opening on the text itself, meaning - if kept the opening on the text itself, meaning - if you pick it, then the minus one's. The space will open up and if -1.2 is not involved in the racket and if -1.2 is not involved in the racket and if -1.2 is not involved in the racket then we will have to add it by cropping. Okay, the s of these two will have to be seen separately. This time it is one plus two. It will be three that I have tipped Laxman to both of them and against because this is a crossing racket, show me how to open in this racket, I got rich, so I stopped the work and the one who has the responsibility of this whole thing will become the teacher after removing the choice of three leaves. If you have one, then let's do the same thing, let's make a jhal. Worry about it, I can go to the office, I have to treat the opening racket like a minus one. Price - 190, you can take it, treat the opening racket like a minus one. Price - 190, you can take it, treat the opening racket like a minus one. Price - 190, you can take it, but according to your own, a jhal is fine, tomorrow Gautam. According to both, how what was to be done on this, on the opening and closing date for lips, on the opening night way, so we are directly on the track of our Pushkar, see the opening date on this case - I have done Pushkar, see the opening date on this case - I have done Pushkar, see the opening date on this case - I have done something to them, next time I will have to do it for the employment person. Sperm has to be considered that there is a cloth at the top of the track, then this child does it. If there is a minus one on this pick of the track, it means that this opening and closing was an independent case, hence one is okay, first of all. That let's pop that opening racket minus one and thank all this dough that now the second case that is made is this now you or the closing racket campaign got the closing racket but there are some guys in the middle of it okay plus wash Will it be or will it be so on the gas we had to add till we do our practice. Everyone is okay so here we take the value audio till then pack dot this pick is not equal to minus one so we add on the value. On this case, you can think that if I am checking directly in this Fragnet back, then if the surprise track becomes empty, then such a case will not happen because the one who is bringing is the balance, if the spring is the balance, then this day is an opening for you. If there is a racket then I will get this at some point or the other - then I will get this at some point or the other - then I will get this at some point or the other - this is the last introduction after doing this work - there will be an opening racket, we will last introduction after doing this work - there will be an opening racket, we will last introduction after doing this work - there will be an opening racket, we will remove it and then the whole jograj and that is your voice of value. Okay, so you can do yours. There has been a lot of improvement in the algorithm, which I had to do, what else is left, maybe this guy will be for free and not one, let's see if some such cash is available, here my dear two are made, okay I mean This entire thing would not have been covered. Had it not been covered then the one at the end of our track would have been one and wild. Even after completing the entire work, we would have had to add the right here. After completing all the work, when I One more time, team work is fine, let's repeat the team work and add on Kallu, till the time it melts, we will not get it, or this time it should be Taj Residency, I want to add gun sometime, I have come and said that the present should be almost complete. It has been decided that this is the right answer for whom all the PMs of the house are doing the solution, we can make it a little better, change it a little on the hot logic, so how when I get a situation like this, I have these from my project. There is one person inside and there is more closed, I basically add everyone in this turn and if I don't have anyone inside, then for this I imposed a separate condition and checked that if direct opening Rathore School becomes one, then the implementation should be a little. If you can do better then the logic will be semi. If we talk in the name of implementation then add all the brothers inside. It is okay if there is no one inside then the pain would be zero and if there was someone inside then they would have some positive thing or the other. So you can implement this on the S of these two. Now check if the value is in place, it means it would be the case, close the volume on it and add it. Other wise, the price of these mantras on this track will be this. If the turn is fine, then one case was solved and the pain of the other one was later seen that after processing the entire string, it had to be added again in the end. This case is for when two people are like this and We have to set it completely, you can do this by handling this case of yours from the album but only handling it which can present such bracket song outside which is your address problem outside it. Also two more such brackets, the method is this time as soon as you come to the track, you push minus one and then after processing this entire string, you do April-June on cigarette length that you have do April-June on cigarette length that you have do April-June on cigarette length that you have got a hero cigarette. Okay, so here Joe If you had moral support, this guy has a governor and if you have him on the track, then it would have been great if you could have done Yagya and read the original, so keeping these two things in mind, you can make its implementation a little better, okay? If so, see you in the next video with the next question. Thanks for watching.
Score of Parentheses
consecutive-numbers-sum
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
Math,Enumeration
Hard
null
1
foreign hello everyone and welcome back to another video So today we're going to be solving the lead code question to some all right so in this question we're going to be given an array of integers called nums and an integer called Target the goal here is to return the indices of the two numbers such that they add up to the Target and there is going to be exactly one solution cool so let's just look at an example so let's say we have a set of numbers and we have a target of nine so basically what two numbers add up to nine in this case it's the number two and seven and we're going to return its indices which is zero and one pretty simple so let's actually first look at a Brute Force solution right so this is going to be pretty obvious we looked at all of the possibilities with two for loops and we add those two numbers and if it's equal to the Target we're going to return those two indices now an obvious problem with this is a Time complexity this is going to take Big O of N squared time complexity and especially the length of month could be up to 10 to the power of 4 which is really big so we have to try to come up with a solution that is less than Big O of N squared hopefully in linear time so let's actually look at this question over here and try to come up with a better solution now obviously in this case the target is 9 the two numbers that we want to add are 2 and 7 and in this case the indices I'll just write them over here so those are the indices we would return are zero and three right but how exactly do we come up with the solution in a linear time right so let's actually go through this area let's iterate through it and try to extract information now we have the number two that's the first thing we get right now what information does this tell us now the first obvious thing is that we know that this number exists right so whatever number we go through we know that number exists in the list obviously and but this also tells us one more thing we can find out 2 plus what number let's just call it X is equal to nine and obviously that is nothing else but 9 minus X so in this case what number when added to 2 gives us 9 well pretty obviously nine minus two is going to be equal to 7. now what this tells us when we go on the number two that tells us we have the number two and it also tells us that if the number seven also exists we have found a pair that when added up is going to give us the Target right so whatever number we go through we can find out what the under other number should be to get a valid pair which adds up to nine right so this is what we're going to do now if at any point we come across this number over here that means that we have found the pair that we're looking for right so let's just see that so in this case over here the next number is 11 okay so we have the number 11. now what number when added to 11 will give us 9. 11 is greater than nine so it is going to be a negative number and in this case that is negative two right same thing with 15 right so 15 and remember each time we're checking if uh whatever so if 15 mean isn't any of these two values it's not so we look keep going on right so in this case 15 uh 9 minus 15 so that is going to be minus 6. so this tells us that if there is a minus six that is going to be a valid pair so now finally we go on the number seven and seven exists in this list over here so what that means is the other number which in this case 9 minus seven is two the number two has already been visited so that means we have found our pair right so now we found the pair but what we want to return is the indices now how exactly are we going to do that now a simple thing is what exactly are we storing so we're storing these values over here right 7 negative 2 and negative six so instead what we could do is we could store it as a pair right or instead specifically as a map so instead what we could do is we could say the value seven so now we go on the number two right so the next value that we want to look for is seven right and we can also keep track of what index is the current value on so the current value with the which for what we need to seven is at the index zero right so this means that the first value 2 is at the index 0 and if we find a seven we're going to return that index and the zero okay so I'll just show you what this looks like so now we go on to 11. so the other value for 11 that we need to get a sum of 9 is negative two and eleven is at a index of one and similarly for 15 we want a value of negative six and if it exists we're going to return it with the index 2. now we finally go on to the value 7 over here and the 7 exists inside of our dictionary since 7 is in the dictionary that means that we're going to return this index itself which is the index 3 and whatever index that is over here so we found the value 7 its index which is the current index and the pre previous value which is 9 minus 7 2 is index which is zero so we're going to return 0 and 3 and that is going to be our solution so let me just show you what that looks like in code as well all right so the first thing we're going to do is we're going to initialize our dictionary over here uh now we're going to iterate through the numbers so we want to get the index and the number so we're just going to enumerate through our list so if you don't know what that does it's going to give you the value itself and the index together okay so the first thing we're going to do is we're going to check if this current number is already in our dictionary right so if num in dictionary now if this is the case we're going to do something but if this is not the case we have to add a value to our dictionary now what value are we going to add now the value that we're going to add is going to be the remaining value right so even in this example over here we added the 7 which is the other number that we are looking for right so we're going to add that value so that is going to be nothing else but the target minus num so we're going to add that value and we're going to have a value of the current index so when we added 7 we had a index of zero so that's going to be equal to the current index that's it okay so now we have the condition of if we have found the number so exactly over here the number seven we have found the number seven in the dictionary so we just need to return the values so we return whatever is in the dictionary the value there and the current index so that is just going to be return so we return I'm sorry so we return that value from the dictionary so D num and we're also going to return the current index and that should be our solution so let's submit this and as you can see our submission was accepted so thanks a lot for watching guys and do let me know if you have any questions
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
509
welcome back everyone we're gonna be solving leak out 509 Fibonacci number so the Fibonacci numbers commonly denoted F of n form a sequence called the Fibonacci sequence such that each number in the sum of the two preceding is the sum of the two preceding ones starting from zero to one so if we take a look at example one right they give us an input of n is equal to two the output should be one because F of one plus F of zero is going to be one plus zero is equal to one right and we can see this in the rest of the examples so it's just the sum of the last two preceding numbers excluding zero and one zero is going to uh return 0 and 1 is going to return one so uh we're gonna solve this recursively and with memorization so we will have another helper function we're just going to call it underscore fib this helper function is going to take in the current number that we're at along with a memorization object okay so to solve this recursively we'll say if n is equal to zero what do we return well the Fibonacci number F of zero is just zero right so we can just return zero if n is equal to one all right we can just return one otherwise how do we calculate the Fibonacci number well it's just uh return FIB of n minus one plus fib of n minus 2 right and this would give us a Brute Force solution but we need to solve this with minimalization to speed it up right so let's just say if we wanted to run this we could copy all this and put it in here and this would run so let's do this just so everyone can see right so it does run we'll submit this right so it's pretty slow right beats 23 percent of submissions and normally I don't check out Delete codes uh run time just because it's unreliable but now let's do this with our helper function so we can see how much faster or how much speed up we get so to memoize we are going to say okay so if n is in our memo object we're just going to return memo of n and then instead of returning this we're going to put this object inside of our memo so we'll say memo of whatever current number we are at is going to be this object and then we can just return memo of n and then we also are gonna have to return our helper function call up here so we will return self dot fib and pass an n and then our memo object is going to be an empty dictionary so let's see here oh we also have to pass along our memo object to our recursive calls now we can run this hopefully it still works yep submit and there we go see we went from what like 23 all the way up to 85. so this uh is going to give us a time and space complexity of O of n for both all right that'll do it for Lee code 509.
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
84
the problem of finding the largest rectangle in histogram is a very interesting one given a list of integers denoting height of unit width bars in a histogram our objective is to find the area of largest rectangle formed in the histogram there are various solutions to this problem and while most of them have a quadratic runtime the optimal solution however runs with a linear time complexity although it requires linear space complexity as well the core logic behind the solution is to iterate the array once and for every element find the area of largest rectangle which includes the current element completely the maximum area of all such rectangles is our desired solution to achieve this let us consider the bar at position i if we can find the first bar smaller than it towards the left and towards the right the rectangle form between the left and right bars with the height equal to ith bar will be the largest rectangle which includes the ith bar completely if we can do this for all the bars in the histogram in linear time then our job will be done this task can be done very efficiently using a stack or more precisely an increasing stack to create an increasing stack we iterate through the array and for every element we push it to stack if it is greater than or equal to the top element of the stack or the stack is empty if we encounter an element smaller than the top element we start popping the elements from the stack until we find a smaller element in the stack or the stack is emptied at this moment we push the current array element on the stack now if you pay attention here an element is popped from the stack as soon as we find the first array element smaller than it as we iterate the array from left to right this gives us the first smaller element towards the right of popped element also notice that since we are maintaining an increasing stack the new stack top will give us the first element towards the left of popped element which is smaller than it as discussed the rectangle form between these left and right smaller elements with the height equal to popped element will give us the largest rectangle in the histogram which includes the popped element completely we store this value as maximum area that we have found so far moving ahead since the new stack top is still greater than the current element we pop it from stack for this bobbed element the right smaller element is still the current array element which is responsible for kicking it out of the stack as before the left smaller element is given by new stack top element as we have an increasing stack and as you might have guessed the rectangle formed between these left and right elements with the height equal to popped element is max rectangle for the popped element since this is greater than our previous max area we update the max area with a new value the stack top element is now smaller than the current element so we push the current element on the stack increment the counter and repeat the same process again since we have an understanding of the core logic now let us see how to write code for this problem we will need an integer stack and a couple of variables to keep track of current and maximum area next we start iterating the array from left to right and push every element to stack but before we do that till the stack is not empty and the top element is greater than our current array element we need to first perform some area calculations we pop the top element and the max area for this element is given by but this is true only if the stack is not empty if the stack is empty then length of rectangle is to be considered from beginning of the array till i minus 1 which is i units once we have the current area we update the max area found so far once we have iterated true array if the stack is still not empty this means that there was no element smaller than the stack top which could have kicked it out of the stack so in the absence of write smaller element we will need to consider the end of the array for our calculations the rest of the code is similar we pop the elements one by one calculate the area of rectangle for both the cases and update the max area once we are done with all the elements return the max as our answer as you can see every element is pushed and popped from the stack only once the area calculation is done once every time we pop an element from the stack therefore the runtime of this algorithm is linear in the size of input array although since we are using a stack for temporary storage which in worst case can hold all the array elements at some point of time the space complexity is also linear in the size of input this problem demonstrates that stacks can be used in surprising manner to solve seemingly complex problems which otherwise require quasi-linear or which otherwise require quasi-linear or which otherwise require quasi-linear or even quadratic runtime there are other such surprising use cases of stack which i will tackle in future videos till then keep coding
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. **Example 1:** **Input:** heights = \[2,1,5,6,2,3\] **Output:** 10 **Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. **Example 2:** **Input:** heights = \[2,4\] **Output:** 4 **Constraints:** * `1 <= heights.length <= 105` * `0 <= heights[i] <= 104`
null
Array,Stack,Monotonic Stack
Hard
85,1918
2
hello guys welcome to another video in the series of coding today we are going to do the problem which is called add two numbers so you are given two non-empty linked lists representing two non-empty linked lists representing two non-empty linked lists representing two negative integers the digits are stored in reverse order each of the nodes contain a single digit just add the two numbers and return the sum okay let's try to take an example we have 243 and 564 as the example so let me take the example you have 243 as one of the linked list and the second linked list is 564 right so what you have to do you have to add the two link list so let's add the two link list if i add 2 plus 5 what do i get 7 so we have to write 7 here now let's add 4 and 6. if i add 4 and 6 what do i get 10 right i get 10 so instead of writing 10 here i'm only going to write a single digit so what will i do i will only write 0 and i will carry forward one okay three plus four is seven plus one is eight so then i write eight okay that's it so let's try to take more examples so that the logic becomes clear and maybe this example is not sufficient let me take some other example let's say we have 3 6 7 2 5 something like this and let me take another link let's say we have 2 8 4 9 something like this okay now let's add these two linked list so now we are going to add these two linked list 3 plus 2 is equal to 5 so the first number is 5 then 6 plus 8 is 14 so we don't write 14 because we have to write only single digit right so we write 4 and then we take 1 as the carry so 1 becomes our carry over now we are 7 plus 4 is 11 plus 1 is 12 so we don't write 12 rather we write 2 and we take 1 as the carry over now 2 plus 9 is 11 plus 1 is 12 so we don't write 12 we write 2 and we take 1 as the carry over right now we have 5 plus 1 is equal to 6 so 6 this is your final answer ok because you are adding in reverse order so i know this is not the way we do addition uh it's different from that but in this question we have to do addition in the way that they have given okay let's take one last example and then we will move forward to coding it so let's say we have nine eight three six five something like this right and let's say we have one more linked list we have three seven six one something like this okay let's add these two link list so what we are going to do we are just going to add the number so what are you doing you have the first link list you have the second line just add the two values now 9 plus 3 is 12 right 9 plus 3 is 12 so now instead of 12 what do you have to write in the new link list in the new linked list l3 you have to write 2 so what is 2 is what if you just divide 12 and you just take the mod right if you take 12 or 10 you get 2 so what will you write here you add these two numbers you get the value you take mod with 10 and write that value here okay that's what we are doing because we are getting 12 but we don't write 12. what do we write 2 right so we don't write 12 we write 2 what is 2 is just 12 mod 10 so we have to remember this okay now we have written 2. so now what is the carry is 1 how do you find the carry the value that you got is 12 right but if you divide 12 by 10 you get 1 so 1 is the carry over okay because your number is exceeding 10 12 is greater than 10 so you have a carry so you have to take this carry forward so you get carry and carry is one so let me write here for the next iteration carry is equal to one now let's add these two along with these two we will also add the carry eight plus seven is fifteen plus one is sixteen okay so f what is the number that we finally get by adding the two numbers and the carry we get the number 16 but you don't have to write 16 what do you have to write 16 mod 10 what is that 6 so what will you write here you will write 6 here and what is the carry over you got 16 right 16 by 10 is one so one is your carry for the next time so again for the next time you have one as the carry okay now let's add these two numbers 6 plus 3 is 9 plus 1 is 10 the number you get is 10 now 10 mod 10 is what 10 mod 10 is 0 so what will you write here you will write here 0 and what is 10 by 10 is 1 so for the next time again what is your carry 1 is your carry for this time also so now 6 plus 1 is 7 plus 1 is 8. now what is your carry if you do 8 divided by 10 it is 0 that means for the first time you have no carry over okay now carry over is 0 for the next time so 5 plus 0 is 5 so you write 5 that's it right so it's very simple basically we have linked list you have to just take care of the carry and the reminders that you are getting and you will get the answer okay now let's move forward to coding it to understand this better so you have basically two linked lists right and you have to return one answer linked list so let me do one thing let me write list node l3 this is a new link list that we are going to make this is a new linked list initially let me just give its value as zero okay now what we will do we will iterate over both the linked list till when do you have to iterate both the link list should have some value right that means both should not be null if it is null there is no point in iterating over them so while both are not null we will iterate over them okay now let's start so what you are doing very simple you are taking the value in the first link list you are taking the value in the second linked list okay and you are adding the carry okay that's it these are the three things that you are going to do and you will get something and that something is called value so let me declare carry is initially 0 and as we change we get a different carry we will keep on changing the carry so what is carry basically carry is nothing see let's say the value of this is 16 okay let's say you add these two numbers and you get 16 okay let's say in the first linked list the value was 9 in the second linked list let's say value was 7 so you added both of them you got 9 plus 7 16 okay and let's say initially carry was 0 so what is the final result you get 16 so your value that you get is 16 okay now what will be the carry over for the next time will be just value by 10. so if you do 16 by 10 what will you get if you do 16 by 10 you get 1 so 1 is the carryover for the next time okay that's it that is a simple logic now we have the carryover now what will be the value that you will insert in the linked list right so in the new linked list that we are creating which is our answer you will also insert the value right but you will not insert 16 what will you insert you will insert six okay so let's insert six so i'm going to create a new list i'm not going to insert 16. if i give value what i will do in the new link list i will insert 16 i don't want that i have to do more 10 and insert so if i do this i will insert 16 mod 10 what is 16 mod 10 is 6 so i will insert 6 in the new link list ok that's it and now what i'll do for the next time l 3 will become equal to l 3 is next okay and similarly l one will become equal to l once next l two will become equal to l twos next so we'll keep on doing this and we'll keep on iterating one that's it the logic is this much this simple okay that's it so we have solved the problem okay now there's just one more thing in the end right so this will solve the problem when l 1 and l 2 are both of the same size but in the end if you have this thing left out right for example in this case till here both of l1 and both of l2 are valid okay but what if you have some digits left out l1's length is greater than l2 or l2's length is greater than l1 then you still have to take consider this case right so after exerting this while loop okay there may be still some digits left in l1 or l2 so if l1 has greater length than l2 there will be some digits left in l1 so what you have to do nothing you have to do the same thing just i will copy paste this code do the same thing just remove l2 that's it so wherever there is l2 i'll just remove that remaining entire code remains same right i'm doing nothing i'm just removing l2 that's it remaining entire code remains same thing i will do for l2 if l2 is greater than l1 what i'm going to do the same code i'm going to copy because there's nothing new in this code we have already discussed what this code is doing now here i will remove l1 that's it okay that's it so now this will work now finally what i can do now see there's one thing now when all this happens where will l3 be initially l3 will point here then l3 will point so let me write first l3 is here next l3 points towards here l three points towards this and then l three points towards this but what do we want to return the head right we want to return the head of this linked list so but my l3 has reached to the end right so but i want to return the head so i will have to declare some other head okay so let me declare some other head because i want to return the head not the end position l3 will reach at the end but i want to return the head of the newly created linked list so what i will do i'll declare some head pointer and make it equal to l3 okay now initially i just give a dummy value zero right so what i will do what i'll do i'll return heads next so what i'm doing here what did i do see very simple initially when i had no l3 right so let me consider the case when i had no l3 okay so what we did we created sub dummy node 0 after that we added 2 we added 6 we added 0 we added 8 okay now when we are iterating l 3 also moves along right every time i am moving l3 i give l3 equal to l3 is next right so finally see i have always given the statement l3 equal to l3 is next okay so l3 always reaches the end okay but i want to return the head now my head is pointing towards the zero so what i will do to return this head to return the final answer this linked list i will return heads next okay just i'm doing a simple trick so that i can retain the head and i can return this okay that's it that's the thing now this code will work except for one case okay this code will entirely work except for one case let's run and see what is the problem with this code see this code is working for one case it will not work and what is that case let's see this is the case for which it will not work why is it not working here what is happening see let's see what is happening here 9 plus 9 is 18 right then 9 plus 9 is 18 and carry over is 1 okay so 9 plus 9 is 18 plus 1 is 19. again carryover is 1 9 plus 9 is 18 plus 1 is 19 then 9 plus 1 is equal to 10 okay so we are returning everything correct but in the end there is still one carryover that is left and we are not returning that so we have to written if there is a carry over in the end we have to return that one see the expected answer is this but what we are returning we are writing all the digits correctly except this one so at last if you have a carry over you have to return that so let's just give that additional line so at last if you have a carry rate you have to return that also so l3 is next is equal to new list node of carry that's it this simple line of code will ensure that our code is working for all the test cases so let's see so it's working thank you for being patient and listening
Add Two Numbers
add-two-numbers
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[7,0,8\] **Explanation:** 342 + 465 = 807. **Example 2:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\] **Output:** \[8,9,9,9,0,0,0,1\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros.
null
Linked List,Math,Recursion
Medium
43,67,371,415,445,1031,1774
692
k frequency is given, then what do we have to return? We have to return the highest frequency of k. Okay, so in this particular case, the top two strings which have the highest frequency are to be returned. Okay, so if I If I look at this question, if I look at aa, what is the frequency of aa? If I look at this, how many is one and two? Okay, what is the frequency of love, what is the frequency of two lead code, what is the frequency of this word, one such coding. What is the frequency of is one ok then basically top two which brother is love and i ok then what do we have to return if the frequency is same return the answer sorted by the frequency from highest to lowest sort the word with same frequency according To lasso graphical order is ok so basically lasso graphical order means to sort in alphabetical order if the frequency of both is same then here we saw that the frequency of i and the frequency of love is the same what is the frequency of both if to is then first xographic order In or in alphabetical order, which one will come first? Which one will come first? Because i is coming first, which is the zero index in this string, which is the row index in this string, which is i, which is coming first, so which one will come first, a will come first. Not in alphabetical order, that's why we returned the answer. Then love is fine, I think the question must be clear, let me explain it a little more, so this is the question given to us. Okay, so here what is the value of pe, what is the value of k in such next case. Okay, so what will we do? Looking at this, what is coming to our mind is that we will have to create some data in which what should we do? Store the frequency along with the words, meaning store the frequency of every word, which one? The method is ok if we use unorder map then basically order map of type string int what will we do here we will take word ok for each word we will store its frequency ok then we will declare an unorder map inside which frequency will be stored And once we have got the frequency, okay for each word, then what we have to return is what is the value of k in the frequency of the most. We will sort, basically what will happen to us, what will happen according to now, we will have an unordered map, inside it the values ​​will be increasing, inside it the values ​​will be increasing, inside it the values ​​will be increasing, inside it the values ​​will be stored, one for each word, values ​​will be stored, one for each word, values ​​will be stored, one for each word, its frequency has been stored. Okay, now if we want to keep it in sorted form. What has to be kept in sorted form, it has to be kept in such a way that it is in descending order, according to frequency is fine and if the frequency of both is same then basically less graphical order has to be checked, after that it is fine, so once we have decided to store it. After that, we have sorted it, okay, after placing it, we have sorted it, so basically after that, what is left after that is to take out the top values, that's it, okay, whatever I sorted, what will I sort it in, I will do it in vector, okay because map. If I am taking a normal unordered map in the map, then I will convert it, how will I keep its values inside the vector, I am considering it as vector v, it is okay with lets, after that when I will sort it according to the given condition, after that I want the top values, this is the question given, I want the top values ​​only, I am want the top values ​​only, I am want the top values ​​only, I am fine, so I think the question must be clear, so let me see how I will do it, so what will be the first step, count the frequency of each word. So what we are using for that is unordered map of type string commit okay second part what will be sort it according to the given condition so what is the given condition that sort according to the frequency from highest to lowest is a given condition and its After what is given, if the frequency of both is same then in which order to sort, if it is ok in graphical order then what will we do, we will create a vector named temp, ok what will be the type, pair of string, kamba ent, then all its values ​​will be string, kamba ent, then all its values ​​will be string, kamba ent, then all its values ​​will be stored inside it. Then we will apply custom sort operator in it, we will apply custom sort function by which we will sort it according to this condition, sort each vector, okay and what will be the last step, when our vector will be in sorted order, then we will start We will take the top values ​​because top values ​​because top values ​​because how we are storing the values in descending order means what we will do in custom short, I will show you how we are doing it in custom short, basically we will store in descending order according to frequency. Ok, inside the stamp, this part is cleared, after that we want the top value, that means we will go from starting till k, we will store the values ​​we are getting inside the vector named result store the values ​​we are getting inside the vector named result store the values ​​we are getting inside the vector named result and return the result in the last. Okay, so store only the top values ​​in the result and top values ​​in the result and top values ​​in the result and return. Okay, so what will we do: declare the return. Okay, so what will we do: declare the return. Okay, so what will we do: declare the result vector to store the values. I think the question must be clear. Let me explain it in the code. How did we do the code? So basically our first step. What was it, what will we do, we will count the frequency for each word, okay, then what will we do, we will sort, in the second step, so what is the first step, we have declared a vector, sorry, we have declared a map, of type string commit, okay, and what are we doing in this? Basically in the step, our case is one, we are storing fancy for every word, okay, what was the second step, basically, what was the second step, we have to sort according to custom sort, okay, so what we will do in the second step, we will declare the vector as temp. What will we do with the name, what will we do with all the values ​​in it, we will do with the name, what will we do with all the values ​​in it, we will do with the name, what will we do with all the values ​​in it, we will insert it, okay, then after inserting, we will sort it, whom, we will sort this vector, how will we sort this is the Comparator which we have used CMP which we have used custom function. What has happened is that we will sort according to this, so if I look at the CMP, what have I done, static bool compare, what I am doing here is basically pair of string combined and one pair of string combined, okay, after passing both of them, I check here. What is the second basically storing? What is the second storing? It is storing the frequency because first what is string means that word and its frequency. I am saying that if the frequency of both is same then what to do. Apply compare function to the string. To check that first adot first compare bid first then if the value of l is if it is negative i what does it mean keep in mind if compare function what does it return negative value when first lx is graphically smaller compare to which The second element should be the second string. Okay, so here we basically have to check which one comes first, basically if a dr first, our negative means if the value of well I got negative, what does it mean a dr first. Lego will come first, graphically it is fine, so I have to return the same. When was this case when the frequency of both is same. If the frequency of both is not same, then basically what to do in it, in which order we have to arrange them among themselves, whose frequency is different. The number of frequencies should be more. It is okay. If the frequency is more, it means that we will have to arrange in the number. So what is the meaning of arranging the number of numbers. Second should be greater. Second is okay because what is the second basically noting? The frequency is so important that this part is clear. It must have been done that how do we put the less shut, so once we put the less shut, what will we do after that, we will declare the result name, our answer because we have to return the answer, we have to return the vector thing, okay, so I declared a result name. The vector of is okay, push inside it the values ​​of the top are okay push inside it the values ​​of the top are okay push inside it the values ​​of the top are okay so result dot push back temp first temp aa dot first s basically what is storing in the first is string right we have to return the word and what will we do in the last Will return the result, okay, so this code, you can take a screenshot of it once, so basically this is what we have here, I will show you by running it, okay, so yes now, okay, let's run it, okay, let's submit it. If you still have any doubt please ask in the comment section, it passed ok so this video please lock all my channels thank you.
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
901
everyone welcome back and let's write some more neat code today so today let's solve the problem online stock span we're given a list of daily stock prices and we want to return the span of each of these stock prices now the span of a stock price is defined as being the maximum number of consecutive days starting from today and going backwards so the maximum consecutive days where the price the stock price was less than or equal to the price of today's uh stock price so let's take a look at an example so suppose that this is the list of stock prices that were given and they're given sequentially right so this is day one this is day two this is day three etc so what would be the span of the first day well obviously there's no uh stock prices that came before it technically so this is going to have a default value of one because the day itself is included okay but then we get to the next day so what's going to be the stock span of day two well remember what's the definition of the span the maximum number of consecutive days starting from today right starting from here where the stock price is less than or equal to 80 in this case right so obviously there's one day the day this day itself so it's at least going to be one now what about the day before is the stock price less than or equal to 80 on the day before well it's a hundred so it's not less than or equal so in this case uh again we're gonna have a value of one same uh goes for this value too uh because the day before is more expensive so we don't have any consecutive days so you can see that when we build our output down here the first three values are gonna be one but when we get to day four seventy uh we look at the day before seventy sixty so technically the price was less than seventy so that's at least two consecutive days what about the day before 60. 80. do we is it possible that we have three consecutive days nope because aed is more expensive than 70 so in this case we have two and at this point you probably get the idea for 60 it'll be one again because the day before is more expensive even though we have a day over here which is equal to 60 we need consecutive days right so we have to look at the day before and it's more expensive but 75 is a little bit more interesting because the day before is 60 is cheaper the day before that is 70 which is also cheaper than 75 the day before that is 60 which is also cheaper than 75 the day before that is 80 which is not cheaper than 75 so in this case we had four days so the spot uh span of 75 is going to be four and 85 is also more interesting because this day and this day are all cheaper than or equal to 85 but a 100 is where it's going to stop so uh we had six days so that's how we build this output now the way i kind of just walked through the algorithm what was the time complexity of the way we just did it because we did it in a brute force way right for every value we're just going to start reading backwards from that value and see how many consecutive days we have where the values are less than or equal to the current day right and if we do that for every single value in this array how long is it going to take to look backwards in the worst case it would be o of n where n is the size of the input array and we're going to have to do that for every value there's n values so the time complexity is going to be n times n which is n squared well there's one shortcut that we can kind of take and we can use that shortcut to actually arrive at a linear time solution but i do want to warn you that this linear time solution uses a technique that you probably won't be able to come up with unless you've seen it at least one time before so don't you know feel too bad if you couldn't come up with this by yourself but first let's see the little trick that we can do because it's actually pretty simple so suppose we had this same exact input right and suppose that we computed the span for all of these and we're at the last value right so basically we've computed all of these we have the span right for 75 the span was four but now we're trying to compute the last one suppose we don't know that it's six just yet how could we figure it out well can't we use some of the work that we already did to help us because take a look 85 right we want to know what's the span of it so of course we're going to look to the left there's a 75 here right first of all 75 is less than or equal to 85 right so therefore we're going to continue looking backwards right that much is obvious but what if it was the opposite case if it was suppose 90 or anything that's greater than 85 at that point we would immediately stop right but since this is less than or equal to 85 we continue starting from 75 we have to look to the left of it to find more consecutive values that could also be less than or equal to 85 but isn't there a little bit of a shortcut that we can take because we already computed the span for 75. now obviously the span of 75 is going to be a little bit different because from here we're going to be looking to the left for values that are less than or equal to 75 but what we really want to do is do that for values that are less than or equal to 85. so it's not optimal but we can still use some of the repeated work because for 75 we know that the span of it is 4 and naturally all values that are less than or equal to 75 are also going to be less than or equal to 85 so what we're saying here is we from 75 we don't have to look individually at this value or this value uh to check that it's less than or equal to 85 because we already know from this four value over here that you know all four of these are less than or equal to 75 so of course they're less than or equal to 85. so what we're saying is from here we can make a jump now all the way here and now we're going to ask ourselves is 80 less than or equal to 85 because while this 75 was a shortcut it's not the whole story because these values were only compared to check that they were less than or equal to 75 there could be additional values that are less than or equal to 85 so that's what we have to do extra work on we can't reuse the repeated work that we did before so here again we're gonna have to look at 85 is it we're gonna have to look at 80 is it less than or equal to 85 yes it is so that's another value now in this case we would again see is there any repeated work uh basically we're gonna check what's the span of 80. it's one so that you know we can't just take another big jump like we did before so we again have to look at the particular value 100 is not less than or equal to 85. okay so that was enough for us to complete uh the span of 85 which now we have determined to be six but you know from the solution while it's a little bit more optimal because we're not uh required to look at each individual element sometimes we can just make a big jump you know that's nice but still this solution in the worst case is going to be n squared isn't it well actually no not if you implement it optimally let me show you what i mean suppose now uh our array actually had one more value in it suppose that value was 90 and now we want to know what's the span of 90. well now we would look at the previous value 85 is less than 90. so what's the span of 85 it's six so we can make a big jump of six these values are included in are less than or equal to 90 so then all we have to do is look at 100 right so that's good but you're probably thinking well we're not always going to be able to make that big jump right what if we had a smaller value like 75 right well in this case you know we're gonna have to look at 85 and maybe sometimes we're gonna have to look at these values in between but my argument is we're never going to ever have to look at any of these values ever again because we know that 85 is greater than or equal to all of these values so what's either going to happen is we're going to have a value the next value over here is going to be less than 85 where we would look at this value and say it's greater than 75 so we're never going to be able to make past this value to even look at these ever again but if we did find a value that was greater than our 80 uh it was greater than or equal to 85 up next right if it was 85 or 90 or something like that then we would say okay this value automatically gives us all of these it's either or there's only two cases here either we have a value that lets us skip all of these or we have a value that doesn't let us skip any of these because we have to make it past this guy first before we can even look at these and this leads us to a solution that's called a monotonic uh stack solution in this case the stack will be monotonic decreasing order sometimes they're in increasing order but let me show you what i mean and let me show you why it's going to be a big o of n time because each value here is only going to be added to our stack or removed from our stack uh one time each so if each value is added and removed then obviously the time complexity is gonna be two times n which is still linear time let me just walk through that solution and then we're gonna code it up so technically we're gonna have two stacks or you could have a stack of pairs that's what i'm gonna do in python at least but so one portion of the stack is gonna be the price and for each price of course it will have a corresponding span so first we're going to look at the first value 100 right there's no values to the left of it so by default it's going to be added to the stack and its span is going to be 1. next value is going to be 80. now before we add 80 to our stack we want to know the previous value is it less than or equal to 80. in this case it's not so we just take 80 add it back to the stack and then give it a span of 1 by default again do the same thing for 60 because 80 is greater than 60 so the span of 60 again has to be one then we look at 70 though the previous value in this case 60 is less than or equal to 70. so what are we going to do in this case we're going to pop this value from our stack and then increase the span of 70 by 1. now we're going to look at the next value 80. is it also less than or equal to 70 it's not so we can't keep popping from our stack now we're going to take 70 and add it so 70 is added to our stack with a span of 2 in this case this 2 basically represents these two values and we never have to look at this value ever again we can pretend like it never existed because we already recorded the information we wanted this stock has a span of two either the next value is going to be greater than or equal to 70 in which case this part will also be included to the span or it's going to be less than 70 suppose in this case we actually do have a 60 value so what that means is if we can't make it over this value it doesn't matter what this value is anyway it doesn't matter it was deleted because we can't even make it over this guy anyway so 60 is added to the stack and we are gonna give it a span of one because it's less than 70. i'm running out of room so let me add a couple more spots sorry about that i don't like the contrast between the white and the black but that's okay so the next value is 75. so we're gonna look at the previous value it's less than uh 75 so we can pop this and increase the span of 75 by one so for now i'm going to put a 2 here now again over here this value is also less than 75 so we pop this value as well but instead of increasing the span over here by 1 we're going to increase it by 2 because there's a 2 over here this 2 represents both of these values so we pop this and actually our span over here is now going to be 4 but we're going to look at this value it's greater than 75 though so we can't pop it so the final uh span over here is going to be 4 and then last value 85 before we add it we're going to compare it to the previous value 75 which is less than 85 so we're going to add 4 to the span of 85 and of course that four represents these four values and then we're gonna look so by doing that we're gonna pop this right add four here so four plus one so far and we're gonna look at the previous value again 80 and we're going to pop that as well so far the span here is going to be six and then we're going to look at the previous value before that as well but it's greater than 85 so we can't keep adding to the span so the final answer here is going to be uh 85 and then the span here is going to be six so as you can see each element was definitely added to the stack at least once and at most popped once and i didn't talk too much about what this problem actually wants us to do basically uh the way this uh solution is to work is we're going to be given a stream of values basically each time we're going to be given a new stock price and then for that stock price we just want to immediately return the span of it but internally we're going to be using a stack to implement that solution efficiently so now let's jump into the code by the way time complexity is bigger of n also the memory complexity is bigger of n because of the stack data structure that we're using okay so now let's write the code and in our constructor we're actually just going to initialize our stack data structure it's going to be a list of pairs in this case but you could have two lists if you're or two stacks if you want to uh do this in java i think if you can't like easily have pairs of values so each pair is going to represent uh the price and the span we're given a price right every time this next function is called we're going to be given a price we want to return the span of that and to do it efficiently we're using a stack so by default the span of any stock is going to be one but we want to see maybe we can make it bigger well we can only do that if our stack is non-empty uh that if our stack is non-empty uh that if our stack is non-empty uh self.stack and if the price at this on self.stack and if the price at this on self.stack and if the price at this on the top of the stack is a less than so to get the top of the stack we're going to do negative 1 in python that just gives us the last value in the stack you could also take the length minus one and of our pair we want not the span of it but we want the price of it so we can get that by taking index zero so if the price of the top of our stack is less than or equal to the current price then what are we going to do we're going to take our current span add to it self dot stack the top of the stack and the span this time so we're going to take index 1 because the second value is the span and we're going to add that to our current span after that we're going to pop from the stack so let's do just that self.stack dot pop and we're going to self.stack dot pop and we're going to self.stack dot pop and we're going to keep doing that until our stack is empty or the price of the top of the stack is no longer less than or equal to the price now after all of that is done we want to of course update
Online Stock Span
advantage-shuffle
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Array,Greedy,Sorting
Medium
null
73
all right doing this problem called set Matrix zeros given an AM cross and integer Matrix if an element is 0 set its entire row and column to zeros you must do it in place that means you have to do it in O of 1 you can't take extra space and if any of the uh if any of the so for example here this is 0 that means the entire row and the entire column has to become zero okay this is another example in this example this was 0 so this row and this column becomes zero and this was 0 so this one is called zero so I can sense the problem that can happen as you have to know the original zeros because otherwise what happens is let's say if with this 0 you convert this into zeros and zeros now you don't know whether this was 0 to begin with OR this was made 0 by this right that is something that you're not aware of and because if you're not aware of that then when you look at this zero you might say hey I want to convert this row and this one to zero and as a result of that your entire Matrix will just become 0. so one of the things is definitely you have to keep track of original zeros right original zeros but now you can't take extra space you have to do it in place and one of the ways could be hey can I go through the metrics can I find out um what positions are original zeros and maybe save them in a set and then go through that set right just that set and if that's set say 0 then I will update uh that rule and that column to all zero and then I'll do it for oh each and every zero that is one way in that way I need an extra space equal to the number of zeros now that's one way is there a question about water follow-up a straightforward solution follow-up a straightforward solution follow-up a straightforward solution using o of n o of M and space is probably a bad idea yeah that's anyways a single a simple Improvement uses a o of M plus n space position all the best version could you devise a constant space solution so it's asking can we do it in a constant space so the approach that we talked about would actually need the number of zeros uh so now let's see if we can do it in place without taking any extra space at all um I mean other than few variables Maybe so let's say we go through this but we I think what we use is we already have a lot of space in the sense that the original Matrix let's modify that original metrics to keep hints uh maybe so what I mean by that is let's say I find a so let's use the first row and the First Column as hinting uh guys so let's just let's go to uh whiteboard and I'm trying to fix my mouse but okay uh so essentially let's take an example of the first Matrix so the first Matrix was one and this was Zero so what we do is we go through each and every element and in each after going to each and every element if I find certain element as zero then what I do is I change the first the Row the first to the correct the first element of that row and the first element of that column as 0 and at this point when I'm at any Matrix and when I'm at a particular cell I already have visited the first row and First Column of that cell right so essentially then what I do is I change this one to zero and then I come down and after that my job is I go to the first row if there is zero I convert that entire column to 0. then I go to the first column if there is any 0 then I convert that entire rho to zero and this is how I convert it now is there any edge condition any base condition which you might be missing let's look at the other example as well so the other example the input is 0 1 2 0 3 4 5 2 and 1 3 1 5. foreign I feel like this might be a corner case where your 0 is a zero okay but so essentially what this should mean is with my algorithm I'll say hey this is 0 that means make the first row uh make the essentially nothing so the first element of the first one for kilometers so it is already zero you keep it a zero and then when I reach this guy that so what this means is that hey make the first element of this row which is this make it 0 and the First Column of this row which is this make it zero which is already which this image it already is why this is done so now what you have to do is go through the First Column which is this so go through the First Column which is this and wherever you find uh whichever side is you know corresponding row make it 0 so I'll make this entire thing as 0 and this is where the problem will be because now when I go to the first row and if this is 0 that means here I convert this to 0 which is fine and but these two zeros are reversed because of this not because of this like these two should not be made 0 this should be made 0 but these shouldn't be right because these have to be made zeros because of this zero and not because of I found any 0 in the corresponding cell yeah how do you distinguish it hat so maybe do not handle the first row and the first column okay let's go back let's do this problem again so the input was zero one two zero three four five two and one three one five okay and when I look at this 0 and I look at this zero essentially it means that uh like the updating bit when I was saying update the first two and the first cell of the row and the first cell of the column is you know which they already are which is fine now my thing was I'll go through each and every I was the first column first I go to the first column and in that First Column but I'll ignore the first row there okay so nothing to change okay no sorry yeah I went to the First Column and nothing to change correct then I go to the first row so first row this is 0 that means this entire column has to zero so I make this and this as 0. and similarly I go to the this guy and this is that means I make this and this is 0. okay Okay so and this two also have to image 0 which is what I did not consider so I keep an extra flag for first row zero right I just keep an extra flag for that and the reason for this is because if I when I was going through the columns and I saw this as 0 and made these as zero and when I go to the first row again I wouldn't know why these are zero right and that I don't have to convert these to zero which is why I'll never go through the I'll never update the first to row 0 while I'd go to the First Column I'll do it only at the end okay so that's my sort of approach I don't know if it's Clarity but let's come to the code and see if we can make it clear there so coming back to code so what I'm doing is first I am just going through the entire Matrix so I equals to zero I feel they might be still some Corners which are not fully considering but okay let's see so if I could like should I even go through the first row and the first column in my initial analysis should I even go to the first one the first column Maybe not maybe go to the first one the first column and figure out wherever the first row should be 0 the First Column should be zero but okay let's find out that case which doesn't work and we'll fix accordingly so first time the basic logic I'm doing is I'm going through each and every so basically if any item in the first row or the first two column would be zero let's do it okay so I equals zero I less than Matrix document I have plus and J equals to zero J less than matric start length J equals plus yeah I think it's another idea I want to go back once again to the board I think the general case that I want to talk about is uh so while I'm using the first one the first column is the hinters the problem there might be something like let's say my array is one two three four and yeah even the problem that I already handled which is this guy so how do you handle this so you go back so this was one zero one no not this how about uh that's where essentially this guy one and this zero so you see it whenever you encounter a zero you make the corresponding row and the corresponding uh the first item of the row which is this as 0 and the first item of the column which is a zero one good I have no problem with that and then when you're going through this you make the entire this has zero and you make the end with based on this you make the entire and it works because this is fine but if there is a zero in the first so the first corner you might have a problem and for example so look to look at that it's let's say so one two three four three five six seven eight and let's say this is zero nine ten eleven and okay altering for something like this essentially means that this row and this column should be zero right but uh when we come to this guy what we would notice is that uh because of this you know our logic is hey make the first kind of the ruin the first guy or the column as zero so I end up making this a zero and once I make this a zero now I usually come to the second part of my analysis here then I say hey go through each and every go to the first one the first concept but I'm going to the first row I see this is 0 I'll make everything a zero right so basically don't touch your first one the first column as simple as that don't touch your first one in the First Column for the first one keeps separate variables and only update the remaining rows and if the first one the first column is used then make Time Zero that will be clear so for example in this case yeah I see this based on this I convert this which is all good and now if because this was in the First Column I will have made this flag called uh First Column zero as true right now when I'm here I will go through the I will not go through this element I will not even look at this element essentially so now I'm going through this and based on this I'll make this a zero and My First Column 0 which is why I'll make this a zero understood honestly I think so okay so let's now uh solve again so I'm making maintaining two flags one is called Boolean first row 0 and I will call this false and then Boolean first column zero and I'll make it also false sorry about that now I go to each and every element right I equals 0 this is this now and anywhere I encounter uh zero so if Matrix of I J equals to zero then what I have to do is first I'll do is the first row so Matrix of I zero equals to 0 and the Matrix of sorry 0 is a U also equals to zero and if I is equal to 0 then you can say the first row 0 is true and if J equals to 0 then you can say First Column 0 equals to 2 right yeah you do you go through all of this things and now you do a second pass first you look at the first anything just look at the first to do so J equals to 0 is less than you always start from one year J equals to 1 J is less than no so Matrix or zero dot length um Matrix of zero dot Grant G plus and at any point if Matrix of 0 I sorry 0z if this is 0 then make that entire column as 0 so for entire equals to 1 is less than Matrix Dot Matrix of i j is zero and similarly do the First Column so I equals to 1 minus 10 matrix Dot if your Matrix of i 0 equals to zero then make the entire row as zero Matrix of I J equals to 0 and at the end just check if first come on first row is zero then start field uh Matrix of zero and if First Column is zero then foreign the First Column zero now uh foreign and it's all in place okay let's run accepted submit and it works all right
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
1,334
foreign welcome back to the channel so today in this video lecture we're going to be solving this problem find the city with the smallest number of Neighbors at a threshold distance which is a yet another problem which can be solved using test algorithm so basically in this problem we are given and cities numbered from 0 to n minus 1 for instance we have if we have four cities they will be numbered from 0 to 3. also we are given an edges array where each element in this edges array is a tuple first two integers represents a node which are connected by an edge while the third integer in the Tuple is the weight of that edge and it's a bi-directional weighted Edge and it's a bi-directional weighted Edge and it's a bi-directional weighted Edge also we are given an integer distance threshold we'll see how what is the utility of this integer so we have to return a city the city out of all those cities numbered from 0 to n minus 1 which has smallest number of cities which are reachable through some path whose distance is at most equal to that integer distance threshold fine so we want to so we have a bunch of cities from numbered from 0 to n minus 1 connected by a bi-directional weighted connected by a bi-directional weighted connected by a bi-directional weighted edges we got to find a city with the smallest number of nearby cities that are at a distance of at most equal to distance threshold if there are multiple such cities we can we will return the city with the greater number for instance we have if we have two cities City number two and City number three then we'll return like the city number two and City number three with the same number of nearby cities with the distance of at most equals to threshold distance then we'll return City number three because it is greater in number now what is the distance of a path connecting two cities I and J it is equal to the sum of edge weights along that path from I to J okay so let's better understand the problem statement using an example so here we have our example we have the city with the smallest number of we have this graph which has four integers so n is four all of the cities are numbered from 0 to 3 then like we can see zero one two and three also the threshold distance for this test case is 4. so threshold distance for this test case is 4. okay now let's see let's start from City number zero and check out the nearby cities which are at a distance of at most equals to 4. now first it is number zero the nearby cities would be City number one because it is at a distance of three units so one also City number two because it is at a distance of three plus one that is four also it does not exceed this 4 so it would it will also be there in the list number three will not be included in the nearby cities because its distance is exceeding the threshold distance its distance is three plus one the minimum distance from 0 to City number three is five which exceeds this threshold distance so these are the only cities which we can include for City number zero which are at a distance equal to the threshold like equal to or less than the threshold distance let's see the same for City number one will have City number zero which is at a distance of three units here this Edge City number two which is at a distance of one unit and City number three as well because it is at a distance of four units or two units because we go from one to two then from two to three this is the shortest distance from City number one to City number three let's check for City number two we will have City number one at a distance of one unit the like shortest distance from two to one is one unit the shortest distance from two to three is also one unit so it is also included because one does not exceed four the shortest distance from two to zero will be four one plus three that is four so it will also be included seat number zero is also there let's go for City number three first at number three the nearby cities which does not exceed this threshold distance would be City number two which is at a minimum distance of one unit City number one which is at a minimum distance of two units That's All City 0 is not included because the minimum distance from 3 to 0 will be 5 from Theta 2 from 2 to 1 then from 1 to 0. so these are the corresponding cities for each city of the graph now what will be my answer what is the demand of the problem says give me the city with the smallest number of neighbors or nearby cities which does not exceed this integer in distance so first zero we have two cities for three we have two cities okay now which one will be the answer zero or three they have same number of nearby cities which does not exceed this threshold distance we'll take that integer which is greater we'll take three because that's given in the problem statement so three will be the answer for this test case okay that's what we have to do now what is the approach to solve this problem if we have for if you have followed the series from the very first video then you would come to the conclusion that all we have to do is to just find the shortest distance from every city to all other cities so from City number zero find the shortest distance to all other cities now pick those cities out of those cities which are at most at a distance of threshold distance so for City number zero calculate the shortest distances so let's call let's calculate the distance array so we'll use diastra algorithm we can use dashed algorithm to do so dashed algorithm calculates the distance array for each node of the graph which represents the shortest path shortest distance from that node to all other nodes so for City number zero the distance array would be like so for set number 0 will have 0 for itself for City number one will have three units first city number two will have two four units three plus one four this is the shortest path first city number three will have three plus one that is 5. this will be the distance array calculated for City number 0 using dashed algorithm now we can see that out of all these cities I will pick City number one and City number two why because these cities are at a distance which does not exceed this four so first city number zero pick City number one and City number two so pick City number one and set number two so it's not four it's two fine so I have this type of list prepared here then calculate the same distance array for City number one so for City number one will have zero for so from City number one the shortest distance to City number zero would be three units the shortest distance to City number two would be one unit the shortest distance to City number three would be two units so this is the distance array for City number one considering it as the source City now first city number one these will be the cities zero now I will consider City number zero 2 and 3 as the valid cities because the distance to these cities does not exceed this 4 so like here then calculate the same distance array for City number two so put a 0 for City number two because it's the source City now from City number two calculate the distance the shortest distance to all other cities using test algorithm so find the shortest distance to node number one find shortest distance to node number three find shortest distance to node number 0 it would be 1 plus 3 that is 4. now from this distance array pick those cities which are at a distance not exceeding this four that would be City number 0 1 and 3. and that's what we have here 0 1 and 3 for City number two now calculate the distance array finally for City number three as well so calculate this distance array for City number three so for City number three the distance would be zero the distance to all other cities would be to City number two it would be one to City number one it would be one plus one that is two first city number zero it would be one plus three that is five so what will be the valid cities it would be City number one and City number two fine because they are at a distance which is not exceeding this four so I will put City number one and two for City number three so this will be my configuration now out of all the so that's how so after calculating these distance arrays simply pick out that city which has minimum number of neighboring cities not exceeding this four and if there are multiple cities return the city with the greater number like here in this case we had City number zero and City number three with the minimum neighboring cities not exceeding this distance four then I return City number three because this is greater in number so that's all we have to do for every pick out pick every city of this graph and consider that city as the source City calculate the distance array the shortest distance array using diastra algorithm which we have learned in the previous videos then a iterate over that distance array and pick out those cities which are at a distance of at most this threshold distance fine if the number of such cities now out of all these nodes pick out the node with the least number of such cities fine and that would be my answer so that's all we have to do so before moving on to my pseudocode implementation just try to implement the solution yourself this is a medium problem so it would not be very hard to implement the solution if you have pay if you have paid attention till now let's jump to my implementation part so this is a pseudo code for the given problem let's write so we have this function find the city which takes in the number of nodes the graph corresponding graph and the threshold integer initialize an integer city with a very large number so it's not zero initialize it with a very large number because we want to find minimum neighboring cities and this integer City initialized to -1 and this integer City initialized to -1 and this integer City initialized to -1 this will store the final Target city which we require now iterate over all the cities starting from City number zero till City number n minus one and for each City considering it as the source City run the standard diaster algorithm so we know what we do in per diester algorithm we have a priority queue we push the source node into the priority queue along with its distance we declare a distance array of the same size equal to the number of nodes in the graph we initialize the distance with a very large number initialize the source vertex with 0 because we are starting from that vertex run the while loop till that priority queue is not empty pull out the top pair like the pairs will be sorted according to the distances in increasing order pull out the pair with the least distance from The Source node and from that Source node just iterate over its neighbors and try to perform the relaxations so this is a neighbor node this is The Edge weight from node to enable Edge now check if there is the scope for relaxation if there is if we can move to the neighboring node with the lesser distance then update the distance for the neighborhood node and push that new pair into the priority queue so continue this till the priority queue is not empty and finally we'll have my distance array prepared at the end of this while loop so from here just initialize an integer count which will be used to count the valid cities it rate over the distances array calculated from the by running the test algorithm now out of all those distances count those cities which are at a distance less than equals to the threshold distance so we have the count of the neighboring cities now if the number of neighboring cities is less than the count which we already have then simply this is a better answer and in that case initial initialize the city variable with the current city and update my count variable fine and finally at this point we'll have our city in the city variable which is the greatest number city with the least number of neighboring cities which are at a distance of at Max threshold and we return that City at the end of this function fine that's all so let's jump to the code implementation part so let's code it here so we have this class solution we have this find the city function which takes in the number of nodes the edges and the distance threshold so first of all just prepare the adjacency list from these edges so adjacency list of pairs of and nodes because the nodes are numbered from 0 to n minus 1 so let's call it Edge iterate over the edges array so we have three things in the edges array we have to pulse so create an edge from the very first node to the second node push back Edge one h two also create a now create we have a bi-directional edges so create a bi-directional edges so create a bi-directional edges so create a Edge in the reverse direction as well H 0 weight h0 h 2 so we have bi-directional edges now so we have bi-directional edges now so we have bi-directional edges now declare two variables count two very count and initialize it with a very large number city with initialize it with minus one iterate over every city of the given graph for every city declare a distance array also declare a priority queue so it's a Min hey basically push the source node into this main with its distance initialize the distance for The Source node to be zero iterate over the priority queue till it is not empty okay pull out the top pair from this priority queue and check if the distance that we already have for this node so we extract two variables node that would be P dot second and its cost that would be P DOT first so if the distance for the node is already better than this cost then we continue to the next pair otherwise it trade over the neighbor nodes for the current node and check if there is a scope for relaxation so distance 2 is better than distance to the node plus the weight that we have if it is the case then initialize the distance to this node to initialize the distance to the new one okay so finally we will have our distance array prepared at the end and we're gonna return the integer we're going to return the now here at the end so at this at the end of this while loop we'll have our distance array prepared so we initialize the count variable to zero then iterate over the dis iterate over the neighboring cities so if less than equals to so count all the cities which are at a distance of Threshold at most threshold distance which we are given here so distance threshold and count them check if we have a better answer if the count is less than equals to the count then update the count and the city as well City to the current city finally we will have our city stored in the city variable which will return at the end of this function fine so in this fashion we'll run the test algorithm and let's try to run this code okay so let's submit it okay so it's submitted let's just okay let's discuss the time and space complexity for this solution now we know that we are running desktop algorithm for n times because we have n cities so the time complexity would be n into the time complexity for dash algorithm that would be the type complexity fine so what is the time complexity for diaster algorithm the time complexity for dashed algorithm is e log n where n represent the number of nodes and E represents the number of edges multiplied by n that would be the time complexity for the given solution that we have explained so that's all for this video if you like the video then hit the like button and make sure to subscribe to the channel and continue in the desktop algorithm series we'll be solving more problems of the same algorithm even the harder problems as well so stay tuned with me I hope to see you all in my next video
Find the City With the Smallest Number of Neighbors at a Threshold Distance
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`. Return the city with the smallest number of cities that are reachable through some path and whose distance is **at most** `distanceThreshold`, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities _**i**_ and _**j**_ is equal to the sum of the edges' weights along that path. **Example 1:** **Input:** n = 4, edges = \[\[0,1,3\],\[1,2,1\],\[1,3,4\],\[2,3,1\]\], distanceThreshold = 4 **Output:** 3 **Explanation:** The figure above describes the graph. The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> \[City 1, City 2\] City 1 -> \[City 0, City 2, City 3\] City 2 -> \[City 0, City 1, City 3\] City 3 -> \[City 1, City 2\] Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. **Example 2:** **Input:** n = 5, edges = \[\[0,1,2\],\[0,4,8\],\[1,2,3\],\[1,4,2\],\[2,3,1\],\[3,4,1\]\], distanceThreshold = 2 **Output:** 0 **Explanation:** The figure above describes the graph. The neighboring cities at a distanceThreshold = 2 for each city are: City 0 -> \[City 1\] City 1 -> \[City 0, City 4\] City 2 -> \[City 3, City 4\] City 3 -> \[City 2, City 4\] City 4 -> \[City 1, City 2, City 3\] The city 0 has 1 neighboring city at a distanceThreshold = 2. **Constraints:** * `2 <= n <= 100` * `1 <= edges.length <= n * (n - 1) / 2` * `edges[i].length == 3` * `0 <= fromi < toi < n` * `1 <= weighti, distanceThreshold <= 10^4` * All pairs `(fromi, toi)` are distinct.
null
null
Medium
null
895
this is larry this is day 28 of the february leco daily challenge uh hit the like button hit the subscribe button join me on discord or twitch or whatever you like and let's go over today's prom uh maximum frequency stack uh and usually i solve these live so if it's a little bit slow fast forward or skip ahead whatever you like but okay let's take a look uh at today's problem maximum frequency stack implement frequency stack okay a class which simulates a stack operation push pop um okay what does this mean okay you have a push and you have a pop removes the most frequent element in the stack if there's a tie for that most it goes to the top okay so i think this i remember sub or working on this one i mean i definitely solved it but i don't remember the details so that's my little caveat um so like it's but i'm trying to remember what i did so uh so maybe i'll just try to figure it out and probably just should just figure out from scratch a little bit um okay so the push we just keep pushing and then element closest to the top is removed and then we turn and then it becomes okay let's see let me i have some questions about this bomb that's what i'm trying to take uh so you do this okay we push all these things uh pop you pop the five oh you popped which five did you pop huh oh no this is the initial way that's why um you pop the five and then now you have a you pop to seven and then you pop this five again and then you okay i think this is a little bit of a weird problem because i don't because hmm so i definitely have a n log n solution i'm trying to think whether i need a linear one or like over just that i can figure out that there is a linear solution in general so the n log n solution uh yeah the analog and the solution is just we push everything on this i'm going to try to solve it um as fast as i can but uh in the n log n way and then we could maybe go to through the discussion or something to see if there's a linear time one um and then i so i definitely remember solving this one as well so we could see how past larry solved it we'll do all those things uh so that and see how much i learned right because i don't remember it enough to know so basically the thing that i'm going to do is and you can actually keep this um so you can actually keep this in a uh so the way to solve this in analog n is by keeping things in a tree-like structure tree-like structure tree-like structure that'll allow you to keep things sorted um and then removing the biggest element from that right and uh and in theory there's a way to do this with a heap um but it's a tricky way to do it with a heaps i'm not gonna do it for heap um because it's similar to there's a way to do it with a heap such that it is similar to the distress algorithm where you have a heap and then you um maybe we could do it that way but i'm gonna do it another way uh like i think you could do it for heap but and if you're trying to solve it with using a heap um my hint to you with respect to that is if you solve it the same way that you do daisu's algorithm uh where you have where there's a perfect heap where you're able to remove stuff inside the heap um and then there's the amortized same or the same complexity but slightly slower heap where you do an amortization step where you just remove stuff more than once um but so it's technically slower but it's still endless again um so the but the key for solving this problem is just keeping a data structure so that you have three items on a key um you have what are the three items right you have the value itself you have to frequency and then you have to index which is the top you know the when or maybe the index but actually maybe time right which is the times the um when was it last inserted um is that good enough now um yeah because once you um yeah okay hmm actually don't want to do it that way i was going to use sorted list but now i think about it maybe it's not the way that i want to do it so i think what i'm going to do is actually i'm going to do it another way okay i know that i've been jumping back and forth and i apologize for that but what i'm going to do is um so this is a data structure problem so i think it's kind of hard to for me to explain the thought process a little bit because my thought process and this is just like because there's no the problem-solving problem-solving problem-solving uh part of a data structure problem is kind of figuring out like almost like lego pieces you have all these different data structure and trying to figure out how to you know interact with like how to get into action in a way such that the complexity is fast enough and for this i am going to actually end up using a heap and um yeah i'm going to use a heap and uh or my dictionary right and what am i going to do i'm going to explain this why code because it is a data structure problem so what i'm going to do is i'm going to have a dictionary that go that maps um basically we wanna what i wanna do is keep a stack for each number um that keeps track of when we like the timing of uh when each number gets pushed to that mini stack so basically uh let's just say stack by number is equal to collections dot uh default dict of uh let's just say a list because we use the list to do stack but um and then we have a self dot time as we said so we start that at zero and then we let's have a heap to keep track of all the things that we have on the heap um and okay so now that we have that we can you know figure out what it means to be a push so to push well first of all let's add the time by one um and then now our stack by number oops it uh we take this number and then we append the time by it and you can actually do a increment before after it doesn't matter because as long as you're consistent about it doesn't matter and then here we now hmm i was thinking of something but then i forgot that if you do remove it wait no i think i'm just confusing myself i think this is right so then by pushing um oh no you have to remove the thing that's inside already right now before you push that's why um hmm man i think i got a little confused here okay fine i am going to use a sorted list for this because it makes it easier for me to um to kind of reason about it so let's say we have a sorted list um and there's an api that basically keeps a list that is sorted it is what it sounded like um and then now to insert it and the way that we can use it is kind of just to get the max value of something and the key that we're going to sort by in this case um it's going to be two things right one is the frequency as we you know that makes sense and then we're going to sort by um the last time inserted which we will keep track of and then we also just keep track of the number right so x um so then now we want to insert it into the list but before we push it we want to um we want to remove what's inside right so here um so we have to keep this in variant of if uh if this thing if the length of this is equal to zero what does that mean right that means that we can just um that means that we don't have to remove it so that means that if this is greater than zero we have to remove the existing entry right um hmm and the existing entry um it's going to be self that sorted list that i think it's called that remove um the existing entry is just um the frequency which we which is the uh the length of the self stack by number of whoops of x more specifically um so the this is the frequency right we you could also use it another lookup table but the length of this is the frequency and then the time is the previous time so this is going to be the top of the stack because we keep track of this thing so this is top of the stack and then the value which is x so we remove this so that we can update it by appending this to the stack and then now we can um add this new thing which is actually pretty much the same now we can add this thing which is just that we updated it so basically what we want to do and why this looks funky is that in this sorted list we want to update this uh value with its new value because now we push the new thing right so the same thing goes for pop so the problem is now we looked at the sorted list um the biggest element which is the item that has the most frequency with the tiebreaker being time and then x is the value right so then we um or the return value is equal to uh the last item the x value which is the third key so this is what we eventually return and then now we have to update the sorted list so then the previous value is going to be um let's see uh yeah so the previous value is good um yeah the same thing similar to what we had before which is we have the length of the self.stack by number of our of the self.stack by number of our of the self.stack by number of our value and then self dot stack by number after um well actually i don't know why i did it this way you could just remove the last number right or um yeah the last item so that's just this right um okay that's actually let's actually write it out last item is you go to the biggest item right yeah and the right value is you go to the last item of this and then now we could remove the last item and then now we have to put in the updated item back into the sorted list i know that i this is really weird code but um so which is um oh the news pop so we have to do one more thing which is that we have to pop the stack by item by number rather uh of let's just call this x so i could copy and paste um we now want to pop remove the last item right and then now we do the same thing with here which is now we update we do the update and then that should be it and again um so these operations depending on your language can be done in a tree like structures um so you just have to be able to and there's a lot of what i call bookkeeping and by bookkeeping i mean just keeping track of where everything is and then removing it updating it and then put it back in a sorted way um oh is that really up from sorted containers imports sorted this let's give it a go let's give it a spin and oh no oh typo let's now give it a go liver give it a spin uh and hopefully that's one time error oh now line 24. oh i have to check one thing which is that obviously this we should only do this if there's still an um you know if there's still a number left otherwise this doesn't make sense um okay so this looks good let's give it a submit sweet so let's go over the complexity real quick um let's see so let's say you know let's say we have o of p plus q oh sorry let's say we let's define something let's say we have p is equal to pushes q is equal to pops right and n is equal to p plus q because that's the num the max number of numbers right then in this case uh so each push you know uh sorted list removal or tree removal if you want to think of it that way will be log n this is just a stack operation this is one so this is also log n so in total this is going to be o of log n uh pop is similar right we look at the last item which is log n operation or whatever depending how you want to define it but either way this is also going to be log n and well if this is the last item i guess it doesn't have to be log n but in any way uh for a tree operation this is gonna be log n because you have to add it back in and maybe anywhere right so this is oh i would i don't know why i will not and even though i set login a few times right so that means that for each push operation um it's gonna be p log n plus q log n or obviously oops over p plus q log n uh with the parenthesis here um so yeah um that's basically the time complexity and then the space complexity of course is just we have a sorted list which is linear uh this is awkward looking but it's linear because each item that we've come in will occupy one space on the stack by number so it's going to it's just transformation of the input so it's going to be linear space uh so yeah uh that's all i have for this problem uh so i'm gonna do two things one is i'm curious if there's a i don't know but i'm curious if there's a linear time solution and then two is let's see how past larry did it right um let's check it out loading oh well one solution uh well okay bucket sword doesn't really uh hmm what is this old one alright let's take a look did i misunderstand this problem how is this all one solution oh i see the push and the pop is all one not that the entire thing is all of one we analyzed it in a little different way um hmm i mean this is definitely the way to do it so we have two stacks as well they did it right wait what not sure i understand all right let's see how past larry does it this is not how is this with detailed explanation this is just an explanation what this is such a lie there's no detail explanation at all okay anyway um i feel like i've done this but maybe not if it was in 2018 i thought i'd done this though let's see how past larry did it uh let's check that out uh let's see oh this was a hard oh it's either that or it was in maybe i don't know maybe i don't know maybe i don't know let's see okay no i did do it at some point but oh i did it last time with a heap it seems like so i did the same thing last time but with a heap hmm okay actually this way of doing it with the heap also makes sense but actually this is way better than the way i did it today um i wonder if this i might already have a video on this so i don't know but uh i sometimes you sell things different ways in different days uh this is way better and if i have a video on it i'll send you a link and you should check that out instead whoopsie but uh thanks for swinging by that's all i have for this prom uh i'll see y'all later take care of yourself and take care of others if you can stay safe stay healthy and to good mental health i'll see you later
Maximum Frequency Stack
shortest-path-to-get-all-keys
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the `FreqStack` class: * `FreqStack()` constructs an empty frequency stack. * `void push(int val)` pushes an integer `val` onto the top of the stack. * `int pop()` removes and returns the most frequent element in the stack. * If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned. **Example 1:** **Input** \[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\] \[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\] **Output** \[null, null, null, null, null, null, null, 5, 7, 5, 4\] **Explanation** FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is \[5\] freqStack.push(7); // The stack is \[5,7\] freqStack.push(5); // The stack is \[5,7,5\] freqStack.push(7); // The stack is \[5,7,5,7\] freqStack.push(4); // The stack is \[5,7,5,7,4\] freqStack.push(5); // The stack is \[5,7,5,7,4,5\] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\]. **Constraints:** * `0 <= val <= 109` * At most `2 * 104` calls will be made to `push` and `pop`. * It is guaranteed that there will be at least one element in the stack before calling `pop`.
null
Bit Manipulation,Breadth-First Search
Hard
null
1,721
Hello everyone welcome to my channel with mike so today you have given the code on your on ok so the name of the question is swapping notes in n link list ok so by giving input and output let us understand what is the question is very simple it is given in this That brother, I have given you a linked list, okay, I have given you an increaser, okay, you know what to do, the starting note is from the returning beginning, the second one is there i.e. instead of and the other from the returning beginning, the second one is there i.e. instead of and the other from the returning beginning, the second one is there i.e. instead of and the other note is this one. And this one is fine, we have to swap the value, okay, the value is a little more complex, the question becomes but just to swap the value, which is sorry from the beginning, and on the second note, the value of both is fine, here four A will go, here you will go brother. My answer is okay, so let's see how we will approach it. Okay, I will make it with two approaches. Okay, first of all the question is very simple. Okay, first see what is the proposal. We will first find out this in the link list, brother. Give the value of , so you brother. Give the value of , so you brother. Give the value of , so you can find out which is the second note from the beginning. You can simply traverse it, but what did you do or how much is this English Kalyan? 12345. Okay, the second note from the beginning is this one or this one too. Can you say what is the total length from starting to starting? There are five models, total - 2 + 1, its five models, total - 2 + 1, its five models, total - 2 + 1, its value is 3 + 1 = 4, that is, the value is 3 + 1 = 4, that is, the value is 3 + 1 = 4, that is, the fourth note from the beginning, 1 2 3 4, okay, that means what I am saying is. And seth node or subtract the total length from the beginning and make it two k plus one, then the value that will come from the beginning, that note, the thing is the same, that is, first what will we have to extract from the beginning, then what I will do here. It will happen or else first we will find out the length but its length has been found out link after that what will be extracted from the field Note from D beginning after that this note from D and at the time of extracting I will extract the L mines plus from the beginning what will be extracted from this Note 2 It will be very simple, it is not medium, it is easier than medium, that is, it is easier than easy, etc. I was just giving the right to understand, so come on, you can see how many times we have traversed the linked list, first to find the length. Listed the entire link, tried once for the year separately, then to withdraw note one, traveled once more to withdraw it. OK, after that, L - K + 1 / To withdraw the note, OK, after that, L - K + 1 / To withdraw the note, OK, after that, L - K + 1 / To withdraw the note, driver's multiple times again. Traveling is the post, okay, so after this we will see another approach in which we will solve it in a single rubber head, but first submit it and let's see, the most basic approach should be made first, then first submit it, let's see if it is possible. Pass Jo D Best Cases Okay, so let's code it before our first approach, okay, it is quite a simple approach, first of all, what I said is that field note from start note should not be said, yes okay, node will say okay and second what to remove. If you want to extract the field note from, then you can also write this as the length of the node is from the beginning, so the start is fine, so let's do what I said, first of all, let's find the length which is the head of the link list and find its land, okay. From here, I got the length. Okay, now after that, what I said is that brother's Anders on one is equal to you, here I made noise in a variable, it is okay, let's put noun stress, one note, one will be mine, okay, which is from the head. It will start ok and it will go till the second note is reached, so what I said is ₹300, we have to keep going reached, so what I said is ₹300, we have to keep going reached, so what I said is ₹300, we have to keep going till the Greater Dane one is there, ok so what will I get here, I will get the note band first. After that, what am I doing by copying and pasting, okay, this is from the beginning, either the field road from the start was to be returned, do find the length, then in this also butter approach, you will see that first, you should have seen it from this approach. Are we able to pass all of them or not? Let's see the example here. I think all of them should pass. It's okay. We have traveled multiple times. But we can further improve the link list. We can make it in a single travel cell. If yes, then let's approach it, let's understand it. Okay, then look at the proof, let's understand it. Look, I ca n't tell you the code of direct approach. In the first pass, do like this and move it will be solved. I will not tell you directly, but you will understand. You should also know the thought process, how to build the right thought, it is okay, so look friend, think of it like this, mother takes it, there are two the day after tomorrow, there is one the day after tomorrow, you are okay and you have said that brother, no to the day after tomorrow. So then the day after tomorrow you have to take any mother, you have to stand on the second mode from the beginning i.e. you have given the value of K i.e. you have given the value of K i.e. you have given the value of K and the day after tomorrow you have to deliver one here and the second note from the end. But we have to reach, okay, so how will we reach, that's what we have to find out. Okay, so look, let me tell you a very interesting fact, this will be true every time, from the sense starting, now p1 is on tap, poor guy, and now look, from the science starting, K = 2, now look, from the science starting, K = 2, now look, from the science starting, K = 2, note in the second. But who has to be reached? If p1 has to be reached, then it is okay to reduce it by one. If p1 has to be reached here, then we start with K = 2. Right now, start with K = 2. Right now, start with K = 2. Right now, I have taken a painter named Temp, we have just seen a note. First one, you have removed the value of t, this brother, have you seen one note? Has the value of t become zero? No, it has not become zero, that means we still have not reached where t1 wants to take us. Okay, no problem, then temp. Okay, we have seen one more note. I will know from the beginning that another note has been received. Brother, blindfold me and first of all tell p1 that brother p1, your note has been received, this is the temple. The one who is pointing at me, I signed it to P one but P1 is happy that P1 has got it but now P2 has the upper hand. Okay, so tell me what will we say to P2 that Bhai Pitu, you are from the beginning. Start, now you are active, jo p2, now you are a tap, but you are now active, because p1 has got a house, now p2, you want a house, so p2 has become active here, poor Pitu is standing here, okay and this we They will say that brother Pintu, you walk till the tempo ends, it is okay to go till the temple and the tempo was increased further, okay and what we did was that we told P2 that you brother should start now. So I eased the head of P2, okay now it has been said that brother P2, you walk till you go, then it is okay, the tempo has just come here, okay otherwise P2 can go further, so P2 came here. The time is over on tap, we will rock P2 there and I will say that brother P2, this will be your home for sure and this is the right thing, think about why this happened, you will understand yourself because look, the time was here. Na, we had started here in the beginning, by the time the link list goes and I had started from here, how many notes will the time take now, one, two, three, okay, we must have started here, okay, so what does it mean that both of us What is the total length? What is five? And if we had already done two notes, then by dividing five into two, three, two, there will be a note just after three. And look, the maths that was applied above, the length one is also the same here too. He is doing fine, so Pitu here except the third thirty-three note, so Pitu here except the third thirty-three note, so Pitu here except the third thirty-three note, p2 came here, then how simple would be its story, understand what I said, see this is the specialty in linked list, if you write the story, it will become clear and if you make the diagram. What did I say in the starting that p1 is the tap, p2b is pointing to the tap, okay and at one time I took the name that brother, it has started from the head, okay, now what did I say, we will continue till the beginning, but If that is, if I have made P2 notes, then only then Pintu, don't read further, it will also increase otherwise, what I told you is that it is okay and at the same time we will activate P2 also, P2 will be told, brother, go to the head. Okay, now P2 will be activated, then this one will start reducing, okay, hide it every time, we did not do anything, in the story told, it was written that Pitu was not activated in the beginning, he was going on removing the cake in the tap like When zero happened, it moved forward in p1 and it continues till the time ends. Convert the story back into code. Farable tu pass which will be done in D best tu se G single pass. And see the best part is that which story comes. Will do, the day after tomorrow there is one, this is okay and the day after tomorrow, you are here, this is also null, okay, now what did I say that it will start from the head and will keep going till the time it does, but as soon as K = 0, does, but as soon as K = 0, does, but as soon as K = 0, I will activate p2. I will give it ok I am assigning you to P one ok here we will activate it till now it is clear so simple code and story threat now what to do solve this question any doubt there is resident de commerce video thank you
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
1,260
um hello so today we are going to do um the problem uh from latecode april challenge um april um 11. so the problem says we'll get a grid and of size m by n and then integer k and we need to shift the grid k times and here what they mean by shift operation is that uh grid i j moves to the next column so it moves to grid i j plus 1 and grid i n minus 1 moves to grid i plus 1 0 so the last column the last position of the last column moves to the first cell of the first column because basically the last column you can't move another column and so you'd have to circle back um so it's sort of circular shift um and then the last cell in the matrix goes to the first cell in the matrix right uh sorry here what this means is that the each cell from the last column moves one row down right so in the first column of course uh so yeah this will be clear with an example so here we have this example with this matrix so 2 5 8 moves over so 147 moves over to the next column we have it here 2 5 8 the second column moves to the last column is a little bit trickier where we know that we have to move it to the first column because there is nothing to move it over to um but you can see here each cell moved one row down so three move it to the second to the first uh second row and then six move it to the last row nine which is the last position m minus one and minus one move to the first cell circular again move of the rows um so this is the main id the main problem um the first easy way to solve it is just to do the exact um the exact logic that we have here with the shift operation this one is a pretty straightforward so i'm just going to quickly work through the code and then we can do a more sophisticated solution um okay so let's see the straightforward solution that just simulates what the problem statement does so i have here the three operation the three uh parts of the shift operations um i just numbered them here so first one is that the element at grid i ij moves to this for example and we are just going to do the exact same operations um and so um here we just keep rows and columns in a variable and then the number of thousand number of columns we want to do the shift operation k times right so we loop k times uh and we initialize a new grid um for each shift so this would be each shifted grid we initialize it here with just zero values um and now we go through every uh now we execute the first step which is every uh column except the last one the element in i j moves to i j plus one right so this means that we need to assign to i j plus one the value in i j and so we just go through the rows and for each column except the last one we re assigned to the new grid i own the ij plus one position so that's here um we need to assign grid ij that's exactly what this first operation does uh and so we do that here and this is this works with the j plus one because we don't need to handle the last column and so um we don't need to um like loop around and go to the first column the second part is the element at i on the last column so i n minus one moves to grid i plus one zero so it moves to the first column uh and it moves one row down right and so we just do exactly that so we go through every um every cell in the last column uh with this and then we one thing here we leave out the last element in the column so that's why we are doing rows minus one here because we will assign it differently with three here um and so there we assign um i plus one zero which is what um which is what we have here i plus 1 0 we want to assign i n minus 1 which in our case here that's just i columns minus 1 okay n is the number of columns uh so we that way we handle 2 now we handle three which is the element in m y minus one and minus one so in the last cell moves to the first cell in the first column and so we just take the new grid for zero um and then we initialize it to the last cell so that's a grid minus one m n minus one which is just the number of rows minus one the number of columns minus one uh and then we assign grid to new grid just so that the next shift operation um we shift the new grid um and then we return to it so pretty straightforward um just simulating the exact number of uh the exact uh problem statement um in terms of the number of the time complexity so we have the slope for that goes k times uh we have here rows and here columns so this is rows by columns and then this one is just rows and so overall it's of k um so overall this is just of k rows columns and if you want you could just name it nm as well um so yeah one thing though is maybe we can get rid of this k term and at least have an m we have to look at each position in the matrix so i don't think we can do better than this but at least this part we can try to reduce uh so let's see how we can do that okay so how can we solve this problem so differently we can do this differently actually so um instead of doing in the previous solution where we did the shift ourselves each time we can just calculate the final position in the new array for each cell so for one we can compute okay um what is the final position of one after case shift what is final position of this one after k shifts so that's the main idea here um now the first observation we can make is that the index the column for each cell so if we do just two shifts right we know that four here will end up here in this column will end up in this column right which is just to zero to one two so we shift once each time we add one to the column each time so the first observation is that we know that we can just take for j which is the column we can just add k right except for the case when the number of k is bigger than the number of columns so let's say for example we want to shift zero let's say k is equal in this case equal maybe to uh three right so we'll shift once here um sorry we'll shift once here there will shift once here then the second time we have to shift around back to zero right and so to do that we can just take j plus k imagine all the number of columns imagine the size or the number of columns let's just call it this um and so this would be just modulo k modulo columns right so that if let's say for the case where j equal to 1 and k equal to three then here we would move from one plus three but for this case where the number of columns is three then we would move to one which makes sense we would first okay we want to shift three times and so for the position one we will first move to um to two and then we'll move back to three and then we'll move back again to the column one right so that's the main idea here um and so we know the new value for j is going to be this um so j2 is going to be this value here now what about the um what about the column what about sorry the row index um for the row um it's simple for the other columns so if i just take um our matrix again here uh for the other columns let's say for other columns except the last one rows remain the same right because we move only j except for the last row where it's a little bit tricky so for the last row what happens is that each so this is nine let me write down the final result for k equal to 2. so if we shift by k we will get this here where we have 9 3 6 1 4 7 and two five eight so what will happen for um basically this here is that three went down uh so three one down to the next row six one down to the next row that's what we have here and the nine because it's the last one it has to go to position zero right so that's what happens it's actually very similar to what happens with that with the columns and so what this would mean is that for the last column all right we know that the value for i two is going to be to equal to because we shift we are going to shift each time so each time for each shift we add one to the row so it's i plus k right because k times we add one now what about the modulus we want to modulate the number of rows right because for nine we'll go back to zero um each time so for the last one we'll go back to zero so we want to shift we want to modulo by the number of rows right um so this is for the last column now how can we translate this to one um to one formula that we can use for all columns right this is where the clever piece of this implementation is so um basically we can for each column add in the formula something so that we can calculate when it reaches columns with the shifts we are doing so we know that if we um okay so how can we expand this to every column right so the main thing is that um we need this we can divide by columns to know how many and so we can do something like uh i plus j plus k divided by columns um i'll explain this in a moment but um so this would be like this so why does this work so what we want is once the column reaches um n shifts right once the column reaches the last column then this would be columns right or if we say columns is n then j plus k divided by n is what we are looking for so once j plus k once this reaches n which means we reach the last column then when we divide by n we'll get one and once it's so we'll get um we'll get one right and if it's two n we'll get two and so what this would mean is basically we'll add one to i when we reach the last column which is exactly what we want and we'll do it as many times as we'll add as many times as there are shifts so if k is equal to two then we know that we will shift the last column two times so this is kind of the main idea here um and so to extend this to more than just one column more than just the last column it will be window i plus j plus k divided by columns and we still want the whole thing to be modular rows so that we don't shift once we reach the last row we shift back up so this is kind of um the main thing so we have now so this would be our e i2 and so with this we have the formula for um for the new i value and then we j value so now we can just use these two um to um basically iterate through the rows and we thread through the columns and we have the new indices and so in the new indices we assign i and j the values in i and j pretty much um so that's the main idea now let's code it up and see if it passes test cases um okay so let's um must implement this um so yeah first we need to initialize uh the two values that we are interested in so the number of rows and the number of columns and those are the length of the grid and the length of the number of columns which is the length of the first row um we know that grid is at has at least size one so we are good with this um and then the next piece is we want to initialize our output array which is going to be just columns here and then we are going to do that for as many rows as we have and now we can go uh for every c for every column yeah we then we know the new index we are just going to use the formula that we computed is c j plus k modulo uh columns so we shift by k um by k basically uh this is just shifting k times each column and we're doing modulo for the last photo of the last column as well and now for each row we are going to say this the formula that we set for the new row position which is going to be i plus this j plus k two community to accommodate when each column reaches the last column um and this is going to be divided by columns so for the last column we each time we uh increase the row by one and then we want to do the whole thing modulo rows so that if we reach the last row we start pull back to the first position and so this would be modulo rows and then once we do this we have the two that we are interested in so i2 j2 is equal to grid of inj so this is the new position we have we calculated the indices for it once we shift by k and we assign i and j and then at the end we just return the result uh in terms of like time complexity this is all of uh columns this is our froze here and so overall we are just having of columns by rows so overall is just oven by n if we have m the number of rows and the number of columns um okay so once we initialize correctly it passes test cases um so let's submit okay so that passes test cases and it's a faster solution um yeah so that's pretty much it for this problem thanks for watching and see you in the next one bye
Shift 2D Grid
day-of-the-year
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after applying shift operation `k` times. **Example 1:** **Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1 **Output:** \[\[9,1,2\],\[3,4,5\],\[6,7,8\]\] **Example 2:** **Input:** `grid` = \[\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\],\[12,0,21,13\]\], k = 4 **Output:** \[\[12,0,21,13\],\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\]\] **Example 3:** **Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 9 **Output:** \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m <= 50` * `1 <= n <= 50` * `-1000 <= grid[i][j] <= 1000` * `0 <= k <= 100`
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Math,String
Easy
null
341
hello guys let's all flatten nested let's titrator today so in this question we are given a nested list of integers called nested list where each element can either be an integer or a list itself and again the list can contain elements which are again integers or less and so on so in this question we basically need to implement this class and that means we need to define the instructor the next method and the hashnet is method so the next method basically uh Returns the next value in the iterator and the has next method returns a Bool indicating whether do we still have more elements left in the iterator or not right and our code will be tested with this sort of a photo code where you see the user has next method to check if we still have elements to cover if yes we append the next element by calling the next method and then we finally lit up return the list so let's quickly walk through an example so if this is the given input we see how the elements are retrieved one by one using the next method and finally a list of all the elements are returned and note that it should be in the same order right and one more thing about this question is we are given an interface called necessary integer so this nested list is actually a list of nested integers uh so this interface basically makes our job easier uh the different three utility methods that we can reuse so the first method uh is an instant decent method that basically returns true if the item is an integer or not the vitamin integer the second integer second method you can use to get the integer value of an item if it's in a teaser and the third method is a get list method which basically returns a list of necessary integers right so let's see how to solve this problem so I'll be solving this problem in three different methods one with a recursive approach to an iterative approach using stacks and in the third method I'll show how to use generators as well so let's see how to solve this okay so in the first method will be using a pretty naive approach where we will try to completely flatten the list in the Constructor itself and once we have the flat end list here uh the next and the half next methods can be implemented pretty easily so let's see how to do that so let's have a list called flat end list we will basically store our final list a flat end list uh to do this so let's say we have the colors and if item is centered so I remember how I was talking about the interface where we can to use these methods so if the item is going to teach and what we do is we directly uh appended to the flat end list and you can get the integer value using the method you can think of right go ahead and return yeah so if this is not an integer that means that this is this item is again another list so what we need to do is basically Loop over the list so we can call it for in null term in we can get the list using the Catalyst method foreign easy way to flatten a given list uh Let's test this out um so uh note that the input to the problem is actually a list of nested integers uh this is pretty stupid actually they could have directly given it as a Nestle integer because that is again can be a list or an integer that could have made the problem a bit more elegant but since it's a normal list of natural integers we need to do one Loop uh we need to Loop over the each item of national list and we'll call our request function right so once we call our recessive function uh the flat and list variable will be populated and that would contain the flattened list and then the problem is pretty easily so let's just use a class variable called index to keep track of what index we are currently at so it's all to implement the next method you can just return the element at index and then make sure you increment index by one and then you'll find right and uh as next can also be easily implemented as like basically indexes if index is within the bounds that means has next has to be true so it can return true if self dot index yes the flattened list will become false so that should be the code for this method let's see if it works uh yeah it should be set for index okay that works yeah it seems to work uh so if you notice uh what do you think is a problem for this method uh like you can see your we are doing the entire flattening in the Constructor itself uh which means uh the space complexity is going to be o of n uh plus whatever space the recursion is using so let's call it l so it's going to be o of n plus n uh but the other two methods are pretty fast so these two methods are going to be o of one so let's see if we can do slightly better yeah so in this method we'll be using Stacks to solve the same problem um so the idea is to sort of iteratively unpack the stack and one by one uh add elements to the flattened list so if you think about it recursion is also internally implemented as a stack so yeah that gives you an intuition as to why this method actually works so let's first uh initialize the stack uh with the given list so let's say this is a given input so note that this input has uh three elements zero one two where the first element is this huge list and the next two elements are integers right so let's initialize the stack uh with the given list but every time we add elements to the stack we're going to reverse it and add it so the reason for doing that is because Stacks are implemented as fifo which means first in first out uh so whenever we pop the stack uh we need this element first right so that's the reason why we always reverse it so it's going to be initialized with uh this list 4 5 6. right yeah so this is going to be the initial state of the stack now what we're going to do is uh we're gonna pop the stack and we're going to check if it is an integer or a list if it is an integer that means we can directly return it so this is the implementation of the next method uh so if so here we have so this is the uh this is the element that will be popped and if it is an integer we can directly return it so you can imagine that's the way that works because if this is an integer uh that should be if this is an integer that should be the first value that's actually being returned right so I will do that check first if it is not an integer we're gonna try and uh iteratively unpack the element so that is the case here so the first step is to pop it so once you pop it we're going to extend the stack by unpacking this list so like I said before while attacking this list we're gonna again reverse the list and add it back to the stack so the Reversed elements are going to look like five six four one two three so this is the stack State and the second step and we're going to repeat the same thing again we're going to pop the last element and then reverse it and extend the stack so the stack is going to look like 4 3 2 1. now uh the last element of the stack we're going to pop it and we see that it's in a pizza directly so we can go ahead and return it right and the next time next is called we again we can pop it and return the value and so on and pop it and return the values one two three four and then once we came here and once we come here uh we will again repeat the same process we'll have to pop it and the next stack state is going to look like eight seven six five right uh and then during the next call we pop this uh and appendify to the list and so on so you see how this method works uh and for the has next method that is pretty straightforward because uh since we have a stack variable uh whenever the stack variable actually has elements in it that means that has next needs to return true if not it needs to return false right let's see how to code this so let's start coding uh these approach uh so let me initialize the stack here uh and like I said every time I add elements to the stack I'm always gonna reverse it so in Python you can easily reverse it you can list this way uh and that's all we need to do with the Constructor and in the next method what we're going to do is uh we'll discuss doing the unpacking right so let's write a loop so while there are elements actually there in the stack and you need to make sure that uh the top of the stack is not an integer if it is integer you can directly return it so by the top of the stack is not an integer we need to sort of unpack that and unpack the top of the stack and add it back to the stack so that we can basically do it as self.x10 self.x10 self.x10 so x n by what x then by the element that is being bought right so you can go ahead and call off so once we call Pop we now have the top of the stack needs to be reversed and note that all these items are of type necessary integer so to get the actual list we need to call uh catalyst and we are going to watch this which we can again use the same method right so at the end of the loop we can make sure that the top of the stack will be an integer uh right which you can now again pop it and return it effect so we have the top of the stack and we can call it getting to the right for the has next method like I said all you need to do is just return if stack has elements in it right the length of Stack is greater than zero will return true uh if not it's going to return false uh but the problem with this approach is that so let's say the stack is so the stack is of the stack is in this state so in that case the length of Stack is going to be one because it has an empty list inside right but technically this is identity stack uh so how do you solve this so the idea is to basically do the same thing again right so once we do an unpack uh the stack from the state will go to the state and that's what we want and then we can again use the same logic so what I'm going to do is actually just take this part and put it into value 3D function call unpack so one track is basically going to take a stack uh and make sure that the top of the stack is not a list so that's the job of unpack every time unpack is called it's going to take the current stack and uh it will make sure that the top of the stack is not an integer if it is integer it's going to do a level of unpacking by doing the power and reversing as we discussed we just need to call on the back whatever right and that's about it should work yes it works of course now in the last uploads we're going to use something called generators so to build a quick overview of what generators are for example the range function in Python that is actually in generator so uh how it works is uh anybody can actually write a generator function this way so let's say we want to write a range function so I guess then we run a loop and every time we uh need to return a value instead of returning it we yield so by yielding what we're saying is uh the function state is sort of temporarily passed and so that the next time the generator is called again with the next keyword the function states sort of resumes that way so that's the difference between doing a return and an yield the return is a hard stop the entire function is executed and then you do a return but if you have a loop and you do a yield that means that you're going to sort of temporarily pass the Blue Shield and then resume from the same state so let's see how to do that so let's start covering this approach uh first let's uh Define our generator object so we'll be writing this function called National it's going to take our nested list into as an input and we'll also have a variable called return valve and explain why this is needed you can be set to now right now let's first Define our generator function so this basically takes in this as an input and so what we're going to do here is basically go for each element of the list and we're going to check if this item is an antenna which we can now do as is uh returned right return item dot so this is about the idea of the internet to come into play so if you do a return that means this dope sort of stops on directly you don't want that we want to remember this particular state so we need to do a yield right uh and uh where item is not an integer that means that item is a list in that case what do we need to do basically recursively call our generator with a item as an argument so what can you do is rather than returning item we are going to uh recursively call this generator data that item and remember that since the item is a list we need to call get list to get the actual list and in Python whenever you do a recursion or because you're calling the generator uh it's not correct if you do just the e but rather you need to say email account so that's the pythonic way to do it uh so I would strongly suggest you to read more about generators if you're interested so that you get a better understanding so this is our generator which you have now initialized into this variable now let's Implement our next function so the idea is that the next function will always return whatever values stored in the compound right uh okay let's see how is written while it's actually getting populated so that happens in class next okay so whenever so if you see the solar code you are gonna call has next first so they're making sure if does it have another variable another element to be returned in that case you call next and return the value right so has next is always called first so when whenever has next is called you can set the return value by following the next on the generator this is how generator does actually work so every time the next is called on a generator object uh one value is yielded and the function state is sort of passed at that particular state and the next time next is called the generator it sort of resumes so if you think about it this method is literally exactly the same method as our first approach but rather than having a recursive request recursive method that populates the flattened list and then do the iterating over the flat end list we are utilizing the concept of generators to do all that for us right uh yeah uh yes I know how do we return for this year so how do we know that the there are no more items to be returned for nothing from that generator so this can be done uh using our tri-cats sort of code block uh using our tri-cats sort of code block uh using our tri-cats sort of code block so in Python whenever a generator is done uh if let's say we have uh edited among all the items in generator and we try to call next again so in that case python what it does is it returns a stock exception that as a signal gate that our editor is done right so if we'll put this inside a drive block so if this succeeds we can play a we do have an element that's what it want to do not you can catch the exception and save and false right so every time has next is called we're going to try uh calling next on the generator and store it in return value so it's going to return true and the next thing next is called we know what will be returned and this is going to keep going on and at one point this is going to raise a stop exception in that case false will be returned right and uh this generator is a code logic of this approach now let's see what are the what's the advantage of using this method the time and space complexity for today first uploads so as you see here the Constructor is just off one because all you do is just initialize an instance of the generator next is again of one as next is again all smart but the space complexity uh is going to be of D where D represents the sort of the recursion depth since we do like a recursive quantity generator the recursion stack is going to take some space so that's the only space that this from this process actually uses uh so that's about it for this approach and this problem I said I felt that this was a pretty cool problem to solve uh it's a good design question as it can rather has the potential to test a lot of good Concepts like you know why Traders generators recursion and so on So yeah thank you for watching
Flatten Nested List Iterator
flatten-nested-list-iterator
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the `NestedIterator` class: * `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. * `int next()` Returns the next integer in the nested list. * `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = \[\] while iterator.hasNext() append iterator.next() to the end of res return res If `res` matches the expected flattened list, then your code will be judged as correct. **Example 1:** **Input:** nestedList = \[\[1,1\],2,\[1,1\]\] **Output:** \[1,1,2,1,1\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\]. **Example 2:** **Input:** nestedList = \[1,\[4,\[6\]\]\] **Output:** \[1,4,6\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\]. **Constraints:** * `1 <= nestedList.length <= 500` * The values of the integers in the nested list is in the range `[-106, 106]`.
null
Stack,Tree,Depth-First Search,Design,Queue,Iterator
Medium
251,281,385,565
3
foreign problem and the problem's name is longer substring without repeating characters in this question we are given a string s and we need to find the length of the longest substring without repeating characters so by definition a substring is a contiguous non-empty sequence of is a contiguous non-empty sequence of is a contiguous non-empty sequence of characters within a string there shouldn't be any gaps between the string so such a string will be a substring and the length of the substring will be less than or equal to the original length of the string now let's take a look at this example and see how this question can be solved I've taken the same example this is the string as given to us now we have to find the longest substring with non-repeating characters so to an acredi non-repeating characters so to an acredi non-repeating characters so to an acredi you can see that this is the longest substring with non-repeating characters substring with non-repeating characters substring with non-repeating characters there is also one more same substring here with three characters so you return 3 as the output so how are you checking if all the characters inside this are unique you're comparing each letter in that substring with rest of the letters and you can see that all three are unique so which data structure you are going to use check for uniqueness you can either use a hashtag or a hash map so let's to use a high set because hash tables do not contain duplicate values I am using a hash set so let's declare a headset and then I'm going to declare two pointers left and right so left will be the slow pointer both starting from the zeroth index so the right pointer will be the faster pointer which will reach the end of the string first so we are going to add the character at right inside the set if it is present or not the character at right is a we check if a is present inside the heart set no it is not present so add it inside the asset and you declare our result variable Max which will initially be 0 so we are going to return this as the output so before starting a new iteration you find the length of the current substring so length of the current substring will be so right minus left plus 1 will give you the length of substring so right and left are Pointers plus 1 will give you the length because right and left are index positions which start from zero so length is equal to 0 minus 0 plus 1 is equal to 1 so in each iteration we check if Max is equal to math.max of current Max or less so max math.max of current Max or less so max math.max of current Max or less so max is initially 0 right 0 comma 1 is equal to 1 so max is now having the value 1 and now we go for the next iteration you move the right pointer we check if the character at right is present inside the asset or not B is not present inside the asset so add it inside the asset and now calculate the length of the current substring so right is pointing at one left is 0 plus 1 is equal to 2 and update Max so current Max is 1 and length is 2 so max is equal to 2 then go for the next iteration check if the character at right is present inside the set it is not present C is not present so add it inside the set and calculate the length of the current substring so write this 2 minus 0 plus 1 is equal to 3 so max is currently 2 comma 3 is 3 so max is 3 now go for the next iteration check if element at right which is a is present inside the set yes it is present so you remove that element from the set and increment left and now you add the element at right inside the set okay calculate the length Max will remain 3 because 3 comma 3 will remain three now go for the next iteration it is pointing here check if the element at R is present inside the set yes it is present so remove the element at left and add the element at right and increment the left pointer now calculate the length then this 3 and Max is 3 Max will remain three now go for the next iteration check if element at right is present inside the set yes it is present so remove the element at left from the set limited left to C so remove C and add the element at right to C so add it and increment the left pointer now calculate the length is 3 and Max is 3 so max will remain the same go for the next iteration check if element at right is present inside the side yes it is present so remove the element pointing at left from the set this is removed increment the left pointer now the element of right is B it is present inside the set so we have to continue removing the element at left from the set so b u is also removed now increment left now check if you are able to add the Elementor right into the set it is not present so add it into the set and now find the length 6 minus 5 plus 1 equal to 2 is less than 3 so 3 will remain as the max now go for the next iteration the element at right is B check if it is present inside this set yes it is present so remove the element at left from the set element at left is C so remove C and increment the left pointer check if you are able to add the element at right into the set B is still present inside the set so remove the element at left from the set that element is removed increment the left pointer now check if the element at right is present inside the set no it is not present so add it to the side and now find the length of the substring write a 7 left to 7 so max is greater than 1 so max will remain the same now go for the next iteration and now write us reached the end of the string so you end the iteration and you return whatever is present inside the max variable outside the for Loop so 3 will be returned as the output I know there is a lot of iterations and calculations now let's code it up and then we'll debug the code using an example inside an IDE coming to the function they have given us this is the function name and this is the string s we have to play with and this is the output return type which is the integer representing the longest substring length so let's start off by creating a hash set which will contain characters now let's declare our output variable I'm going to name it Max now let's declare the two pointers left pointer which is the slower pointer will be starting at the zeroth index and now we use a for Loop for the right pointer because that is the first pointer and will be reaching the end of the string first the right pointer will also be starting at 0 until it reaches the end now let's extract the character pointing at the right index position foreign ER is present inside the set or not so until this character pointing at the right index is present inside the set we need to remove the character pointing at left from the set so set dot remove s dot carat left and we increment the left pointer in each iteration and outside the for Loop it means that character is not present inside the set so we add it inside the set and now let's find out the length of the substring and each time you add the character inside the set you need to find the maximum length of the substring so max will be replaced with Max of current Max and the length so whichever is maximum will be replaced inside Max and now outside the for Loop it means that you reach the end of the substring and outside the for Loop you can return the variable Max now let's try to run the code this is right plus the test cases are running let's update the code there you have it our solution has been accepted now let's debug the code inside our ID so I've taken the same code and I've taken the same string as the input so I'm calling this function inside the main method and it will return an integer variable Max and I'm printing it I've added a breakpoint here so let's debug it so here you can see s is having this string so let's step over no CH will have the character at right which is a we are checking if the set contains CH set is empty so it doesn't contain so it won't enter the while loop and we add that CH into the set so here you can see at zeroth index a has been added into the set now length is calculated as 1 right minus left plus 1 and Max will also be one so here you can see Max is 1 and in the next iteration right is equal to 1 right is pointing to the letter B now we're checking if B is present inside the set so it only has a as of now so it won't go inside the while loop B is added into the set length is equal to right Mass left plus 1 that is length is 2 current length will replace Max so max is also 2 now so here you can see Max is 2 now right is equal to 2 so right is pointing at letter c is not present inside the set so it won't enter the while low and C is added into the Set current length is equal to 3 now current length 3 will replace Max so max is also 3 now so here you can see Max is 3 and now right is equal to 3 right is pointing as letter A we're checking if a is present inside this side yes a is present so it will enter inside the while loop and now we remove the element pointing at left is pointing at zero so s dot carat of 0 is equal to a so we remove a from the set here you can see it has been removed and now we increment left will become one now we are going to check if set contains a is not present inside the set so it will come out of the while loop and now it will add element pointing at right is 3 the third index has letter A so we add a into the set now we see a has been added again now we can create the length is equal to 3 minus 1 that is 2 plus 1 3 Max is already 3 so it won't replace so max is still 3 now write is equal to 4 the character pointing at right is B we're checking if B is present inside the set yes B is present so we have to remove the element pointing at left is equal to one left is pointing at B so remove B so B has been removed increment left will become to chsb check if B is present inside the set no it is not present so add it into the set again so B has been added again now check the current length of the substring it is still 3 so it will remain the same now right is equal to 5 character at 5 is equal to C check if C is presents inside the set yes C is present so we have to remove the element pointing at left so left is equal to 2 is pointing at C so c will be removed from the set C has been removed increment left is equal to three now check if C is present in the set it is not present so add it so it has been added now and now check for the length remains 3 so max also remains three now write a 6 CH has B now check if B is present inside the set USB is present so remove the element pointing at left so left is pointing at a so a will be removed from the set that you see a has been removed now increment left check if V is present inside the set yes it is present enter and remove B from the set the UCB has been removed increment left now check if B is present inside the set now it is not present so add it so B has been added into the set find the current length is 2 but Max is 3 so max will remain as 3 now right is 7 so we are at the last index check if B is present in Center set yes it is present so left is 5 so left is pointing at c will be removed now increment left check if B is present inside the cell b is also present inside the set so B will be removed increment left check if B is present inside the set now it is not present so B will be added so B has been added into the set find the length is equal to 1 but Max is 3 so it will come out of the for Loop because so length is 8 and right is also 8 so this condition will fail and you come out of the value and you return Max has 3 inside so 3 will be returned as the output so here you can see 3 has been returned as out so the time complexity of this approach is often and the space complexity is also often where n stands for the length of the string s that's it guys thank you for watching and I'll see you in the next video
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