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
202
hi everyone so let's solve another easy lead code question which is happy number so we have to write an algorithm and if uh determine if a number n is happy or not a happy number is number defined by following process starting with any positive integer replace the number by the sum of squares of its digits repeat the process until the number equals one where it will stay or it loop endlessly in a cycle which does not include one those number for which the process ends in one are happy numbers so for 19 we will start with uh 19 as a current number and we'll square the digits and the number now is 82 well again squared is its number now is 68 and for 68 of the num squaring the digits up results 200 and 400 it's 1. so we are ending at 1 so this number 19 is happy but somehow if we are continuously in an endless cycle then the number is not considered to be happy so actually it's very easy this uh implementation is already given in our problem statement but the main thing that we need to focus over here is how will we determine the endless cycle so uh to do that we somehow need to store the numbers that we have already visited and in case we comes up on the number again that means we are in cycle so we'll just return false let's implement the solution so we need set of integers which will store all the number visited till this point and we want to continue until our current number is not equal to one so until our conte current number is not happy so if uh so this loop will break if n equals one so that means a number is happy so we'll return true now let's write processing in between so first of all we want to calculate the sum so to calculate that our current number is end and our sum is starting 0 so um we'll have to iterate on all the digits of current number and calc square it and calculate the sum so to do that while current is not equal to zero let's cite rate on current number and we will actually find out the last digit which is easy to find out using mod operator and our sperm would be sum plus last square last digit square and our current element would be current divided by 10 okay so by the end of this loop in some variable we have the sum so we have to see if we have seen this sum earlier or not if visited dot contains system current sum is already seen then we simply return false because we are endless cycle otherwise we will just put this number in our map in a set and also now our n is changed to current sum let's run this problem yeah so we have actually uh successfully submitted for this solution uh that's it for today's video i'll link i'll put out a link to this problem in description box and also to my github repository where you can actually see the solution let me know if you tried out this problem and thanks for watching
Happy Number
happy-number
Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squares of its digits. * Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. * Those numbers for which this process **ends in 1** are happy. Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. **Example 1:** **Input:** n = 19 **Output:** true **Explanation:** 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 **Example 2:** **Input:** n = 2 **Output:** false **Constraints:** * `1 <= n <= 231 - 1`
null
Hash Table,Math,Two Pointers
Easy
141,258,263,2076
530
hi guys welcome to algorithms Made Easy my name is kushboo and in this video we are going to see the question minimum absolute difference in a BST given the route of binary search tree return the minimum absolute difference between the values of any two different nodes in the tree so here is an example given to us and in this the minimum difference between any two nodes can be determined by having a difference of 2 and 1 which is 1 or between 2 and 3 which is again 1 so the output is 1. here's the example number two and here also if you see the minimum difference between the nodes is between 48 and 49 which is 1 or you can say within 0 and 1 which is 1. the constraint given to us are that the number of nodes in the tree can range from 2 to 10 raised to 4 and the values of the node can be from 0 to 10 raised to 5. so let's go ahead and deep dive on how we can solve this particular question so let's take a sample tree with us and we'll try to find a solution for this tree now since we are told that this is a BST it means that the value of left node is going to be lesser than the value of root which is going to be lesser than the value in right so we are going to have these conditions satisfied for each node secondly when we say that it is a binary search tree we know that the in order of the BST will produce a sorted data so if you write a in order for this particular tree you would find the elements in the order as 1 2 3 4 and 6. and the minimum difference can be the difference of the two nearest nodes in this sorted data no nodes which are far away from each other can have the minimum difference so we are going to take advantage of this property of BSD and try to solve this question so what is the in order as we talked about in order is one two three four and six now that we have this let's try to see how to find the in order first and then we'll try to incorporate our code to find the minimum difference in that in order traversal that we are doing so for the inorder traversal it is simple first we need to Traverse to the left then we are going to process the root and then again we are going to Traverse to the right so this left and right reversals are going to be recursive and this is somewhere we are going to do the actual processing of the current node or the current route that we have what is the processing that we are doing in the processing part we will be calculating or he'll be setting the minimum difference that we have found until that particular point so what will be the difference will be having the previous node into account and will also have the current node value into account and it will be the difference between the two values and so the answer or the minimum difference will be the absolute difference between the previous and the current load value with this what we'll do is we'll update the previous for our next iteration this is about the looping that we'll be doing but when we have a recursive solution we also need to have a exit condition so what can be the exact condition over here we can check whether the node is null or not if the node is null we cannot do anything but we need to return the minimum difference so that's all about the algorithm that we are having for this solution now let's try to dry run this with the example so let's take the solution over here and we have this tree we'll start with the root node so let's take this handy with us that we are going to first process the left tree then we are going to process the root which is the root node 4. then we are going to process the right tree for this root so we are going to go from top to bottom so the first part is to process the left now this is not a single node this is a tree over here so it will again call a recursion so for the recursion it will go and it will make this as a root node and for that it will try to process left and right so again for an order we will have process the left for this to process the root node 2 and then process the right of this now since this left is again not the single node it is a tree so we'll again jump into it and we'll go inside that now we have gone to this node assuming that this is our node so for this our left is null so we'll process null node process root and write is also none so over here we are going to end now what happens over here is we go to this null node trying to process this null node and since this is the exact condition that if the node is null we need to return the minimum difference in the start since we are minimizing the result we initially need to store a maximum value in the answer so the minimum difference over here in the initial point will be Max and now the previous node is still null since that is not going to make any sense while processing so now this node is done next we are going to process this node so we are going to go to the one node and we will process this for this we just have this calculate Min difference and update previous thing so what will be the mean difference for this since my previous was null earlier so I don't have to calculate the minimum difference now I can skip that but my current node will become my previous node for the next iteration and that's with processing node 1. next is to process Its Right which is null node now for again this one we are going to say that this is the null node so we need to exit we need to return the minimum difference which is still Max so till here also our Min difference remain the same our previous remain the same because the node is null there is no use in setting the previous to this node so that's about processing the null node now we need to process root node 2. so we'll go over here we'll see we have a previous which was 1 so my Min difference will become minimum of the previous value which was Max or this 2 minus 1 which is 1. so my main difference over here become 1 and my previous over here will become 2 and with this I can say that the processing for root 2 or the node 2 is done now what we have is we need to process the right tree so we will go to this right node over here and for this we have left root right which is null three null and now we'll start processing these things so we'll go to the null Value First and over here since it is null I am having a exit condition of returning Min difference and since it's null I won't update the previous so I'll turn one from here that's done next is to process the root which is this so this will become minimum of 1 and my previous was two so it will become absolute difference of 2 minus 3 or 3 minus 2 which is 1 again so minimum of this is 1 and now my previous node will become 3. so we have updated 3 over here now moving next is so that's done now moving next we'll move to the right over here for the right notice null so it is an exact condition and we return the minimum difference and do not change the previous value so that's done now everything in the left is complete so we'll move on to process this root value which is 4. so we move to this root we see my previous was three my current value is 4 so my minimum difference will be minimum of 1 or 4 minus 3 which is again going to be one and my previous node value will become this current node value which is 4. with this I am also done with this root now I am going to process the right for this so let's see what is there and write in right we have this node as a root and its left and right are null so let's go ahead and process all the values in the right so we'll go to this null which is this node and since it's null we'll return the minimum difference and not update the previous Still Remains 4 and that's done and then we'll go to the root now this root is having a value of 6 my previous was 4. the minimum difference will become minimum of 1 or this absolute difference of 4 and 6 which is 2. so the minimum Still Remains 1 and my previous gets updated to 6. so that's done now I'll move to the right node for this which is again null so I am going to have the exact condition and return minimum difference so with this is complete and my entire tree is now processed and so what I am doing is I am just going to return this minimum difference that I have found until now which is nothing but one so this is the recursive way of solving this question now in order traversal can be done in a iterative way as well so that's a homework for you guys you can watch out our video on how we do a iterative pre-order an order and post iterative pre-order an order and post iterative pre-order an order and post order traversal to learn how we can iteratively solve this question the steps will remain the same while we are processing the root node or the current node we are going to calculate the minimum difference and update the previous that's all only the way in which we are traversing through the tree is going to change for iterative and recursive now that we have seen the dragon and the algorithm now let's first take a few variables so I'll have a global variable for a difference that is a minimum difference and my previous node value and here since I want to give null I am taking a integer rather than Intel over here this is going to be my recursive function so for this I'll first write my exit condition which is if my root is null simply return the minimum difference otherwise Traverse left which is calling this function on left then we are going to process root and finally we are going to again call this function on right in processing the root we are first calculating the minimum difference so if my previous is not equal to null then only I am going to find the minimum difference which will be minimum of the previous value in this variable and the value from current calculation which is the current root minus previous now we are also going to update the previous so if my root is not null then I am going to update my previous with my current value so previous becomes root dot val after this is done after everything is done even write processing is done we just return the minimum difference and that's it let's try to run this and this is giving us a perfect result let's submit this now it got submitted the time complexity over here is O of n where n is the number of nodes that are present into the tree and the space complexity is O of edge where H is the height of the tree because we are going to need a recursion stack space for H levels that's it for today guys I hope you like the video if you did please do not forget to click that like button also share your thoughts in the comments and subscribe to the channel if you are already not subscribed so that you get a notification of all the new videos we post thanks for watching and I'll see you in the next one foreign
Minimum Absolute Difference in BST
minimum-absolute-difference-in-bst
Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,0,48,null,null,12,49\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 104]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)
null
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
532
1,861
hello friends welcome to coding interviews channel hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe let's jump into today's problem rotating the box you are given an embankment matrix of characters blocks representing a side view of a box each cell of the box is one of the following a stone a stationary obstacle are empty so the box is rotated 90 degrees clockwise causing some of the stones to fall due to the gravity each stone falls down until it lands on an abstract another stone are the part of the works gravity doesn't affect the obstacle's positions and the inertia from the box rotation doesn't affect the stone's horizontal positions it's guaranteed that each stone in the box rests on a ball obstacle another stone or the bottom box return n by m matrix representing the box out of the rotation described above so basically we are given with an entire matrix and the box will contain either a stone or an empty or an obstacle right so each of the cell in the matrix could be any of these phases right and what they are going to do is they are going to rotate that box 90 degrees clockwise right and when they rotate the obstacles don't change the position so obstacles will be staying same basically right so gravity doesn't affect obstacles right so obstacles will not change their positions but the stones will change the positions right so the thing another thing that is mentioned is when the box is rotated it doesn't affect the horizontal position of the stones right so they just fall vertically from where they are into the same column right so like that so for example uh i'm going to represent for just for the discussion sake uh and for the better understand right i'm representing store with s and uh obstacle with o and empty with e right so that means whenever the s the stone is present it has to hit either the bottom of the box or another stone or obstructed right so whenever we rotate the box the stone has to hit an obstacle or an empty space or it should be next to the other stone right so any of the three possibilities right so let's go and look at it right so for example if the given matrix is like this s e s uh this is just for our discussion sake right so but s is represented hash and obstacle is represented star and empty is represented right but you have to better understand i'm representing right so s e f that means stone empty stone right so that means this stone has to be moved until it hits uh obstacle armor another stone right so let's take this empty action it has to hit an obstacle or another stun so that means this tone at zero position has to be moved down it has to be more here okay this one what is it is empty so this one has a mode here right so let's so this is not the representation that we want at the end but let's take this so when we move the stone to the forward right it becomes this right just for the information also although we want to represent the final result as n by n matrix right and biomatrix so this is what it's going to do so this need to be transformed to the environment anyway that will do it so but ultimately this stone is getting moved until it hits another stone or obstacle or one more thing is bottom of the box that's anyway granted right so if it is we can't anyway go out of the box anyway right that's one thing and let's go look at another example right this one so where this can move so let's see right so this can move here right good and after that we have another stop but this one right so we moved the first stone to the empty right that became this one it became empty and this one became s and we have another stone here so this has to move down right so now we moved this first one and now there is another stone that has to move too so it comes this but is it the right answer is that the way that it moves no not really so in that case whatever we are seeing so this is not the right answer not the right one right so how we should actually move right so we should move from the bottom so we should not start from the zeroth index but we should start from the n minus one so assuming that length is n so we will start from n minus one theta right so we will have to keep track of what is the empty position that is available next so initially we will initialize with the empty position to be n minus one right so here n minus one is empty yes it is still empty right so there is nothing to be more so our index let's go to index is also in minus m t is n minus 1 and x m so if n index is an empty then we can't do anything so we do index minus 1 right then that is minus 1 that will be n minus 2 right so instead of n minus 2 and all that stuff right so here we know there are only 4 0 to 3 let's see which is 3 that became 2 so index minus became 2 so 2 it is a stone but this stone has to be moved to the next empty position that means where to the 3 right so after moving that right and index minus will become 1 right because the index is we are at 2. so that's good now at 1 we have another empty that's good we can't do anything anymore right so except that we will be subtracting the index again so it becomes 0 so it's 0 you have a stone right this stone will move to the next empty position what is the next empty position it is 0 right so index minus will become -1 and index minus will become -1 and index minus will become -1 and just empty minus one is right that will become one but index has all already become management that means there are no more uh stones to be moved right so that's how we'll be proceeding so this is not the right way but this is the right way when you move these two stones they should be going to the bottom right good but let's look at another example right so when there is a object what happens so here i will be initializing the same right it is empty still three right so what will what we are going to do we will be subtracting the index minus one right so it will be same index minus that will be 2 is abstract so that means empty cannot be three right so empty has to be updated to them empty has to be updated to index minus one so that means empty became what index is to empty within one this is the condition that we need to remember so whenever we hit a stationary obstacle whatever the empty that was there we need to update it to index minus 1 that is that becomes mt is equal to 1 in this case right so good uh and also we will be anyway subtracting the index right so index -1 index right so index -1 index right so index -1 that becomes what one so one is empty right we can't do any index became zero so zero is having a stone right that means where we should move this stone the next empty position empty is one right so that becomes basically this right so here index minus that becomes minus 1 right so let's go and empty minus right that but there is index already became negative so we don't have to move anything so that's how we have to deal with the obstacles so now that we know how to do it for single basically one by m matrix right so it's all about replicating that for all other rows right so assuming the rows as columns and move the index so this is the logic that we are going to apply so the only change that we are going to see is this thing we have to do it for every single row right and when we actually make this change right we will be doing that in the result array right result array so input is m by n right m by m but output has to be n by m that's what it said right so this is input and this is our simple that's what we did so let's look at the code simple let's follow the code and try to understand the same logic that we have uh see uh get m and n first so length of the box and length of the box of zero right so that will give you m and initialize the answer uh list basically the answer array with n by m right this would this will do the initialization for answer so now as we said whatever the logic that we discussed we are going to go from n minus one right last one right so for each row right the column will be from n minus one okay for each row the column will be processed from n minus 1 that means the last element in that particular row so that's where we are across so we care about two things right here stone and an obstacle if it is a stone what we are going to do is whatever the next empty location we just put there right next empty we have initialized to n minus one just like we started right when we went through the example the empty is initialized to 3 and index is also n is less to 3. so in this case n is 4 right n minus 1 is 3 so that's what we are essentially doing right so here n is n minus 1 is initialized to empty obviously since j is starting with n minus 1 that means the index is minus 1 basically right so when we put the answer into the answer i direct there is some magic that we need to do so if at all the box of ij is hash means stone with a stone right so that stone has to be moved to the next empty location right next empty location so what is the next empty location which is initialized with n minus 1 in the current moment but it could be changing so we will be going to that row so remember even though input is m by n we are going with n by m as the output that's what the requirement right so empty became what so empty was represented as even though it was column initially right so in answer we are going to represent the empty that is the row and which column it is going that is a trick you want to get to what is the trick what is the column that it is going to is the question so which column we are at is an atom so which column we are at generally in order to calculate which column we are at right since rows are becoming columns right rows are becoming columns so that means whatever the row that we have that is i throw right whatever the row that we have i through that i throw we will be coming down right so if you are just look go look at the example right if this is the i throw right that is 0 and 0th column that is coming to here so which we don't know yet right but how to calculate that as long as you know the total number right as long as you know the total number minus one how many uh i mean the indexes index are starting from zero to m minus one right so the row index is 0 to n minus 1 and the column index is 0 to n minus 1 so m minus 1 minus i so that is the location that it is going to right so what is m minus i 1 is basically that is the row that it will be in there so that is a column that it will be in the output matrix so another way that you can think of is so basically let me type it like this right so box of right m minus 1 minus i of m symbol right so this is what it's going to be but we are going to return the output as n by matrix that's why we flip the row and couple assemblies so that's how we are come up with this one so this will be move right the stone is getting more and empty you'll have to subtract basically while you're subtracting empty because we have initialized mt to be n minus 1 that is the last index in that particular row right and then one more thing we are going to do here is since the box is moved right that location in the original array need to be updated to the empty one because that is moved okay right so that's the important step if you don't do this then what happens is you have already moved that and when you encounter that row that index again right it will be problematic right so this will be another thing at united okay go if that is the stone but what if it is a obstacle what is it obstacle just like here if it was an obstacle right we just put in updated the empty also right we update the index anyway but we update the empty here right that is what we are doing we are updating that empty is what the current index minus one what is the current index j minus one and obviously we will copy the uh stone sorry obstacle also into the answer right answer so mt would be the current index minus 1 that's what we did empty current index is what 2 minus 1 is 1 that's what we are doing mp is equal to ms so it's the same logic that we discussed we are doing this for all rows so i is ranging from in the range of m right so 0 to n minus 1 we are doing this for all rows so this is for every row we are doing that is how we are able to compute the problem now let's look at the time and space complexity for this right so time and space so we all already know the matrix size is m by m right so here we have two for uh loops so that means we are going to take m by n time and if you want to call it as n by m that's also fine that's our problem so that's that'll be order of m time the complexity time complexity will be order of m and what is the space complexity so we are given with m by an input and we are supposed to written a matrix of n by m right so answer voltage that we are using so this is an extra space that we are essentially taking right but if you think whatever since it is required for returning your output right so if you take that out of equation right then you are using only constant space but if you consider that towards the space then it will be on our energy space right so we are using order of mn space time complexity order of mdn and space complexity also control mntn so that's how we are able to solve the problem basically so if you have any further questions please post them in the comment section below this video i'll get back to you as soon as i can thank you for watching you will be able to find several playlists regarding various categories of the problems such as pfs dfs demo programming stats queues and linked lists please check them out if you haven't subscribed to my channel please go ahead and subscribe and share also among your friends please click on the bell icon so that you will be notified about all my future videos thanks again for watching i will be back with another problem very soon till then stay safe and goodbye thank you very much
Rotating the Box
building-boxes
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity **does not** affect the obstacles' positions, and the inertia from the box's rotation **does not** affect the stones' horizontal positions. It is **guaranteed** that each stone in `box` rests on an obstacle, another stone, or the bottom of the box. Return _an_ `n x m` _matrix representing the box after the rotation described above_. **Example 1:** **Input:** box = \[\[ "# ", ". ", "# "\]\] **Output:** \[\[ ". "\], \[ "# "\], \[ "# "\]\] **Example 2:** **Input:** box = \[\[ "# ", ". ", "\* ", ". "\], \[ "# ", "# ", "\* ", ". "\]\] **Output:** \[\[ "# ", ". "\], \[ "# ", "# "\], \[ "\* ", "\* "\], \[ ". ", ". "\]\] **Example 3:** **Input:** box = \[\[ "# ", "# ", "\* ", ". ", "\* ", ". "\], \[ "# ", "# ", "# ", "\* ", ". ", ". "\], \[ "# ", "# ", "# ", ". ", "# ", ". "\]\] **Output:** \[\[ ". ", "# ", "# "\], \[ ". ", "# ", "# "\], \[ "# ", "# ", "\* "\], \[ "# ", "\* ", ". "\], \[ "# ", ". ", "\* "\], \[ "# ", ". ", ". "\]\] **Constraints:** * `m == box.length` * `n == box[i].length` * `1 <= m, n <= 500` * `box[i][j]` is either `'#'`, `'*'`, or `'.'`.
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
Math,Binary Search,Greedy
Hard
null
994
hey what's up guys jung here again and today uh i want to talk about this lead code problem number 994 rotting oranges medium problem it's very i think it's a it's an interesting problem okay you're given like a 2d grade and on each grade there will be only three options here either zero one or two where zero representing an empty cell uh one representing a fresh orange and two representing a rotten orange every minute any fresh orange that is adjacent four directionally to a rotten orange becomes rotten and returns the minimum number of meanings that must elapse until no cell has a re as a fresh orange if this is impossible return minus one is that yeah it's pretty straightforward right so at the beginning let's say assuming for example this example one here let's assume you have a rotten orange at this position zero and on the next second on the next minute the adjacent uh fresh orange will become a rotten orange so basically this is like a plague right a disease that's spreading to all the uh the oranges in this case and until all the other adjacent oranges have been uh have been i've been traversed essentially right i mean so by this time i believe everyone can see this is like a breadth first search problem because it satisfies all the uh the signatures of a bread first search problem you have four directions and then you need to find the minimum numbers that's what i mean after traversing to all the uh the oranges okay and uh i think one more it's just uh one more thing to be careful here it asks you to return minus one if it's not possible to make odd orange other fresh oranges to be become a rotten art to become the rotten orange become rotten then i think in the end we simply just threw a loop through we can just do a final check in the end we just look throughout this 2d board 2d broad to the board and when we see a fresh orange we simply return minus one okay pretty straightforward huh right so the main code for this is just like just the standard breadth first search template okay let's try to implement these things here okay directions right it's very standard breadth first search minus one zero okay we need to define four directions right that's up so that's down and so this is left okay left and this is right okay then we're gonna have like the length the rows and columns okay the rows and the columns okay so the grid is at the length of the grid is at least one so we don't have to check this m and then here to do a sanity check cool so other than that we need a queue right since we going to do a breadth first search collections dq okay dq so where to start right and to start with we have we start with all the rotten oranges here and remember even though in the example here we only have one like rotten orange but it doesn't say that there will be on only one rotten orange at the beginning which means there could be like two rotten oranges right so for in that case so first we're gonna loop through the uh the to the grid here in range on m right for j in range n basically if the grid i j is two right then we simply add um append um pan this uh this orange to our queue so after this photo an acid photo appear we have all the basically we have our starting point uh where we have all the rotten orange added to this q here okay now let's do a while q right so that's the uh that's the bfs search and for bfs search we're gonna do a four in range length of q okay so and then current i current j right equals to the q dot pop left okay so this is the one uh the things you need to be careful so for the bfs search uh we add to the tail but we always pop at the beginning at the at we're at the front okay so and for each of the i here right we do a loop here right for directions in range sorry in directions okay directions and then the new i become the d current i plus d zero okay and new j goes to current j plus d one right and then we just do a boundary check here and okay and what so for the bfs search you know if you know template we have to somehow we don't want to basically end up in the infinite loop here that's why we have to mark the uh basically the node we have we had previously visited before but in this case we can simply mark that we can simply mark all the nodes at the vcc nodes two to two here two is the rotten orange right and we only add the new node to the q if it's a fresh orange right basically that's what i'm doing here so b and if the dp and also if the dp at nu i and new j is one okay so what i'm doing here is if the new i and j i are within the 2d board and this great is a fresh orange that means that okay now it's this it's his turn to be uh to be able to be to become a rotten orange so that's why i do a q dot append new i at new j right and after adding this one to the q don't forget to set this fresh orange to the rotten orange okay set this one to two here yeah so basically this is the uh this is basically the what's the bfs search here okay the bfs traverse and but in our case we haven't set this answer yet you know i mean we can simply do an answer dot plus one here you know and then um but there's a like small issue here i mean in the end we simply return the answer right so basically that's not going to be our answer here but there's like a small uh issue here let's in assuming yeah assuming in this case okay assuming in this case we have like zero we have empty space and only one rotten orange and in this case uh at the beginning the queue will have this one rotten orange and after traversing this um after traversing this q here we didn't see any fresh orange that's why uh we'll be ending we'll would we'll stop this while loop here but we're adding this but we're adding these answers by one right so now we'll get a one instead of zero um i mean you can argue we can always do a answer minus one i mean this might work right but this answer minus one i also have another issue let's say we don't have anything in this queue here okay i mean let's say we don't have any rotten orange in this 2d board everything is a flash or everything is like no sorry not everything is fresh or let's say everything is an empty cell and in this case the answer will be 0 because we never get into the skew here but we do answer minus one so in this case but we are expecting zero not minus one so we have to deal with that uh special case as well so i think one of the simple solution here is that before doing the answer before we before increasing the answer here we can simply do a check here basically if the queue is not empty then we increase the answer so that i think that aligns with the description of the problem you know every minute right basically you know every time after uh after finishing after looping through the current uh the current layer okay and if the queue is not empty then we know okay so there will be more fresh oranges becomes a rotten in the next minute that's why we will basically increase our the minute by one okay so that can solve all our edge cases and yeah i think one uh one thing we haven't caught we didn't haven't covered here is the uh the check for the minus one so an easy check is that we simply do a another for loop here we loop through the whole grade here one more time and if the grade i and j equals to one i will simply return minus one right because we have already uh basically infected all the uh all the fresh oranges within this while loop i mean if there are still some fresh oranges left then which means it's that something we cannot i mean that i mean it means those are the oranges we cannot reach right from the from this rotten oranges that's one that's when we need to return minus one here otherwise we simply return the answer um yeah i believe this should just work let's try to run this code here direction okay directions okay so this test pass this test case passed let's try to submit it yeah so and yeah pretty straightforward okay yeah how about the timeline space complex complexity here right so um i think here it's like uh o of m times n right that's the for loop how about this while loop so the while loop we have um yeah so the while loop is also all of m and n because we will since we will not reprocess uh the node for multiple times basically we will be only for the worst case right for the worst case let's say all the uh odd oranges will be uh become rotten so that means we will basically will do this pop like m times n times in total and we'll do this like for each of the m times n we'll do this for loop that's going to be 4 right so times 4 right but still since this 4 is a constant still time complexity for this while loop is a o of m times n and the uh and the space complexity right the space complex and here is also like another o of time in so in total uh in total the uh the time complexity is still o of m times n so the space complexity is also like o of m n right that's the uh that's the size of the q here yeah actually you know so the size of the cube it might be uh smaller than i'm times n because we're doing like this uh the bfs search so every time we're only processing one layer of data but still i mean still it's a it's um it's amortized o of m times n yeah cool i think that's it for this problem yeah it's very it's just like a very classic uh typical like bfs search problem and it's just like see anything until here it's just basic bfs search problem that the template and we just add one more final check here to handle this minus one case yeah okay i think that's it for this problem i hope you guys enjoyed what enjoy watching the video and stay tuned see you guys soon bye
Rotting Oranges
prison-cells-after-n-days
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`. **Example 1:** **Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\] **Output:** 4 **Example 2:** **Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\] **Output:** -1 **Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. **Example 3:** **Input:** grid = \[\[0,2\]\] **Output:** 0 **Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 10` * `grid[i][j]` is `0`, `1`, or `2`.
null
Array,Hash Table,Math,Bit Manipulation
Medium
null
1,598
today we will be discussing problem number 1598 of lead code it was a part of weekly contest 208 uh and it says you can easily guess out the approach by while seeing that the pictorial description so here the input will be logs something like this so from the main we are going to the d1 folder and from the d1 we are going to the d2 folder but when we are saying dot slash we will again go to the p1 so this will not be a part of our account then again d21 so from d1 we are going to d21 and then dot slash so this we have to ignore so the count will be 2 okay now we'll see this so d1 will increase the count t2 will again increase the count back dot slash uh will not affect our account d3 account will be 3 then dot slash so we will decrease our count account 2 then here our count will be three and for this input initially our count would be one then this occurs so zero and for all this will not decrement again so it will be zero only so see we have taken this min up variable which we will be returning finally we will iterate our array which is box dot length a plus now if min up is greater than zero then only do this and our logs of i dot contains if it contains this operation then we have to decrement else let's see if it contains this what it contains x if it don't contains dot slash and not contains logs i dot right and at last we know and try to run our code right so what we are basically doing uh if main knob is greater than zero to avoid the negative part of our variable and if it contains dot slash then only we have to decrement it and if it contains backslash and not contains dot slash right then we will increment our counter right try to submit this code yeah so that's it for today thanks
Crawler Log Folder
crawler-log-folder
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
null
Easy
null
1,561
hello hi guysi I hope that you guys are doing good in this video maximum number of coins you can get it has been asked by clear tip flip cart danzo and last one two years you can see the timings let's see uh again it's a marked as the medium problem but it's a very easy problem so let's see the problem statement itself we have three n piles of coins so again uh we have three n piles of coins of varying sizes you and your friends so Main thing is three and piles of coins uh you and your friends take will take piles of coins as follows and in each step you will choose any three piles of coins so you will have three options to choose on and it can be any three options to choose from so that is one thing that you can choose anything whatsoever you want of your choice Alice will pick now when you choose the three options Alice will pick the maximum of the coins the pile will have the maximum coins Alice will pick so Alice Max right Alice will pick the maxium coins now you um like or you can say the largest coins right uh you will pick the next pile with the maximum number of points which is the okay middle medium because there are three right there are three one will be large one will be medium one will be small so I'm just marking it as okay Al will pick the largest coins you will pick the medium number of coins and then uh the Bob will pick the last pile which is for sure he will pick the smallest one why because we have to the maximum number of coins that you can have so if he will pick the largest so it's of no logical concept that you will pick the small coin and let him pick the middle coin because you want your you greedily want your score to be maximum so you will make to choose the medium which is the medium value coins to actually get more number of coins so you'll choose a medium number of coins because large for sure Aris will take now uh repeat until there are no more piles so for sure you will see that he will also take nend coins he will also take n coins as in we will also take n coin coins and Bob will also take n coins everyone will take n coins now it is for sure that like the um like Alice will take the maximum coin Bob will take the smallest coin and we will take the middle coin we'll try to take that now um again remember this fact that we have to choose the three piles of coins now we are having an array of piles where the piles is the number of coins in the I pile so that's it now if I say you that we have these configurations and give me the maximum score so are you saying that Aran what I will do is I'll simply sort it out let's say SSS mmm L LL as you spoke uh I'll give SSS to Bob for sure llll uh will be taken by Alice so I will get this score which is actually 3 into M or basically m + m + m actually 3 into M or basically m + m + m actually 3 into M or basically m + m + m because these M can be different also it is in medium I'll say hold on for sure when you have a configuration like this the option for you was to choose three although you can see I'll choose three piles so what I can do in the beginning is I can choose this and this as three piles what will happen is I'll give the one smallest one to the Bob middle one to me and the next middle one to Alice because I choose three if it is M1 if let's say and see it is in the increasing order so it can be S1 S2 S3 M1 M2 M3 L1 L2 L3 right so for sure now we spoke that we will try to take the middle ones we have to take the like middle one to actually maximize the score but there's a catch that we can choose three piles of coins in any order whatsoever so I choose these three piles why these three because I want to give the smallest one to the Bob so he will just go away with the smallest coin now this middle one will I have to take because the next middle one is the more larger one and that will be taken by Alice itself for sure so this M2 has gone to Alice this S1 has gone to B so both have gone my score is M1 right now but you saw that Alice got M2 rather than L earlier with the thing which we have thought of now cool now the next uh which I have to choose is this S2 I'll choose M3 I'll choose L1 I'll choose what will happen with this simple again Bob will take a S2 I will take a M3 and Alex will take a l one okay cool will take a L1 now lastly I choose a S3 L2 and L2 what will happen with this is Bob will take a S3 I'll take a L2 and Alice will take a L3 so you saw I what I will do is if I have a configuration like this SSS mmm I know that all of these will be taken by Bob because these are the smallest coins piles of coins so it will be for taken by Bob now the remaining part I will just make sure I will take all alternate coins and give the alternate ones to Alice these Alice for sure Alice is taking larger than me at every point of time it's just that my coins will maximize if I take alternate because these are in the maximum order so as simple as that firstly get all of these piles of coins in the sorted order and start for I equal to n by 3 because you know that I have n like the entire size is n and I have to for sure distribute in the three equal parts which is n by3 so I'll just start off with n by3 and I'll go on in alternate terms which means I = to I + 2 alternate terms which means I = to I + 2 alternate terms which means I = to I + 2 and keep on adding the score and that will be the score of us so the complexity will be simply n log n considering we will do a sorting in the beginning it is a Time complexity and for short the space complexity will actually again be a login uh for C++ in actually again be a login uh for C++ in actually again be a login uh for C++ in Java it's login the space and for python it's actually overin so yeah that's the Sorting space uh let's quickly go and type code this up again it was pretty simple so we will have an answer uh we also need to have uh piles size so I will have uh piles um size now as you saw that we'll just simply go on to all of our elements now starting off with you know n by3 I'll go up till n here I'll just do a i + 2 because I equal I'll just do a i + 2 because I equal I'll just do a i + 2 because I equal to I uh I = to I +2 because I want to go to I uh I = to I +2 because I want to go to I uh I = to I +2 because I want to go to alternate element I simply add this in my answer say piles of this I and then ultimately I can just simply return my answer with this it should uh work answer what happened cool now with this it should work um because we are just actually using the piles uh did we miss something okay we have to sort it also so we will just simply sort uh piles. begin and piles. end and then we have just simply sorted it up so it should work now let's quickly submit this up thank for bye-bye
Maximum Number of Coins You Can Get
rearrange-words-in-a-sentence
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the maximum number of coins. * Your friend Bob will pick the last pile. * Repeat until there are no more piles of coins. Given an array of integers `piles` where `piles[i]` is the number of coins in the `ith` pile. Return the maximum number of coins that you can have. **Example 1:** **Input:** piles = \[2,4,1,2,7,8\] **Output:** 9 **Explanation:** Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with **7** coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with **2** coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, **2**, 8), (2, **4**, 7) you only get 2 + 4 = 6 coins which is not optimal. **Example 2:** **Input:** piles = \[2,4,5\] **Output:** 4 **Example 3:** **Input:** piles = \[9,8,7,6,5,1,2,3,4\] **Output:** 18 **Constraints:** * `3 <= piles.length <= 105` * `piles.length % 3 == 0` * `1 <= piles[i] <= 104`
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
String,Sorting
Medium
null
1,959
hey everybody this is larry this is me going with bi-weekly contest 58 me going with bi-weekly contest 58 me going with bi-weekly contest 58 problem three minimum total space wasted with k resizing operations hit the like button hit the subscribe button join me on discord gives me some love give me some support um but yeah and also if you came here right after the contest or something like that um join me on discord a lot of people discuss the problems right after contest so if you're into that just come out hang out with other smart people and me uh yeah anyway for today's problem or for this problem minimum total space raise the k side resizing operation so the first thing i notice about this problem is that this the number of n is 200 right so that means that we can get a little sloppy we can get um yeah we can get a little bit sloppy and do something like n squared or sorry even n cubed but i was thinking whether i can do this in n square and the way that you would think about this problem especially with k um the first thing i notice is that the first thing that i think about and i was trying to you know way often i'm going to try to like um have an idea right and then i test quote-unquote tests in and then i test quote-unquote tests in and then i test quote-unquote tests in my head whether this works and for me uh and if you struggle with this problem i recommend definitely going with easier dynamic programming problems first because dynamic programming is already hard enough as it so you should start with uh easier problems and build yourself up to it um so yeah the first thing that i tried to do was kind of think about the states and the thinking the states that have is kind of the index and k this is a very kind of reasonable state because in this problem you're doing you effectively i like to say cutting things off because when you resize an array for example if you have this thing let's just say uh you know you can think about it as cutting it off let's say we cut off here then the cost of this chunk is just the max of that right and then here we use another resizing for the future right so basically i think about this is the number of way to number of ways to partition uh the nums away uh with k cuts right okay partitions like k minus one partitions maybe yeah uh okay plus one partitions uh yeah so basically from that right we have a so you can you know this is the state and the brute force is just forcing on how long each partition goes right so this is a very straight for um really i wouldn't say standard but it's a typical thinking about okay that's what i have this is going to be a n cube right is if we have this date and we if for each day we iterate you know we iterate how many links to cut right because for example let's say we're the index is at here um and we have k is i don't know say two then okay then we're going to iterate okay let's cut let's make a cut here and then recursion on the rest we can also cut here and then make a recursion on the rest cut here oops make a recursion to the rest and so forth right so this is actually um this comes up this is very common in dynamic programming problems so it's a that's why i kind of you know jump to that to see if that works and then the question is okay given that how do we get the max of this chunk right um and not just get the max and the cost of this chunk um there are a couple ways doing it i think you can get some prefix sum to get the total of this um yeah actually now they think about i didn't do it this way but you can actually think about this as getting a prefix sum because this is actually maybe a cleaner solution but um but yeah but this is just basically you go to the max of this minus the sum of this right because okay um yeah so the max so let's say the three numbers and the max is 20 then that means that you have 20 times minus the actual sum right so that's the space usage and you can look at that as just getting the max of these three numbers which you can do with some fancy maybe some tricky math but you can also do it another way by just having a rowing sum and then here this total you can just use prefix sum um i didn't do it this way but and again prefix sum is bringing prerequisite is kind of tricky already i have a lot of videos in the past about explaining prefix some so i'm gonna skip that explanation a little bit um definitely work on you know look at the um if you want to do it this way read some prefix some problems and then kind of familiarize yourself with how to calculate a um a sum of a segment by using a prefix sum so okay so you can do it this way as well but i actually didn't do it this way um the way that i did it is okay so these are i have the same states and i have the same kind of separation but what i did is i did a rolling histogram um and actually i guess i did it with the same way with prefix sum but i expressed another way um and for me the visualization is just this rolling histogram and for that i am going to bring up a visualization so hang on so the way that i did it is by okay so you look at you know let's say there is 10 20 15 or something like that right so basically the idea with what i did with considering this as a histogram is that one at a time i go okay sorry changing colors okay so initially we go okay this is the max so we get the wastage and then the next we recalculate the max because now we're here we say okay now this is the max let's get what is the previous max right well the previous max is this difference and so we calculate the number of difference and the number of things to it um let's actually also add one more thing here so that we can see later um yeah and then he and then of course when you see the next number uh when you see the next number you just add the delta you add the difference again because this is smaller and then here now that we have a new max we just basically and here we already calculated all this delta and then here um similar to histogram we see a new max so then we just calculate by using a different color hang on so here we just calculate the difference between this height and this width right and this width is just the number of numbers and the height is the delta between the maxes and then after that you fill out the histogram uh pretend that's a square because i draw very poorly but that's basically the idea behind this problem and once you recognize that you are able to solve this in a quicker way so let me go over my solution but yeah and this is a standard dynamic programming memorization problem i use cache here but that's just basically to memorize the inputs every carefully so what this does is that for every input um it use it assumes that if every input has the same output and then therefore by that output you it saves it for next time so here i can go from zero to oops zero to n k can go from also zero to n so therefore you have n squared possible inputs each input we use an o of n loop so total time is o of n cubed time and total space is of n cubed oh sorry n square space because each input we use over one space and going over the code now i just do what i told you that i would implement so this is basically okay uh we chopped it off with only using one number so i do just to keep things in mind i do keep track of k differently my k is actually number of oh sorry um min space wasted with k um if k space is left okay um partitions left starting at index i right so basically we chop this off using one number which is num sub i and the cost is zero so that's why we have this thing you can also say plus cost but it's you know the cost is zero and here we keep track of running costs and this is as we said the histogram type solution where okay uh we keep track of the max so far if the max is greater than the number then we just add the cost because you just kind of you know because it's smaller than the thing otherwise we did this rectangular math that we talked about with respect to the histogram and then we set the new max and here then yeah um then now we just get the cost and this is very standard memorization as i said if this is awkward to you definitely you know practice on other dynamic programming problems but yeah this is just this chopping off using one of the case and this goes you know chopping off in that um and the cost is of course the running cost that we kept track of so yeah um so when i was doing this problem i actually started doing the this way but i had a confusion which took me some time was that i thought we can figure out the cost by the first element that's a very common thing but i didn't really think it through um and yeah once i realized that actually you can the cost can be from early element um i actually work backwards to calculate this histogram thing um to figure out uh the cost as we go i um so one more a couple of more statements here is that one this is a ridiculously hard problem especially for an interview um because you have some you have to put together like two or three things both of which are kind of an intermediate maybe even by itself hard um i would say that to be honest uh in the past even without this histogram thing maybe this was a hard problem um but you know things have gotten harder so i don't know why they said this as a medium is this a heart no i don't know they put it as a medium so i don't know it's a little bit awkward um the histogram math you can probably figure out with enough time but again this is combined with a dynamic programming so this is really hard for an interview i don't think i would imagine this is an interview question at least not anytime soon though maybe who knows in the future um but yeah but it is a fun farm and for competitive farm i enjoyed it is a yeah it's a cool cube problem uh that forced you to use histogram which i haven't done in a while uh i don't know if that's the exact terminology as well but that's how i visualize the problem and that's how i did this math um if you watch me solve it live next during the virtual contest you'll see me kind of do it uh come up with this but you might not you know see my visualization which is why i explained to you because i did the visualization in my head and just try to figure out how the math follows but yeah uh i already went over the complexity so that's all i have for this problem let me know what you think hit the like button hit the subscribe button join me on the discord and actually you can watch me attempt this prom live during the virtual contest next okay let's do it q3 what is that took a while didn't it 10 minutes yikes okay let's go focus larry quick refresh what is a waste okay and okay do we always resize it up how does this work okay and let's go to 200 should be just dynamic programming maybe um is that true is that two-star n-cube maybe that'll be n cube 200 cube is gonna be eight million i don't know if this is fast enough in python this should be fast enough in other languages i think so that's a little bit awkward but let's give it a try um i don't know why they just don't make it funny enough but okay fine let's see okay now this set no this is a little bit awkward actually i want to remind everyone no spoilers please hmm so i don't think this i mean i think i have to do it backwards how do i want to do it i think i'm because the thing that i'm missing is that you don't have to start with that in size for example here you started size 20. that's where i'm like a little bit off in my that's why i stopped a little bit because i am a little bit weird on it i'm trying to do that math it's a little bit weird maybe no that's fine okay now i know how to it okay so we have to figure out the cost of zero if we do it this way and then we have a max yeah let's see go to the number i okay and then now yeah i'm off by one somewhere in my case otherwise then we can do something like otherwise not using i if it's created num che then of course okay equals number j minus x times so this times the number of numbers we had minus this one right yeah which is so it's like maybe i'm off by one i have to think about this something like this maybe okay maybe not like that then hmm let's see so um because am i off by one okay oops 10 15 is that right um i don't know if this is right but this may time limited as i said because it's going to be n cube i don't even know this is right though and you know there's no expected answer so any edge cases before i go now let's give it a summation not super confident my time out okay uh q4 hey uh yeah thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this prom again you know if you came from the contest we like going through the contest right after contest so yeah contest so come join me on discord and hang out with me and other smart people i'll see you later stay good stay healthy take your mental health bye
Minimum Total Space Wasted With K Resizing Operations
minimum-path-cost-in-a-hidden-grid
You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size). The size of the array at time `t`, `sizet`, must be at least `nums[t]` because there needs to be enough space in the array to hold all the elements. The **space wasted** at time `t` is defined as `sizet - nums[t]`, and the **total** space wasted is the **sum** of the space wasted across every time `t` where `0 <= t < nums.length`. Return _the **minimum** **total space wasted** if you can resize the array at most_ `k` _times_. **Note:** The array can have **any size** at the start and does **not** count towards the number of resizing operations. **Example 1:** **Input:** nums = \[10,20\], k = 0 **Output:** 10 **Explanation:** size = \[20,20\]. We can set the initial size to be 20. The total wasted space is (20 - 10) + (20 - 20) = 10. **Example 2:** **Input:** nums = \[10,20,30\], k = 1 **Output:** 10 **Explanation:** size = \[20,20,30\]. We can set the initial size to be 20 and resize to 30 at time 2. The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10. **Example 3:** **Input:** nums = \[10,20,15,30,20\], k = 2 **Output:** 15 **Explanation:** size = \[10,20,20,30,30\]. We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3. The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 106` * `0 <= k <= nums.length - 1`
The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find the minimum cost.
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Interactive
Medium
865,1931
1,984
hi so this question is minimum difference between the highs and lows of case score so we are given in Array and a k so the case uh representing the one uh case student from the array so that the difference between the highest and lowers of the case score is minimized right so return the minimum right so this question is you know it should fall enough and the tricky part is what if a array is not sorted it's going to be hard you have to Traverse every single one of them and you don't know which one is greater than the other because the rate is not solid so the best way is why you sort of array so when you sort a load rate it's going to be 1479 and I know the smaller is going to be the left index and the largest value is going to be on right Index right then I can try reverse right so I'm going to Traverse based on the K right because um if I have the if that if I have a small window which is going to be a case size window I know my left Mouse is going to be the smallest my rightmost is going to be largest and just imagine like this array is like 10 000 right it's like 10 000 value and your K is like what 10 right you definitely need to know these two value only right you don't care about the middle but when you Traverse on the next iteration you need to uh you need to use this value with your you know the current window largest value right so this is how it is right you want to make sure um you want to make sure uh the turn window for the size of K Windows the largest one minus the Min uh the smallest one is a solution so again the k equal to 2 right so this is the size of two right four minus one is actually three right another one this one four minus seven okay you know three and this is what the size of two nine minus seven is going to be two so the answer is two all right so you well we know this idea right you can stop coding so what you have to do is well you just saw the array for the nums and also you need a return value it's gonna be what I'm making the value for the largest you know I'm going to just keep mean minimum for the you know traversal so I'm going to starting from what so it's not starting from K because case uh the starting value is starting from one right and then a race is based on uh index zero so you have to say k minus one I listen number lens and I plus right and then the result is going to be messed up mean right we take the mint for the turn result as well as the numbers I minus num say I minus K plus one so if you just put a k minus up K minus one inside here you add you will add up what to zero right because I starting from zero right so um I mean this uh this is a map you know the case to the part inside the window okay um so let me just run it and submit so the timing space are pretty straightforward this is what this is a time this is also a Time time for the Sorting is unlocking and represent the end of the nums array and then space is constant right you don't need to allocate any space and this is all of info time so this is pretty much a solution so let me see all right so let's just run the test k for this one hopefully you get the idea and all right cool so just keep looking on the left window and pause any second foreign yes the yes I'll put you three right and uh what you have to do is what um just leave a comment if you have any question actually I wanted to k equal to two this is more doable for you to think about this all right I didn't you know uh I didn't pause my return value but the place is one right so whatever and if you still have a question just leave a comment below and subscribe if you want it but the idea is like using the size of window K to find out the minimum value you have right just the leftmost uh sorry rightmost minus left most it's actually your uh return value which is a minimum but just depending on your traversal and this will be the solution so if you still have questions leave a comment below subscribe if you want it alright peace out bye
Minimum Difference Between Highest and Lowest of K Scores
maximum-distance-between-a-pair-of-values
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **minimum** possible difference_. **Example 1:** **Input:** nums = \[90\], k = 1 **Output:** 0 **Explanation:** There is one way to pick score(s) of one student: - \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0. The minimum possible difference is 0. **Example 2:** **Input:** nums = \[9,4,1,7\], k = 2 **Output:** 2 **Explanation:** There are six ways to pick score(s) of two students: - \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5. - \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8. - \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2. - \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3. - \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3. - \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6. The minimum possible difference is 2. **Constraints:** * `1 <= k <= nums.length <= 1000` * `0 <= nums[i] <= 105`
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]
Array,Two Pointers,Binary Search,Greedy
Medium
2199
1,958
so hello everyone in this youtube video that i'm going to show uh in which i'm going to show you how the method that i proposed to solve this problem which is entitled check if move is legal uh it's a ledge code problem that's a that was on the 1858 uh by bi-weekly by wikileaks by bi-weekly by wikileaks by bi-weekly by wikileaks uh contest so the interesting thing about this problem is that he is in fact how i tried me specifically to resolve it i found it really interesting because my method is really very close to reach false i try to it's not like bridge force but in which i try to implement everything separately i try to make three problems and for you after only the code i put it i would put the link of the this code in the description uh the code is in a great github repository that you will found the link in the description below so let's just continue about with this problem so the first thing we're going to try to and to do is to understand the problem so the problem start like this you are given a 0 and exit eight by eight grid board so we are given a board like this board is uh this board contains cells that are determined by r and c row and column uh presented by poland free cells we have type we have three different types of cells the first one is free cell which is represented by a dot and w for white cell and b for black cells so what we are trying to do in this algorithm or in this problem is to find uh or to check if a move is legal or not a move can be legal in case we have a sequence like this the color of the we are trying first we in the in this algorithm we are giving first the row and this and the column this means we are given a free cell this we are try and the color to color that freestyle we are going to change the dot with the color either white w or black b so uh given the fact that we are always closing a free cell we need to check if the move is legal the move can be legal only if there is at least three or more at least three cells or more cells that are that started taking in consideration the first cell which is the free one that we are going to color uh taking in consolidation that's one and another one in which is which goes the same color and in between them we have the different colors this is me basically something like this black white black or black white black at least that means black and only white and then black that's how we go into that's how we can tell if a move is legal so let's just see though these examples now to understand uh what good line the move is legal that's mean that we have a good line is it means that it can be like this black white we have a good line with the black and the points and then good line with the whites and points white black and white this has no good lines because we don't have a sequence of two different colors it's a sequence of yeah of two different colors basically here we have diagonally we can go also diagonally uh obviously and vertically we have like these two examples good line of good lines uh starting with two whites and points and here with two black and points so this is an example that we are given if we try to draw this example we're going to have this part so we are with this example in this example we should have as output true meaning that the move is legal because we have two options um that's been said now we are going to check the algorithm that i create that i created so i'm going to go directly to the code and here we go i called the class littlemove.java the file sorry the file and the class is named littlemove so here the code that i or the solution that i made is composed of three methods the main method or the method that we are the important that we should which we are on in this call is check move the other method is check move one direction the other one is rotate matrix so the idea of my algorithm is that every single the idea of this algorithm is we're gonna check uh only move in one direction this means basically something like this we are going to check if the move is liquid on this direction only and then on this only direction and then on this on reduction this is me this means basically this we are going to check the move on each direction separately we have eight direction this one and the others okay um so to do so i created this method where named rotate matrix uh in that for these parameters will give us or will tell us if would give will give us a blanket less composed of the characters that we are going to have in a certain place this means basically that if we take this the method okay let me do this so that's the method takes as arguments be the board and see the coordinates of the cell the empty cell and the round the number that tell us in which direction we are going to take i give it i give this number that till the round that tells us which direction basically if i give zero it's this direction one for this in the next one two for this one three for this direction and four for the same direction etcetera so basically if i give it zero it will give me this direction it will give me a dot white w and black this is the output of this method if for those for these arguments how this method exactly works let us check so the first thing that i did is i created the linked list in java this is in this linked list is firstly empty then i use the this switch and then for number for an option between 0 1 2 3 4 5 6 and 7 i can say i can give back another boost so the first thing that i did is that i created this is basically just like saying for e for in e this thing here in stream doctrine c to eight for each this basically is just like creating something like this for okay it's yes this is it this is for g equals zero uh no equals c b is eight this is basically the ex this loop for here do the same as this one as this code i use it instead of this one and in stream because i found it's faster it gives me a faster time so this is just an optimization of the code and you should learn the stream api for java 8 it's been for a long period and it's way it's very helpful in competitive programming especially if you are working or familiar with java i know that many people are familiar with c plus and some people are familiar with python but i prefer to work with java it gives me too many options and also which gave me a very good runtime so this is it i use this one i created stream of integers this stream basically start from 6 from c the value of c to 8 and for each value of this stream what i'm going to do is to add to this linked list i will add the b the value that is in the coordinate b r i so this is how it works so let me explain for this example uh look at this how this code works we started by c the value the first value of i is c so if we take in consideration that this is c i know this sorry this is the column c which has the value c so we are here in this column in some place in here and uh the thing that we are going to do is that we are going to link less the value of in the board which has this coordinate r and i so we are always in r is fixed value so we are here if we take a consideration that we are in here and we are starting from this column let's mean that we will start from this point and we are going to add to the linked list this value then i going to increment by one and so we are going to the next cell which is this one we are going to add the value of this one which is w y stands for white then this one and we are going to end by this one exactly by this one and i'm going to do the same for this one but this time for the other direction how this works exactly how i pick the seven minus r instead of c let me show you and no i'm sorry it's not in this direction it's in this direction as you can see i is going to increment started from the value 7 minus r so we are going to give to i the value the first value is 7 minus r so here we're going to have 7 minus seven plus r so seven minus seven plus r gives us the value of r if we incremented r by one we are going to have i by one i'm sorry we are going to have seven minus one plus r which gives us r minus one which is this line over here uh to be more specific this cell over here and this is how the argument the algorithm works and we are going to go lastly like this one then this one and this one it works basically the same for all the directions so we have here let me draw this so that i help you to understand rest of the algorithm and here it is so we are if we are going to this direction we have here r plus 1 and here 8 minus c here what i'm trying to explain is what if we go to this direction and it stands exactly for the choice of 4 r plus 1 and 8 minus c i'm going to explain from where i get these values so that you can understand basically how the algorithm works and you can be maybe based on this on my idea you can think of your own algorithm and solve this problem in your own method and this is the best thing that you can do if you face the problem in any algorithm and it's not a bad thing to learn from what other people's solution but the best thing is that you can learn from other people's solution and then try to make your own solution try to think in a better way believe me there is some contribution that you can make to any solution is some change i don't care how small it is but you can do it and that's how we learn so trust yourself uh we uh let me explain how this works basically for me here the range in this case starts from zero to math mean r plus one eight minus c so let's just go and open this one like this and this one here so that you can see better so we are starting from zero i are going in this direction so to do so every single time we are going into in this direction here we are doing the same operation on rows and on cells uh and on columns the thing that we are doing is that we adding one to the coordinates for uh for cell four columns but for verbs we are subtracting one that means we are here if we have for example here we are in the line five we are going here to line four however we are going to this column uh if we were also here in the column five we are going to the column here six so minus one plus one minus one plus uh sorry i did it wrong so i mean here is minus one plus one you can see it now we are going like this minus one plus one and this is how basically we can do it why i picked the mean because we have don't forget this board is square so no matter which place you are taking you when you start from for example from this point you have end up here in the mean of the distance that you are given here or here you are going exactly to be more clear if you are going up you are going exactly in one two three four five times four you are going to exactly four sales up and here we are going one two three four cells all right so the thing that's going to happen if you pick this place for example you are going to go three two and two if you pick it for example this place you are going one and that's six you are not going here up six you are going just one you can see it you are going just one cent so every single time just try it and you will understand it by yourself that you are going by the minimum you know the minimum distance is the only is the distance given so this is basically the thing that i did i started from zero till the mean of the given distance is started from r plus one to if we are going for the rows and eight minus c for the cells for the column sorry and the thing that i'm going to do here is that um each time i go up i the number for or the yes the index of the row gets uh gets less lesser by one and gets higher or it's grows by one for the columns goes by one and the rose shrinks by one you can see this so this is basically the idea of the argument so that you can go into this direction and you can go into any direction now taking in consideration that you have every linked list for any direction that you want the thing that the next thing that you are going to do is to check if the move is legal for each direction so that's what i do so if we have a linked list that has a size less than three or inferior than three this means that we there is no possibility to have a sequence in which we have two colors and one co two colors uh this means three i want to say three colors white for example black white and black white or black so we need to have at least three the size of liquid list should be at least three and else well the first thing that we are going to do is to remove the first value in the linked list is the dot is this one the dot so we are going to remove it we don't need it anymore next uh we are going to iterate over this linked list that we got and then for we are going to check if the value that we got equals dot this means that we find a blank or free place here this means that it's entirely pos impossible for us to have a sequence of fold of the same color and then the different color we shouldn't have a free cell so immediately we are going to return false this is what the this is the algorithm how the algorithm works and then uh oh this is what we are asking to do in this exercise and then if we get the same color as the one that we picked here this means in this case we found the one we picked here is black if we found black that means that it's true if we find the right color it that means we are going to return true and that and thus we are going to return finally the correct value which is true uh and we are going to say that this move is legal otherwise we are going to return just false because we only in we only we didn't found a blank cell and we didn't found for the entire line we didn't found uh the same color as we have this means that we found something like this black white and white we didn't find the black again so finally we are going to return false because this is not a legal move so this is in general how we are going to check for the move for one direction and you can guess it already that to check the move for all direction it's basically so easy because what we are going to try to find is for one time at least for one direction the move is legal this is what we were asking in the algorithm so we are going to do or are using or here uh the logic operator off so that we're gonna check for any direction so this is the first one second direction third direction this is how the algorithm works and to see basically that the algorithm works i'm going to use here a set of tool that helps me too much with uh with competitive programming which is uh the debugging tool for nvs coder uh this the testing and debugging tool in the escort so basically this is uh the code that i'm going to run is this one is some is a simple set of units of some this unit is that i made check just check move for the this exact the first word example another example third and fourth and so on we have eight examples so that we cannot check the algo we can fully check the algorithm so this is it and uh the thing that i'm going to do is to i'm going to use some breakpoints in every i think that i'm going to use only breakpoints here for one case just this one so let's go and run the tests uh i think i'm going to run only the first one uh i'm going oh i want it i want you to debug it so that i show you what's up this algorithm so debug test all right and here we go the algorithm stops in this break point so the thing that i'm going to do is that i'm going to go into this check one check move one direction method to see how it works but before i'm going to go to the rotate matrix method and we are going to see exactly how this method works so uh we have here we created the linked list which for which has the size zero there's nothing it's an empty linked list we're taking this board which has these values as you can see we don't need to see them they are here it's just an example so uh the other thing is that we are given the four and the cell three so and around zero we are here in round zero in case of around seven because that's the prick point in which we stopped in case of round is zero so the thing that's going to happen is that we're unsure this case uh after this line the thing that's going to happen is this as you can see we quickly uh filled the linked list we are going to see the values that we have here in this linked list we have the first value dot then w and v let us check here this example uh i'm going to change the chords somehow so that we it will be so easy to read it for us okay and perfect so we are here in line basically as you can see this is the matrix that we have all the board we are given we are here in row 4 cell column 3 sorry we are here exactly in this point and we start from this direction and we are taking dot then w and then finally b now this is our linked list the linked list that we are going to work on we return this link list then we are going to see what's going in to the other method of the second which is check move one direction let us go into this method here we are in this method we i have here the linked list the previous one we have four and three the coordinates of uh of this point the given point and the color which is black b so we are going to check if the size of the linked list is inferior than three and basically the size of this linked list is five you see size equals five so it wants to return false at this point next is we are going directly to else we are hearing less the first thing that we are going to do is to remove we are we're giving this link less the thing that we are going to do is to remove the first uh the first letter in this negative list which is dot now the size of links of the linked list is four and we lost the first dot and everything moves easily that's why you may ask me why i picked this type linked lists for this algorithm and this is another the thing that for which i like that is that it offers many types and many methods and it's basically my own choice my preferred choice of programming languages in competitive programming i'm not just saying you for you to work with java or anything else i'm not sponsored by oracle or something no i'm saying that i prefer to work with collection it is easy for me i have a long experience with this so i like it uh now that we remove it the first we can do this in ca of c plus easily i know it's not something special but here for me we will move with the first uh the first letter which was dot now everything moves smoothly and immediately the w took to zero as index so we are going to move now to the next line in which we stopped which is this one uh in this line what i'm doing is i'm taking i'm defining a char variable or character named wave color this wave color here this expression returns the opposite color this means that we are going to check if color equals white then we turn black if colors equals is different than white then returns white this means that red color will take the opposite color than the color so as you can see here we have red color as w white color is b black so we are going to continue here we are going to check if the first uh the first letter or character in the blanket list is the opposite of white which means the opposite of red color of roof column which means it equals left corner in this case the thing that's going to happen is that we can continue to do checks otherwise we don't need to check anything because if we didn't find immediately a different scholar than the one given this means that this is not a legal move to give you a clear idea why this is not a legal move you need only to go back to these two examples and especially or precisely to this one this is not a good line because we have white we need something like white and then black immediately and that's why we do this fails this condition now we are going to remove first again because this check is success in our case here as you can see take a look at this one it will go as you can see we deleted the first uh the first line which means that we only have now white and black we in the next thing that we're going to do is here in this for loop now as i said before we're going to check do check these conditions if these are valid we have v equals w this means that we are not going to enter here and return false we are going to check if v equals w and color v equals w and we're going to check sorry if v equals color v equals w while color equals black so i'm not going to return true we are going to the top of the linked list each of the four booklet we are going now to check in the second case here for v equals we are going we are here for v equals w and we are going to continue the same thing will go will happen and now we have v equals black b as you can see here v equals black so we are going to check this conditions this concentration it went successfully so or will go successfully so we're going to return two now the first test result zero if i go like this returns true as you can see so everything basically next will go as i showed in this example i'm going to get this true false and then as you can see we have true false and false it's exact same example here this is the example that i earned we have uh true then false and then we have false and false this is what we did here the final result is going to be true so finally the test will succeed as you can see the tech the test is succeeded so we got here this grain check means that the test is succeeded and algorithms is works finely so this is it for this video i hope you liked this algorithm or the way i explained this algorithm if you have any remarks for me or in the middle that i used to explain if you have any remarks for me or you want to tell me something please feel free to write down in the comments below i will be happy to answer all of you and thank you for your support but before we close up this video i'm going to submit this code to check if it works and to check how much time it takes so it takes six milliseconds it's not that much fast uh when i when submitted in the contest it took way too much time but the memory usage is slightly better than 60 percent of java submissions so
Check if Move is Legal
ad-free-sessions
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`. Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only **legal** if, after changing it, the cell becomes the **endpoint of a good line** (horizontal, vertical, or diagonal). A **good line** is a line of **three or more cells (including the endpoints)** where the endpoints of the line are **one color**, and the remaining cells in the middle are the **opposite color** (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers `rMove` and `cMove` and a character `color` representing the color you are playing as (white or black), return `true` _if changing cell_ `(rMove, cMove)` _to color_ `color` _is a **legal** move, or_ `false` _if it is not legal_. **Example 1:** **Input:** board = \[\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ "W ", "B ", "B ", ". ", "W ", "W ", "W ", "B "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\]\], rMove = 4, cMove = 3, color = "B " **Output:** true **Explanation:** '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'. The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles. **Example 2:** **Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "B ", ". ", ". ", "W ", ". ", ". ", ". "\],\[ ". ", ". ", "W ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", "B ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", "B ", "W ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", "W ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", "B "\]\], rMove = 4, cMove = 4, color = "W " **Output:** false **Explanation:** While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint. **Constraints:** * `board.length == board[r].length == 8` * `0 <= rMove, cMove < 8` * `board[rMove][cMove] == '.'` * `color` is either `'B'` or `'W'`.
null
Database
Easy
null
1,455
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go q one check of a word occurs as a prefix of any word in the sentence so this one it's pretty straightforward I thought it was pretty straight for it so I just ended it but now but as soon as I saw it I was like okay this is just proof for us let's yeah let's check each word by itself and how are you and then that's pretty much it I look at your sentence and I look up each word and with each word I check whether the search word is the beginning or the prefix of the word which there's a functioning in Python for doing it so this is and that sounds pretty straightforward I went examples I did it so intense I was like wait that is not white so I and I just wanted to read to double check that one index is okay because sometimes it might not be and I had to beat the palm a little bit as soon as I saw the word one index I'm okay but this cost me like 10 seconds so 20 seconds check your for word occurs as a prefix of any word in the sentence so this one the hop the solution is just to boof force it because this the sentence like this at most 100 the third search word length is at most 10 so you can actually start by any character and then go and search for when they'll be okay the only tricky part about this is that you have to return to index of the word index so what I did is I used Python magic and I split the sentence with the spaces so and then and using enumerate which gets to which maps the content of a elevator with like a counter of sorts so if for each word that is in sentence if the word starts of the search word that I just returned the Iife index and the only tricky thing that cost me a couple of seconds which I guess is okay is that it's that is one indexed which I was like when I look at this time I did look at the example test cases which was a mistake that I did last week for accident and I was like okay everything's off by one then we double check that is one index and when I saw that was one index okay and then I submitted and there was a case where the word is not in it so I was like okay we gives negative one then I think I'm okay so yeah so that is q1 although a yeezy problem is an individual question I guess it could be I mean it's a it's too simple but it's good practice good warm-up definitely recommend it warm-up definitely recommend it warm-up definitely recommend it complexity it's o of where n is the sentence and M missing research word and it's all of n times M technically you can also you could also end lies in terms of number of words but when it's roughly right space I use on own extra space all of one extra space so yeah so that's q1
Check If a Word Occurs As a Prefix of Any Word in a Sentence
filter-restaurants-by-vegan-friendly-price-and-distance
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** sentence = "i love eating burger ", searchWord = "burg " **Output:** 4 **Explanation:** "burg " is prefix of "burger " which is the 4th word in the sentence. **Example 2:** **Input:** sentence = "this problem is an easy problem ", searchWord = "pro " **Output:** 2 **Explanation:** "pro " is prefix of "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index. **Example 3:** **Input:** sentence = "i am tired ", searchWord = "you " **Output:** -1 **Explanation:** "you " is not a prefix of any word in the sentence. **Constraints:** * `1 <= sentence.length <= 100` * `1 <= searchWord.length <= 10` * `sentence` consists of lowercase English letters and spaces. * `searchWord` consists of lowercase English letters.
Do the filtering and sort as said. Note that the id may not be the index in the array.
Array,Sorting
Medium
null
895
welcome to february's leco challenge today's problem the last problem of the month is maximum frequency stack finally finished another month so the question is implement frequency stack a class which simulates the operation of a stack-like the operation of a stack-like the operation of a stack-like data structure frequency stack has two functions push which pushes an integer x onto the stack easy enough and pop which removes and returns the most frequent element in the stack so if we had five ones and four twos we want to pop off the one now if there's a tie for the most frequent element then the element closest to the top of the stack basically the element that's been added the most recently is going to be removed so how are we gonna solve this well initially like if it wasn't for that tie this would be pretty simple right we can use a counter object uh keep track of what the highest frequency is and then just pop off or return the element that has the highest frequency stack and we can use like a counter object to do that but the problem is when there's a tie when there's a type we have four ones and four twos we don't know which one to return uh we need to keep track of which one was the most recent one so that becomes a little bit different so here's what we're going to have to do what i'm going to do here is create a counter object and this is just going to keep track of every element and how many times it appears so if we had 1 10 times two five times whatever uh second thing we'll need is a stack and what this stack will do we'll have a default dictionary with all the number of times something appears so let's say 10 is going to be our key and we'll have a stack of like all the ones that we added um actually they're not going to be multiple ones because each time we want to add a new one what we'll do is say hey this one becomes like 11 then this one will have 11 now and we'll add one to the stack here this way we'll keep track of each one that we added now we also need to keep track of the max frequency somewhere so as long as we each time we push we update our max frequency to be the one that's the maximum here it's going to be 11 right what we can do is just say hey pop the one with frequency 11 and whatever is in here first like maybe we add twos later maybe a three and they all have about you know count of 11 then we're gonna pop off three first and once we pop off everything off here if there's no stack left we actually will have to decrease our maximum frequency by one now our frequency is going to be 10. so hopefully that makes sense let's start to code this out uh the tricky part with this is really all these self variables so first we'll start off with a counter object and that's simple enough and now we'll have a stack i'm gonna make this a default dictionary of lists and these are technically stacks but whatever we use them we use list as stacks and we also have the max frequency which starts off at what zero right alrighty so let's first figure out how we're going to push this on here well the first thing we probably will do is get our counter object we'll input our x and we'll just add one to it so that's gonna keep track of that now we need to update our max frequency so this starts off as zero but we want to get the max between whatever max frequency as well as whatever we just inputted here because this might be greater now so we'll also put that right here and finally we want to add to our stack so we'll get our stack here we'll get our frequency that we just have which would be this self c dot x and we will append to this dx okay so now when we pop off we already have our max frequency stored right so we're going to pop off whatever element comes off first here so what i'll do is to say this is a candidate we'll get our cell stack and we'll get the max frequency here and we'll pop off whatever is most recently added so this would be candidate now one thing to note we're gonna have to decrease our counter so we'll get self dot self.c self dot self.c self dot self.c with our candidates and we'll subtract one and we'll also need to see if we need to update our max frequency so if uh let's see if self.stack uh let's see if self.stack uh let's see if self.stack at self dot max frequency is empty so if not this then we will get ourself max frequency and we'll decrease it by one because surely there's going to be one with minus one of that it could be the same number it could it might be a different number right and finally we just return our candidates okay so let's see if this works all right looks like it's working so let's submit that and accept it so this is actually an of one time complexity uh we do use extra space because of all these memories so it's going to be of n in terms of memory but when we return it you can see it's all of one right we look at our dictionary uh we pop it off that's all one operations and then we just return it so yeah this one's pretty simple um you know sometimes if you might start off with a bad approach like maybe you start off with heap or something like that those could work but they're a lot more unintuitive i think this is a way better solution so we're gonna go with this all right thanks for watching my channel and remember do not trust me i know nothing
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
89
hey everybody this is larry this is the first of july uh happy july uh if you're new to this channel hit the like button in the subscriber and join me on discord we usually solve every problem live and hopefully get the streak going this is my i don't know 12 13 i don't know 15 months straight or something like that you could it's a long streak anyway today's problem is gray code okay um okay so the key part about this one um it's just a lot of literature i think they're definitely um so great code is something that hasn't had is very well studied there's his own wikipedia article properly and kind of just go through it um i don't remember too much about this and i don't know if knowing it helps too much but the key thing to notice is just that you know you could think about the gray code in a number of ways um but you can think about it as a n-dimensional hypercube and then kind of n-dimensional hypercube and then kind of n-dimensional hypercube and then kind of think about having that graph and that graph it has a lydian cycle um and because it has an already in cycle then you just try to figure out a way to um to kind of go through all the path once right um huh maybe i mixed it up i meant hamiltonian psycho um is that true no yeah so yeah i think that hem um though i think they're different things as well but yeah there are a couple of algorithms that you can do here um and the way that i always do it is just kind of a sort of a greedy um yeah it's going to be homozygous psycho but it's a little bit sort of a greedy um which is that i start at any number and here it doesn't really matter because it really doesn't matter which number you start at i'm going to start at zero and then you just kind of find one bit at a time going to a bit that you cannot or going to um a node if you will or a number that you haven't visited before until you reached or to the end um to the end numbers so that let's get started let's play around with the idea i think that's roughly right um but again if you ask me how i know this to be answered the answer is that i think i've done similar problems before and some of this is just knowledge from the past um i so if you don't or if you're not familiar with it maybe just read up on the literature a little bit um i don't know if this is a good one to kind of prove and it's kind of a weird one for the first of july i would say on an interview um if i see this as an interview i expect quite a lot more hints or something like that or telling you how to do it because it's just very weird um because i think like if you really want to be strict about it um you probably have to prove just correct which is harder than it sounds because i don't know there's a lot of people who you know write papers on stuff like this right so i mean that's just a little bit awkward anyway so let's get started um but also the other thing to note is that n is less than 16 which is has to be small because you know they're two to the n number of outputs so yeah so we just have a thing where we set for the used and then we are also going to have current is equal to zero and maybe the answer is just an array so actually i guess we don't even need the current we just need the last element of answer so yeah so let's just go from range from one this is of course i use bit shift but that is just two to the n which is what we said earlier um this may be off by one to be honest so let's play along with it so this is the last number um and then let's just try all n bits so starting with the zero bit and then we can probably do it that way um if x and this is just the operation that uh is defined into the in the problem if this is in used or not in use then we want to use it uh um okay current is let's just say next number is equal to this thing if it is not used then we set it to used uh actually it's a set so we said to use like this and then we append it by next just a lot of typo i cannot type tonight um and that's pretty much it probably i think this should be good but let's run it real quick because um i think the thing that i worry about is just that this doesn't complete or something like that's not quite right oh i have to put zero in used okay so that's good but i don't know so this breaks up this loop and then it should go here all right so then why doesn't this happen again why doesn't this go to 3 so n is 2 so one to the two is did i mess up maybe i mixed it up what am i doing wrong so that's the core idea i have here but why am i not this on the next elevation this should be true oh i am dumb this is okay i meant this where basically this is the bit offset and we want to shift we want to xor meaning flipping by one bit so basically the idea here is that um just to go over a little bit i think i kind of jumped to the code a little bit earlier today um but what i mean why am i using an xor an x0 means that we're changing it one bit at a time and by shift by choosing which bit that we do we shift it one bit at a time what a silly mistake though my bad so yeah so that now looks good and of course that's one some small numbers because they're only 16 possible inputs so if you're on an interview or even uh competitive if you're having to get something like this uh you can probably just run it out i would even i would just want 16 later but i wouldn't just kind of i bought these because 2-16 has a lot of numbers because 2-16 has a lot of numbers because 2-16 has a lot of numbers so here we can kind of see and this is actually i don't know we i don't think oh actually we have the same output as the one that they do okay but sometimes uh in here they're not the answer's not distinct right so because there are other ways of doing it for example if you go from the nth bit first you can get from zero to like basically a easy different answer is just this backwards or something right so that's why i'm actually surprised that we actually match perfectly so then now let's just give it a 16. uh the way the reason why i choose a big number is just to see if it kind of goes too long or something like that um but and it's so no looking at the time it looks fast it looks good and actually to be honest i knew this but i just you know kind of it's a good muscle to practice and exercise as you know as you keep on doing it'll be good to you know uh do it all the time okay so now uh what is the complexity of this right well the complexity of this is that's quick on the submit one first because i keep forgetting it some days i don't know so this is accepted so that's good uh so is the complexity well here this is 2 to the n and this is o this is n or of n so together this is o of n times 2 to the n in terms of space this is going to be o of 2 to the n space because that's the size of the output though we also you know here we also um uh trade space for time um so it's also another two to the n space to save another um look up time otherwise you might have to look up this array which uh is another two to the n factor um that's all i have for this one um i think there's a this is one of those problems that if you have trouble understanding this video and i don't blame you or even solutions when you look at it on the internet and you do googling whatever and some of that is because people who know the solution already knows the some properties of gray code um and it becomes and so it's not fair right so it's not like and in that sense it makes it a kind of a crappy interview question unless the interviewer really guides you which is why i said earlier like they have to give you a lot of hints because like proving this is probably like a paper i mean maybe not anymore because it's known but like at some point in the past right might even have someone's name on it i don't know i don't actually know this thing but um but yeah so i don't really think this is like a good learning problem which is makes it really awkward for the first prime of july uh on lead code but yeah um but let me know what you think and the cool thing is that here given that i started at zero you can actually start at any number it might even be a follow-up even be a follow-up even be a follow-up um because the key thing to start at any number is just that knowing that um knowing that because this number or this sequence if you will has every number from one to two to the n or zero from two to the n minus one to be more precise and therefore you can just imagine starting at any number in the middle it's just that same sequence but transposed or something like that um and there are different ways you can go obviously um depending how you do the algorithm but you know uh it will always terminate as a result um and some of that is maybe beyond the scope of this video because i'm just even though it's already 10 minutes long i'm still trying to keep it short but yeah let me know what you think about this farm uh i usually solve this live i might mention it a little bit too late this time but so that you could see my thought process and you know and feel free to kind of fast forward or this is the end but uh but yeah i intend to do this for the rest of july so you know subscribe hang out chill join me on discord talk about this farm and other problems and yeah um that's all i have for this one that's what i have for today happy thursday have a great rest of the week fourth of july is coming up if you're american i mean fourth of july is coming up even if you're not american but you celebrated you know hope you have a great weekend i will see you soon and to good mental health bye
Gray Code
gray-code
An **n-bit gray code sequence** is a sequence of `2n` integers where: * Every integer is in the **inclusive** range `[0, 2n - 1]`, * The first integer is `0`, * An integer appears **no more than once** in the sequence, * The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and * The binary representation of the **first** and **last** integers differs by **exactly one bit**. Given an integer `n`, return _any valid **n-bit gray code sequence**_. **Example 1:** **Input:** n = 2 **Output:** \[0,1,3,2\] **Explanation:** The binary representation of \[0,1,3,2\] is \[00,01,11,10\]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit \[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit **Example 2:** **Input:** n = 1 **Output:** \[0,1\] **Constraints:** * `1 <= n <= 16`
null
Math,Backtracking,Bit Manipulation
Medium
717
1,424
Hello friends, today we will watch the video of C Plus Medical Entrance Form, that is your left question, here first of all we have to see the matter that we have to do in the program, then you understand this matter, this is your matriculation, what we have to print in the matriculation. You have to print sexual ali, this is the first time, you have to print one, then you have to print photo again, you have to print 153, fruits and last, you have to do job, simple, you can write first, can rotate crop fitr and always understand this, logic before this, video. I have made Indian Army, what is there in it, first time one is printed, then you are printed for 357, 28th is just opposite to this, so all of you watch it so that it becomes clear to you, now we have to print here, how to print, for this it is most important. First of all, before making the program, we have to make its logic, how will we paint, so friends, if you want to visit my channel for the first time, then please subscribe the channel, like, comment, if you want help in any program, send it to Niketan. Apart from this, we can make Telegram restless. Now let's come to the program. You are seeing that the first second road and professors are 5 rupees because we are in programming, so here the counting is done from zero i.e. 024 Roy Clear. Now is done from zero i.e. 024 Roy Clear. Now is done from zero i.e. 024 Roy Clear. Now we always keep one thing in mind. Hai Ro Meerapur, how will we do this? Now friend, if we have three matrices, then we will print it for five and load it in the file. This will become logic, otherwise, what should we do to make the logic? Remove a confusion and how will we convert it into five, this is point two. If it is 4, then how will be the setting, see the simple logic of it. If it is 4323, then now Karo plus Kal Hum Janeu is three plus 3 minus one five. If it is a foreign tour, then Ro plus Kalam for foreign tour is 9717. SP logic can be calculated * - 190 * 6 - And it is clear, * - 190 * 6 - And it is clear, * - 190 * 6 - And it is clear, now what we have to print is 14275 386 and for this we have to first input and print it, so first of all we will share the function man hand free mode, so we are two dimensional. We will reduce it from Twenty-20. It dimensional. We will reduce it from Twenty-20. It dimensional. We will reduce it from Twenty-20. It is definitely a pen. Hmm, we will input it from war, so see it as Twenty-20. input it from war, so see it as Twenty-20. input it from war, so see it as Twenty-20. Whatever you will roll it, we will make one more video for it and we will give it follow simple see out message setting. I got the user input every now and then in the phone number off and we store it in the scene function and then give a sea salt message on it, I store the number off problem Anupam and then I got the movie like Jyoti 66 inter. That cat research 13 images that stones give line or not, will take to-do that stones give line or not, will take to-do that stones give line or not, will take to-do list and will put loop for i 120 ireland M5 plus find out this for check paltu 0 plus this is done for pen now we stop pen ISRO's this Enter in the step, we have to know it first of all and it will always create logic, so for this, what we will do is simple, Siyavat enter hua and tell us that the elements are in these, let's make a pocket clip and I, this is yours, shift to stop. Let's hold and create a new pocket. This should be your work. We need a simple person function. We store it. Biography of the person who comes here. This matrix has become the main input. When the matrix is ​​input, we have to print it. So we are When the matrix is ​​input, we have to print it. So we are When the matrix is ​​input, we have to print it. So we are anxious to print it. Aahat mat inch main India jo content ko my next9news for it 's quantity roy electronic shop the 's quantity roy electronic shop the 's quantity roy electronic shop the hide personal it stopped when from a moment z10 plus it became for the pen Siwat we have to print so come yes ji ko print Will do and put a space along with it that as soon as this throw is printed then next time trains will run with my favorite Players from used to run that Britain second's feminine gender 123 45678910 Elva Edison We copy this location person from After copying hua hai, I paste it here, hua hai, make it a playlist, I make it a little thicker, yes, now let's clean up what we have to print, so first let us print one. After that we print 2 proteins, then we remove it and then we have done a horse. Raghu Dixit has to be printed together, so we print 357 together, then we remove the thing from here and make one set as one. If you want to print together then 68th is doing it together, it has happened, now we have to make logic here, then see the logic, what will be the logic in it, first this is your zero gone, it is only in programming, the program always works from zero, so it should be zero. My mind is gone, this has become your two, this has become three and this has become four, it has happened that Pragya, now look here at 151, see the face of the pen every day, first stopped, what is this, my zero plus zero or it must be zero or No, it is equal, you see 0r here also the cheap rate is considered to be four to two, what we see here is location one and if we take out this sa, then 101 top 101 is the same, where is 753, but if we take the location, then we will get 0201 1202 286. If you see, every woman will come here also, Noida is for, here also there is for, so in this way, I got the logic of the location, for this, what do we have to do, we will put a loop, it will do zero to four, it will do as much Romera as it is best to print and this This loop of yours is done with I and this will be your J and K A Yo Honey G Plus sowing So print it otherwise don't do it We put more loops on the program in the flour Oil 120 Ireland Aims A Height Plus Point This We There will be no am plus and minus one hoga jitni number aur hoga toh number off karo close kam dikhte the for j12 nyaro li hoga z plus and quality things 10th a famed it like this a simple now what we have to do is to apply logic This hi sorry z plus k is equal to two if oil hota time simple what should I do you print siyavat egg j and k here print the horoscope of g and ki simple now strong we print this we print the g key and see after that you It will be understood that you print it and make it dark in which, sorry, put space here, the numbers like yours, let us put them in these lines in the printed piece and the one that will follow, do this, if my print is done then the second one is next Rohit Kinjal that now this Point Ko Hello Jyoti is free hands free through 1234 economic and these are yes now what is the problem here is your first toe print wife it's footprint is done or not, here we are seeing the logic which is the plane which is from top to bottom or No to 4 have been printed, 356 have been printed, 8578 have been printed, these were what we have to print, weight from bottom to top, 942 have been printed, 753 have to be printed, this is six, we have to print them, simple logic for this will be, first we will capture the order and later Print with pen like we do in transport, for this you simply change it here, pen is another thing to play and it is done. Now run it to increase the value in A, 2348 09 is printed, like this point form. You can print that Bhojpur 123 45678910 11123 1558 16.24 This that Bhojpur 123 45678910 11123 1558 16.24 This that Bhojpur 123 45678910 11123 1558 16.24 This simple logic should not be much of a problem for you What is the location of the difficult task We can see that both are the same First time is taken out How many rows will be printed So zero will be printed Your printing will be done accordingly. According to the look, we will work out the row and column and calculate below. If equal to print, otherwise no print. The video of the playlist system of Saheb Bhagwan Troublesome, you are the exam question, we will list it. You can do more for this, I will request that first you will make a video of your Life Lal's Birha, watch it is related to this, then you will understand the process of making these two videos. Travel Subscribe. There will be one more video of mine after these two videos. You will definitely see it, you will feel different in it. Hello friends please subscribe my channel short video.
Diagonal Traverse II
maximum-candies-you-can-get-from-boxes
Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_. **Example 1:** **Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,4,2,7,5,3,8,6,9\] **Example 2:** **Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\] **Output:** \[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16\] **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i].length <= 105` * `1 <= sum(nums[i].length) <= 105` * `1 <= nums[i][j] <= 105`
Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys.
Array,Breadth-First Search
Hard
null
1,345
hello guys welcome to deep codes and in today's video we will discuss record question 1345 that says Jump game four so here in this video I will discuss multiple approaches to solve this question I will discuss some of the flaws that are present in one or two approaches and I will tell you why one specific approach can solve this equation efficiently so yeah make sure you watch this video till the end so that all your doubts get cleared so in this question you are given one array of integers and you are initially positioned at first index so yeah your initial position is this and your goal is to reach to the last index in minimum number of steps so return the minimum and we need to return the minimum number of steps to reach the last index okay now for each index you have three conditions or slot conditions you have three options to choose so the first option is either you move towards the right neighbor that is I plus 1 index or you move towards the left neighbor that is I minus 1 index or to select any index J where the value of Adder of J is equal to the value of current index okay got it so you here we have three choices from each of the indexes so if you take a look at this example so or I will let me explain you here so yeah this is uh your initial index this is initial and this is your goal okay good now you have to say choices as I told you can either move to I plus one that is a neighbor on the right either you can move to I minus 1 that is the neighbor on the left or you can take a j whose area of I equals to array of G you can select some your index J whose values same as the current index okay now let's say here you are from here you move towards the right okay this point minus 23 so for minus 23 you move towards this minus 23 then you move towards so four zero four and you move to Europe so in this case uh at by taking four steps you move towards the uh the goal okay now is there any better approach to solve this so let's try to take a thing of another approach see from this hundred you can also go to this hundred right values are same so you can go here from this hundred you can go move towards its left that is four zero four right we can move towards the left neighbor and from this four zero four what we can go to this last four zero four right because the values are same so in this way you can reach their goal State or the gold index in three steps right so this better efficient more efficient approach correct so yeah this is how by taking or by traversing in different approaches we will find our answer okay so yeah if you remove from 0 to index 4 then take a step back and move to the left index of the four that is index three and then you directly jump to index nine from this 404 to last one four zero four okay so this is how in three steps you can reach to the goals index now in the second example the first index and the last index is the one in the same so you don't have to make any jumps in the third example the first index value in the last index value is same so according to our third type of approach that is when the values are same then we can directly jump so yeah we directly make a change from the zeroth index to this last index and yeah we reach the destination index in Punjab so we written one as our answer so uh one thing that I would like to talk about is let's say you are here and you want to jump to this hundred okay let's say it means 100 at index I you want to jump to another 100 index say or 400 at some index uh I you want to uh not 400 404 you want to jump to any other four zero for at index J so for that if you want to make such jumps you need to know the value of the next index so you need to something like hashmap where you will store the indexes at which this number is present so you will store indices like uh so if let me give the give number two three four five six seven eight nine so what you will have to show 400 you will have to store like zero and four for four zero four you have to store something like three and nine so that when you are at ith where I equal to 3 and you have to check whether 4 0 is 4 is present towards uh the right in any places then yeah you can check that yeah so if you have something like hashmap and you will store this value and index is then you will directly jump for this third condition or third type of jump you can make simple as it is so yeah we will use hashmap to store this thing this is simple now talking about approach to solve this complete question is say since you have choices like either to go towards the right or left or make some jump like this then based on this uh choices you can make a choice diagram and based on the choice diagram you can write a recursive code an efficient solution and uh will it be efficient solution so to answer that question let's look at the addend length so here the error length is 5 into 10 to the power 4 and the recursive solution will be of big of n square if you optimize it then also the maximum after optimize time complexity you can achieve here is because n Square so that is higher than uh 10 to the power 9 because n is what 5 into 10 to the power 4 so N squared is greater than 10 to the power 9 so it will definitely give you t l e that is time limit exceeded so if you write recurs the solution or recursive plus memorization solution or if you try to do DFS approach then also all this will give you time limit exceeded okay uh and also to just show you let me also show you the recursive code how we can uh write recursive solution for this so initially I took one visited to Mark the node as visited then I store all the indices for the values in the map hmm as I have told you it is uh keys are of it and values are a factor of it because a number can be repeated multiple indices so we have to store all the indices so I took Vector of int and yeah I call this recursive function so in this recursive function these are some of the base conditions that if it is out of bound or if the array I means the node is visited or if it is the node then returns 0 and in the else we are written X in maximum value so maximum value okay now we took we are taking uh three steps like means one step towards the right neighbor one step towards the left neighbor and one to another uh J whose values same right so for this we are traversing with the help of map this map the node the current node is visited but we have again have to mark it as false because we need efficient solution we need minimum number of steps so let's say in a first recursive trial you've got uh something like uh you reach the destination but in more steps so in order to find the minimum number of steps you have to unmark it again and do backtrack so this is a backtracking step where we unmark it so like so if you don't um unmark it and try to run the solution then you are you will get a roll answer see here this is because it yeah we reached to the gold state from the starting state which is to go straight but in fourth step now if you want to find efficient solution then you may need to backtrack and that's why we have to unmark this again so if you unmark this then the code will work but at the end you will get time limit exceeded see code will work if you do a backtrack but uh at the end as you can see that it will give time limit executed so that's simple as it is so yeah we need to find some better approach to this okay see the from for each current state there are some different states possible that is the right most that is the right neighbor left neighbor and assumption So based on this state can we draw something like this uh tree see initially we are at here from this node we can Traverse either to this right this index or to this index correct so for this we can Traverse to either it's left or to right so yeah as you can see that we have this state diagram or you can say a tree type structure you can take because we have some a sub starting node the starting node is fixed so we can take this as a root okay and we can try to generate different states possible simple as it is now uh to find the bear to find the shortest part in a tree what is the best approach based approaches better for such shortage path algorithm is by doing better process okay this is simple as it is so if you have no shortage path in a tree from a source note to a destination node we can do that using BFS simple as it is our source part is this destination node is this and we associ we just need two Traverse so yeah initially in BFS as we know that we use Q data structure so initially our Cube will store this is initial position now in one jump after while making one jump we have these two choices so we will store these two modes in our queue right now in the second jump we can either move to this or this so we will all store all this while taking second jump now in the third jump we will store all these three possible State now as you can see when we took the third jump and reach here so we this is the growth State as you can see so whenever we find our goal State views simply stop and we want the towers ahead so that is the beauty of prep for such approach that uh at each we are traveling level by level and whenever we find our gold node we store see if you would be doing DFS then you might have reach up till here then here so in BFS that there it might be possible that you Traverse all unnecessary nodes but in B that is in depth or such but in breadth first search you only Traverse the nodes that are necessary and yeah you will get best or possible answer in minimum number of iteration and that's why we will choose bfsu prep for such see this is what this is simply label order towers that I have shown now the coding for this question is pretty much simple it is so here we took this as a base condition if there are less than one element less than equal to one uh element in this order then we simply written zero no jumps has to be taken then we took this another map of int and Vector of n to store all the indices this is what we did and then we took uh queue and on step variable so we initially push this zero that is the index 0. so here in this queue we are pushing the index okay we will push the index so we push the index uh the starting index or the index 0 into this queue and we mark it as visited now at each time we are doing label order traversal so we will Traverse all the nodes that are that can be traversed up at a current level see this is y c so let's say we are at level one so here at this point we have two index that is one and index four so from this we can travel to index three two three and five so that's why uh we are doing this like we are taking all the current elements from the size that is through the size of the queue and we are making label order traverser for each of this we're traversing all the possible neighboring elements okay from the current index or the current node so this is the base condition that if we reach to the and or the destination called we will simply written the steps and yeah this is the first choice that we have that is either moving towards the right neighbor and we push it to the queue left neighbor push it to the queue if it is not visited we all also do need to check this and this is the case where uh we are trying to find another uh node with the same value okay and we try to push that to the queue and one thing to note here is uh we are making the clear so let's say here in this case uh 400 we had we have travels to all the different hundreds right we are stored we will store all this uh all the other index of 100 also in this queue so then there is no need okay because all the 100 let's say for the value 100 all the index is where the 100 is present we are already stored in the queue so then there is no need so just to reduce the number of iterational number of calls we are simply making it clear okay and at the end after this complete level of the traversal what we are doing we are simply incrementing the steps and if it is not possible to reach via simulator minus one so coding part here is simple if you have understood the logic it is simple BFS approach I'm not talking about the time and space complexity the time complexity here would be P go of n and the space complexity is also between big offend and the space complexity is also big off and since we are using this queue as well as map here so this is the time space complexity for this approach so yeah that's all for this video make sure to like this video And subscribe to our Channel thank you
Jump Game IV
perform-string-shifts
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the **last index** of the array. Notice that you can not jump outside of the array at any time. **Example 1:** **Input:** arr = \[100,-23,-23,404,100,23,23,23,3,404\] **Output:** 3 **Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. **Example 2:** **Input:** arr = \[7\] **Output:** 0 **Explanation:** Start index is the last index. You do not need to jump. **Example 3:** **Input:** arr = \[7,6,9,6,9,6,9,7\] **Output:** 1 **Explanation:** You can jump directly from index 0 to index 7 which is last index of the array. **Constraints:** * `1 <= arr.length <= 5 * 104` * `-108 <= arr[i] <= 108`
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
Array,Math,String
Easy
null
109
hello friends in this video we will see how to uh convert a sorted linked list to a balanced mind research tree so balance binary search tree is a binary search tree so it maintains the search property and also the difference between the depth of left and right subtrees so if there is a node here and we have a sub tree here and the maximum depth here is let's say 5 then in this part it cannot be more than 6 or less than 4 so difference can be at max 1 and this would be true for all the nodes that is for all the nodes you look at left and right subtrees and the difference will not be more than plus minus one so for example we have this sorted list one two three four five and if we convert to a balanced binary search tree it will be something like this so if you see the what is the depth of left subtree of root note 3 then it's 2 right side also it's 2 so for 3 it's valid for 2 left subtree has a depth of 1 right subtree is nil so it has a depth of 0 so difference is 1 so again the property is valid as 2 similarly you can see that it's valid so at all the 5 nodes it's valid at five also it's one and zero so difference is one at one both are zero so difference is zero similarly here so this is a balanced binary search tree now let's see how we can convert what is the algorithm here so when we are given a list we have a bunch of values let's take a generic case we have let's say n number of values given to us in a form of linked list this is not a array so you have to iterate one at a time so we have many elements and these are sorted and you see that when we uh do the inorder traversal of a binary search tree we get a sorted list so this is already sorted so you can think of it as the inorder traversal of the resulting binary search tree which we are trying to build but this is not a simple binary history it's balanced so left sub tree all the nodes of left sub tree followed by the root node followed by all the nodes of right subtree so this will be the order so root will lie somewhere in the middle so if it's odd it will be exactly in the middle if it's even it will be one of these you can pick one of these so the algorithm is that we find the middle of the list so at this point we only know about that the middle node should be root so we make this as the root and then we have this remaining elements in the left sub tree so all the l will come here then root will come here then all the nodes of right will come here in this list so now you see that is naturally recursion is coming here we are breaking the problem into smaller problem earlier we had a bigger list which was l plus r 1 now mid we have extracted as the root and then in the left part we have this list of length l in the right subtree we have this list of length r so the same function whatever function we had written to do this conversion can be applied on this part and the right part now we have a smaller problem again here we will find the middle make this root so let's take a concrete example let's take our original example 1 2 3 4 five let's say five elements next is null so uh in order to find the middle we all know uh the slow and fast pointer concept so we can have a slow and fast you can initialize in multiple ways you can keep both of them in the beginning then there will be a shift of one element so let's say slow is initialized here first is initialized here and slow moves by one step fast moves by two steps so when the fast reaches to the end or one before the end one before the tail then we stop then slow will be somewhere in the middle either exact middle or this one so let's do it so next slow will come here first will come here so first we are advancing by two steps next now again slow can come here and fast can come here at the null or you can stop here itself when the next is null you can stop then this slow is at the middle if it was odd number then we would not have moved this one then the middle was next of slow or you can have taken this also as the mid so this way we find the mid so what time it takes often if the length of list is n it takes often to find the middle so this is first step so after this step what happens we make 3 as the root and we call the same function on 1 and 2 and then we recursively call the same function on 4 and five after n steps in the next steps we will have this n by two elements here roughly i am not writing plus minus one this will not change the time complexity and then n by two roughly here so again this time the finding the root will take n by 2 times and similarly here n by 2 times so for a balanced binary search tree when this will terminate when we have single nodes itself then it will be constant time and what is the height of a balanced binary search tree its log n so each step we are taking n time so here n by 2 plus n by 2 again in similarly here n by 4 plus n by 4 again in and this length is log n so overall time will be n log n so the time complexity here is o of n log n space uh we are not explicitly using any extra space we will just uh modify this list itself so for example uh when we find the middle of the list so we have this one two three four five and it's next is null so we found out 3 as the middle we made this as the root and it's left and right so right is fine we will call this on the next of this three so it will call on four and five but uh if you look at this part if you simply call this recursive function on this head left part then this next pointer will think that so in the list we have only access to header using that we step until we reach the end so this pointer is crucial you have to disconnect it you have to make it null otherwise it will treat this whole thing as the list and it will go on again and again so this we will do in the code so space we will treat it as o 1 and time as n log n and you got the idea how we are doing it so let's write the code for this in c plus java and python and there is one mistake here so it should be 109 problem number i forgot to change it so now we will write the code so this is another example again this is sorted and we get a similar structure so let's take the base case if the head itself is null that is list is empty then nothing to return null point similarly if the next of head is null that is there is just one element again there is nothing to worry we will return just a node of a tree and the structures are different in a tree we have left right in a list we have next so return new tree node and what is the constructor it takes a value as the value of the node which will be value of this head itself so these are the base cases now let's find the middle so for that we will have list node slow equal to head and fast is equal to head next and while first next uh first next is there and fast next is there again you can do it as per your choice you can stop when the next is null itself and you can allow it to go to null also so this check may not be required depending on your use case it's up to you will need to modify the code accordingly so fast becomes so or let's write slow first so now when this loop ends slope will be at the middle or in this case we are stopping even when next is null so slow ideally should be one before middle then we have to break this chain remember this otherwise it will treat this whole list as the left part of the list then this root node mid value and root left equal to the same function on head but we have disconnected it after slow so from head till slope left part and similarly and finally we return the root so this is very intuitive i hope you understand it now let's run it hopefully there is no error here so there is error null pointer of list node line 28 uh if uh so a null pointer line 28 so fast is head next so head next is null but if head next is null so this would be head next this case so if head next seasonal we return this that is one node case now let's try it now it seems to be correct so let's submit and the solution is accepted now we will do the same thing in java not much change required here uh and the java solution is also accepted now we will do it in python 3. and the python solution is also accepted
Convert Sorted List to Binary Search Tree
convert-sorted-list-to-binary-search-tree
Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** head = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST. **Example 2:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in `head` is in the range `[0, 2 * 104]`. * `-105 <= Node.val <= 105`
null
Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Medium
108,2306
525
Hello everyone welcome to my YouTube channel in which equal number of van and like our example of zero and van is present because account of both zero and van is not van then its length we will return the maximum length now in the output which is You are the same example, you will come, just like our example is 11010, if we solve it with 4 and number of van, then we increase the count and if we get zero, we decrease then. As the count increased, you came, then zero came, then as count decreased, van came. Now we will notice one thing in this, like if we see the element between van and van, then like A is A, it becomes 10. In this, the number is from van and zero. Similarly, if we look at this is also between 11 and 10. In this also the number of van is tu and the number of zero is tu, its length becomes tu. Similarly, if we look at the a between tu and tu, let's balance it like this. So we have understood why we are increasing and decreasing which one, so let us see it once more properly We have taken the account variable in which we will be updating maxillains, is it also zero van or not map? When I checked the van, there was no van, so we put its index against the van and gave it zero. Now after that, when we checked, van plus van came, you were also not present in the map. Now if we went further, if zero came, then we decreased the account. If we give then the van has come. Now if we check the map then the count was present. If the van was present then we will update Mexico. We will update the max of Mexico. What has happened to us? If we check, it is zero 1234. Now we will Log pe hain toh aayi hamara 2 - Map of count Hamara toh aayi hamara 2 - Map of count Hamara toh aayi hamara 2 - Map of count Hamara van map of van is zero to hamara zero kama 2 ka max aaya 2 to hum log maximum updated kar diya tu se and we will not update the map of count here because If we need a back lens, then we will keep the count in the index in which we found it for the first time in the map because we need a map lens here, after that if we go ahead and come again with a van, then the count will increase, so van tu. Now you checked, if it was present in the map, then again we will update the maxi, then again it is maxi. 3 - Map of you is map of 21, 3 - Map of you is map of 21, 3 - Map of you is map of 21, so updated the maxi with you, we will see it equal to maxi, now more. If our count of van is zero in the map, then this is done. If we return it, then our output becomes four, which is our desire result 011, so if we look in this, then what should be our output? Output four should come as many numbers. Off van tu hai aur number off zero hai hamara hai kya hai hamara in the map, earlier it was -1, so we updated maxi is equal to zero, it has come, here we are checking, so 0123, so our Second induction and map of mines is in zero map, otherwise if we go through the logic for this then we will be left with only you, so if we have already put zero earn-1 in the map here then we will get already put zero earn-1 in the map here then we will get already put zero earn-1 in the map here then we will get zero earn mines. We are putting van because we have to find the maximum length and this is our zero best index finger so if we have already done zero kama mines van put then if we have zero here then now we again update the maximum. Will do maximum equal maximum and maximum i is our three so we are taking 3 - map of zero we are taking 3 - map of zero we are taking 3 - map of zero mines is one so this is 2 3 + 1 4 so this is four our maxi 2 3 + 1 4 so this is four our maxi 2 3 + 1 4 so this is four our maxi so its relevant we have understood 0 -1 because if we find the -1 because if we find the -1 because if we find the maximum length, then to find the length, we will have to count zero. If zero comes, then we will have to take the length from the very starting till the point where there is less zero, so let's do this now. When people try the code, first of all we do Namaskar . If I Plus was not there, then we would add its corresponding index in the map and if it is present in the map, then we would update Maxi . ] After doing that, we will return the maxi and what will be its time complexity. If we are running only one for look in this, then the bigo and space complexity will be on running all our tests. After that, after the final submission, our
Contiguous Array
contiguous-array
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1. **Example 2:** **Input:** nums = \[0,1,0\] **Output:** 2 **Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Hash Table,Prefix Sum
Medium
325
1,354
Hello Guys Welcome Gautam Sameer And Subscribe More Than 150 Thursdays Subscribe And subscribe The One Office Meeting Changes Electronic Meeting Changes Electronic Meeting Changes Electronic That Let's Understand What Problem With About How They Can Solve Staff Band Security Subscribe All Will Not Find The Total Subscribe From Do Lakh Sexual Addiction subscribe And subscribe The Amazing Valve Veer Loot Next Apni Is Particular Sequence Silver 1357 Veer Subscribe Amazon Subscribe to this channel for incomplete please subscribe this channel Increasing in the middle of the wave The Great Attention and Doraemon One Sequence That Converting the Gruesome Acts Will Define Do Subscribe 3525 Thursday Subscribe Vinod subscribe Video plz subscribe Channel Enter the Element Subscribe Thursday on Medium Ki Anna On Driver Letting Value Video not Will Be Nothing But Avoid - The Meaning Of Avoid - The Meaning Of Avoid - The Meaning Of elements present in the midst subscribe And subscribe The Amazing Subscribe - The Amazing Two Subscribe - The Amazing Two Subscribe - The Amazing Two Basic Types of Luteya subscribe to The Amazing 225 Will have to get that an ax a nice Complete the meaning of Maximum * Find a nice Complete the meaning of Maximum * Find a nice Complete the meaning of Maximum * Find out the difference between More subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page Now Half of the Norms Aap Eighth Also Neetu Discuss Around What All Conditions Will Exist When Will Not Benefit subscribe and subscribe the Channel Please subscribe And subscribe The Amazing All one subscribe to that with your friends on this great occasion to validate target maximum when will simply return for what do subscribe kar lu Video then subscribe to the Page if you liked The Video then subscribe to subscribe the Channel subscribe and subscribe loot and will be Coming let not give you for watching operation adhir va veervar ko subscribe Share and subscribe this Video plz subscribe approved used with computer appointed person Yudhishthir Video not top volume salt consider veervar ko subscribe from one to three do it that in odu rich look Fat in what they are currently doing click subscribe button subscribe subscription in between liquid with oo that shraddha and doing and nation will just mode wali you can result in to the question Ronit 500 from amazon or difference free mode The Amazing Loot Not Weep Subscribe Channel Subscribe I Want A Developed Physique In That 20 Minutes Complete The Wedding Gift Subscribe To Set Alarm Run Successfully For All The Tempest Acid Is 108 Times So Time Complexity Of Intense Pain Log In Under Subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to subscribe Send A Priority Kyun Dhond To Find The Samsool Dheer Wa Remove Virwar Ko Subscribe Value Subscribe Loot-Loot subscribe Value Subscribe Loot-Loot subscribe Value Subscribe Loot-Loot subscribe Video then subscribe to the Page if you liked The Video then subscribe to the petty why on father operation what is not getting up at subscribe now to receive new updates subscribe and subscribe 108 times but time complexity increase chief sexual crime tube electronic bulb skin video servi hai hua hai
Construct Target Array With Multiple Sums
find-players-with-zero-or-one-losses
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat this procedure as many times as needed. Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`. **Example 1:** **Input:** target = \[9,3,5\] **Output:** true **Explanation:** Start with arr = \[1, 1, 1\] \[1, 1, 1\], sum = 3 choose index 1 \[1, 3, 1\], sum = 5 choose index 2 \[1, 3, 5\], sum = 9 choose index 0 \[9, 3, 5\] Done **Example 2:** **Input:** target = \[1,1,1,2\] **Output:** false **Explanation:** Impossible to create target array from \[1,1,1,1\]. **Example 3:** **Input:** target = \[8,5\] **Output:** true **Constraints:** * `n == target.length` * `1 <= n <= 5 * 104` * `1 <= target[i] <= 109`
Count the number of times a player loses while iterating through the matches.
Array,Hash Table,Sorting,Counting
Medium
236
111
Hello Hi Everyone Welcome To My Channel Today In This Video Vihar Solving Problems Minimum Death Of Spinal Tree To Binary Tree Very Famous Data Structure And Lots Of Problems In The Married Things Frequently Asked In Interview Secretary Vinod Angry In Detail And As A Result You Very Famous Traversal Entry Difficulty and Tried to Solve All Problems Give Me the Number of Units Lungi Aadha 9999999999 From This One Plus One to Go to Apni Disagreement Note Sid Episode 215 This is Utterly 14 Minimum Nine to You 220 Very Straightforward Solution I Know You Must Have Also Very Busy Life But Can Solve This Problem Very Daddy Thanks To Its Soul With Tea Deficit Will Change It's There Is No Elementary Channel's Will Not Give Chase Fruit Nal Veer Water Canal That Fruit Mein Life Is Only Nal Among Misbehaved With Rights Of priests where to go to the guide supported and will return oneplus the minimum tips minimum from the subscribe similarly for the root dot right a fierce null sister it means will have only the fluid plus minute till this used oil's node for child will Get the return basically from gautam off from the tarzan minimum dot right subscribe kar do hua hai 1968 sudhar time complexity of dissolution and you can see bihar processing all the notes of var tree in vars case scenario so between means the time complexity can Give what is the number of units and installations can go now to-do units and installations can go now to-do units and installations can go now to-do list of the tree subscribe this Video plz subscribe Channel No evil returns from across this will create a new train from Delhi to implementation and monitoring subscribe 9 quit from all the Lord Shiva Singh Dhaliwal Dhool Is Not MP 09 2010 Ki Hum Tele Thing 9 2010 What We Will Do First Will Begin Your Order Will Process Level Will Have Also Like To Be Started From Pardesi Sawan Level Second Level And In The World Will Find Ads For Lips Not Mean That till date level after but some will increase in every level award for processing power and subscribe all the best wishes for truth no water not from check half of idli sandwich looking for a the the the bank will return that itself vitamin d water deficit Which will be our minimum otherwise check dam is not returned root dot write this not returned dot print only after the mid level Video Please subscribe and C 231 Walking Now We Can Submit Definition as Well 108 Accept the Time Complexity and Space Complexity of Dissemination If the implementation of vs straight forward is more than percent then you can implement and share and comment it will help you thanks for watching like share and subscribe my channel
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
374
hey everyone so let us talk about this lead code problem guest number higher or lower so we are playing the guess game the game is as follows I pick a number from 1 to n you have to guess which number I picked and every time you guess wrong I will tell you whether the number I picked is higher or lower than your guess so there is a guess API that is given to us okay and it returns three possible results minus 1 if you guess is higher than the number one your guess is lower than the number and zero whether your guess is equal to the number and then you need to return this number Okay so basically you are given n some range okay and then you need in the computer let's say picks some number over here let's say three okay so you need to guess from 1 to n this number three and you are given this gas API okay in which you pass the number and this API returns either minus 1 or 0 in case if it returns 0 that means you guessed it correctly and then you need to return this number okay so one thing that we can do is we can run a for Loop over here on this entire range from 1 to n and then check for each number and if that each number in the guess API returns 0 that means we directly return this number and then say that this is the number that the computer is picked okay but this is a very good example of binary search so if you just run this a for Loop you will get a Time complexity of O of n but using binary search we get a Time complexity of O of log n okay in this what we do is we pick two pointers low and high okay then we calculate the ah middle and then check this mid in the gas API okay and why binary search works over here is because we have a sorted array we have a range from 1 to n in which we need to guess the number okay now if this if we have picked this mid this number and we pass it to the guess API if the guess API returns 0 that means we have selected the correct number which is the computer aspect but if the gas API returns -1 that means but if the gas API returns -1 that means but if the gas API returns -1 that means we have guessed something which is very high and we need to guess in the low area Okay from in this range that means we have completely discarded the search in this range in case if the gas API returns 1 that means we have picked something which is lower and we need to pick a higher number and then our search is between this area and we discard the leftmost area okay so that way our algorithm returns in overflow of n time and this is a very good example of binary search Okay so let's just write the code and see how it looks okay so we'll create first two pointers low and high we have to run a while loop while low pointer is less than equal to high okay now we need to guess a number okay so we'll pick this number we find the middle element so we say low Plus High minus low divided by 2. okay so we use this formula to calculate the middle number basically we could have just said low plus High divided by 2 to get the mid but there could be a chance wherein low plus high would be an integer overflow that the result of low plus I would be an integer overflow that is why we are using this formula now in JavaScript division would return decimals okay so we need to return the digital out of it sorry the integer out of it we do not want the decimals so that is why we are using math dot floor okay so now we have picked this number Mid let's pass it to the guess API okay so now this gas API will return either minus 1 or 0 okay so if the guess API returns minus 1 that means your guess is higher than the number that is picked okay so we need to search in the lower range so we have to reduce our High pointer okay now if our guess API returns 1 that means we have picked a lower number we need to pick a higher number that means we need to move our search in towards the right hand side so we say low is equal to Mid Plus 1. and if our gas API returns 0 that means we have picked the correct number that the computer has cached so we return the number okay so let's just run this on the test cases all right so we got an acceptance on the test cases let's submit it Okay so we've got an acceptance
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
938
in this video we will look at a range sum of a binary search tree so let's see the problem statement so we have a binary search tree so all the nodes in the left sub tree of a given node will be less than the current node and all nodes in the right subtree will be larger than the current node so uh here you are given a range for example the range can be 7 to 15 and this is inclusive range so 7 is included 15 is included so what you have to do you have to return a value return the sum of values of all the nodes so a node has left right and val so you have to visit all the nodes check if it lies in this range inclusive so even if the value is 7 it should be included if it lies in this range then you add to the result otherwise you ignore that node so you have to return the final sum so let's see how we can do it so first of all you need a way of doing traversal of a binary search tree so any of the traversal methods is fine whether you do pre-order methods is fine whether you do pre-order methods is fine whether you do pre-order post order in order or even level order any order you prefer you must visit all the nodes so first let's write the code for the traversal and then we will slightly modify that to solve this problem so let's say our function is find sum and we are given root so in traversal we are just given root so first let's complete traversal so what we do so if root is null then we return and then what we do we visit so whatever is the function or we can print root well then what we do i am doing preorder you can do any other traversal as well then we do the same function find some root left then find some root right and this is the traversal function is complete now uh instead of just visiting it we have to also calculate the sum so let's modify it and this would return int so if root is null then you should return 0 so you are asking that find the values of all the nodes having values in the range low and high in this case lowest 7 i is 15 so the node is empty then the value is 0 there is no node so this remains same else you create a local variable to store the result so initialize it with 0 and instead of just printing the root value you check if root value is less than equal to high and greater than equal to low then instead of printing it we will add it to the result plus equal to root val next result plus equal to find some root left and here there are extra parameters high and low which will remain same in all the calls else result plus equal to find sum this and result plus equal to find some right subtree so very simple if you write any traversal code you reach a given node and then from there you reach all the other child nodes so instead of just printing the value you check whether that lies in this range then add it to result if it doesn't lie in that ring this line will not be executed and it will not be added to result so in the end when this traversal completes you would have accumulated all the values having values in that range now let's write the code for this if root val is less than equal to high and root val greater than equal to low then result plus equal to root valve root plus equal to the same function and we return results so this is same as pre-order traversal uh so the answer is wrong let's see sorry not root result i don't so it should be result root is the node pointer and our solution is accepted so i hope you understood it
Range Sum of BST
numbers-at-most-n-given-digit-set
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
Array,Math,Binary Search,Dynamic Programming
Hard
null
953
Hello guys welcome to front media manager and will be discussing various points induced in this question Thursday subscribe Indian hidden files appointed subscribe really description and subscribe this Video give and bihar radhe-radhe vidron in english bihar radhe-radhe vidron in english bihar radhe-radhe vidron in english language subscribe in english if know Effective Work Subscribe Andher Previous Video Which Are Subscribe subscribe and subscribe this Video Subscribe Quite Well In This Question They Can Not Used Default Servi To You Will Receive The God Of But Salt Code With Me To Subscribe Notice Subscribe subscribe and subscribe the Channel subscribe Thursday Subscribe button video 4 that which is not right to edu sare note subscribe button for scientific knowledge about the middle and give subscribe to the Page if you liked The Video then subscribe to subscribe our Subscribe Friday morning using interior is exactly for the mapping Subscribe And 9 Rates On Shampoo Don't Volume Internship In Sequence And Comment It No Veer Vivo Luttu Length - Vwe This Current Subscribe Lutb - Vwe This Current Subscribe Lutb - Vwe This Current Subscribe Lutb School In Three Different Appointed The Length Of The Day Main Naagin Tu Ullu Tel Is Particular Length So They Can Help Vivo Length Admit Difficult President Is Particular Withdraw Subscribe Button Click President Subscribe Value Day Thursday And Vidmate Subscribe To Pimp WhatsApp Number Four Committee Did Not Get Specific And Vacancy In This Not Giving Husband Then And President Witnesses subscribe The Channel and subscribe the Channel subscribe School Day Adhir Value and Subscribe 9 Absolutely to the current length but in this request to the next length subscribe The Channel Please subscribe and subscribe this Video give Veer subscribe thanks for watching this Video Singh A Hua Hai
Verifying an Alien Dictionary
reverse-only-letters
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Two Pointers,String
Easy
null
436
hey what's up guys chung here so today let's take a look at this little problem number 436 find right interval okay so you're given like a set of intervals and for each of the interval i check if there exists an interval j whose start point is bigger than or equal to the ice and the end point and for each of the i here you for each of the interval i you need to return like the minimum index the mean index of the interval j who's like the starting point is greater or equal than the ice and ending point okay and if there's no such index interval j whose starting point is greater than the then the highest ending point you just put minus one okay so example one here right so the first one is always if you only have one like one item there is there's no other there is no other intervals okay so that's why the only thing you have is minus one here and the example two here okay for example the first one is three and four is that is the target we're trying to look uh looking for right basically we're trying to see among all of those like uh intervals if there's any intervals whose starting point is greater than four but unfortunately there's no such intervals that's why the first one is minus one okay and now it's uh now we're tracking the two and three here so now three is our search target and okay it happens to be that the zero the first one the three is equal to the equal to three that's why we have zero on the second index the second element so here now we're either like one two so this number just number two is our search target right and okay and then we're looking for yeah actually sorry so i think that the problem the description is a little bit confusing here so okay so here's the tricky part basically you need to find uh among all the intervals right whose j is greater than the current ice starting point you need to find the minimum start point of all the interval j's okay that's why uh when we are tier right that's why when i add one and two here okay so we're looking for if there's any intervals which is greater than two here now we have two options we have two uh candidates three four and two three right both three and the two is greater than two but since we are looking for the what the minimum one that's why uh we need this one that's why we need this interval whose index is one that's why we have a we have one here not zero okay cool i think you know as long as you can understand the description of the problem you know this uh the solution shouldn't be that hard to come up with i mean uh then the brutal fourth way is like every time we loop through each of the interval right into each of interval and then we have a target okay so from the target right we uh we look through all the intervals one again from start to the end okay and every time when we find like valid candidates right which means uh that interval's a starting point is greater than our target then we just uh try to maintain the minimum start point okay and then in the end we simply return the uh the minimum index of that okay basically while we're maintaining like the current minimum start okay we're maintaining like a current the minimum start so every time when we have a valid candidate we just check we check okay if that start is it's smaller than this minimum start if it is then we update our index okay yeah and in the end we simply return that minimum the minimum index okay um but you know since there's a like this uh constraint here you may assume that the interval's endpoint is always bigger than the starting point and also none of these intervals have the same start point okay what does this mean the second one means that if we sort by the start point right so everything basically everything is increasing so that i mean so and it's kind of obvious that we can use the binary search right to find the minimum starting point okay and since each of the starting point is unique we can simply also we can also build like a hash table right with the key is the start point and the value is the index for us to start for that starting point so that later on after we find the minimum starting point we can easily find the index the interval index for that starting point okay so let's try to call these things here uh answer equals to and then we have n here okay n is the length intervals here so like i said i'm going to create like a starts uh like a hash table okay and the uh the key is the starting point and the value is the index so later so that later on we can use the start point to find the index so the key is the interval you know for i and interval in enumerate okay intervals okay and the key is the starting point which is the interval the first element of the intervals and the value is the index okay that's how we uh initialize our hash table for the starting index first starting point and it's index and then next one is we just need to sort right maybe we just need to sort all the starting point okay so basically i'm just have like sort sorted starts equals to what equals to the sorted same thing here right the interval zero for interval in intervals basically i'm getting i'm using like a shortcut in python basically i'm looking through all the other starting point among all the intervals and then i'm going i saved them into a list and then i stored that list so to get this sorted starts okay now we have a um we'll start and end right in the intervals okay and what's our target basically our target our search target is the end point okay and we're trying to find the uh the minimum okay the minimum uh starting point that is greater than the uh than our target okay so i'm gonna use the pythons bisect you know left to find the uh to find the index so the source is this and we have a target here so why i'm using a bisect left here uh so by bisecting the left means if we have the same value as a target in this like sorted starts list we're going to return the index on the left side so why is that let's take a look here let's say we have one two three four and five okay and let's see that's our sorted starting point and our target is three let's say the target is three here and that's our start all the starting point and we're looking for the three here okay so uh so if we have a three here right that's the basically if we have three here and we know that's the answer we are that's the starting point we're looking for okay and the index is uh zero one two three and four okay and when we have like a three here right so we're gonna uh return the index on the left side which is the which is two so here the index is two it's on the left side but if we are having if we're using a bisect right and if we have a 3 here right if we see us the same number as our search target here instead of 2 here it will be returning the index on the right side which will be three but that's not the answer we need because we need three here okay so that's why we use a lab okay what if the let's say we have a not four or five let's say we have a seven and eight okay let's see if we have seven and eight and we're looking for uh not three let's say we're looking for five okay so in this case it so since there's no same element in this uh search array here it doesn't really matter if we use a bisect left or right it will just always give us uh three here give us the position to insert basically this thing returns you the position that you can insert this five which in this case it's gonna be uh gonna be three okay and the three is the answer we need okay because we're looking for the answer that's greater than equal greater than five which is uh seven in this case okay and that's why we choose this bisect left here how about the minus one how can we know uh if there's no such element okay um cool so let's say we're looking for 9 okay so for if we're looking for 9 here there's no such element which is greater than 9 in that in the array here so how can we know if this there's nothing in the target if there's not there's nothing in the sorted starts and that can that we can have like a we can find the target position so in this case if we have a knight here right the index will the index returning will be like what zero one two three four five it's going to be five because nice since nice greater than all the elements that's why the insert position for nine will be at the end of the uh at the end of the array so with that we can simply do a check here basically if the index we're returning is equal to the n then we know we couldn't find any start starting point that's either equal or greater than the target then we simply append -1 okay else we append uh okay so here it's uh the starts hash table comes into play here uh we're gonna have like uh let's do a start point okay start point is gonna be the starts uh sorted starts dot index okay so now we have the index we just use the index to look for the real start point that we need but uh with the start point here we can just use the start point to go back to the start hash table to find the index for that starting point okay and then we just append that to the answer and in the end we simply return the answer yeah i think that's should just work oops uh oh sorry sorted it's a function here cool submit yeah so it passed basically you know uh you know the first approach the brutal force approach is uh is just to do an acid for loop which will be uh n square but for in our case right so let's take how about the time complexity for this one uh this one is owen right that's owen this is a unlock and right because we sort how about this one here uh here's n right here's n and the by select is a lot it's a log n so in total it's n log n that's the time complexity space is n okay so basically we're just using the uh we use the binary search uh to improve the time complexity from n square to n log n yeah here yeah i think that's pretty much it is it's a pretty easy like uh i would say it's an easy to medium uh problem so it's a good practice right it's a good practice for you guys to get familiar with the binary search right both the binary search and maybe the hash table a little bit okay cool uh thank you so much for watching the video guys and stay tuned i'll be seeing you guys soon yeah bye
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
258
hi folks let's try to do the elite core 258 which seems like a very easy problem to do and i guess it's good for if you're starting out and programming and you just want to do some low hanging fruits and probably practice your favorite language while doing that it sounds like a good idea so here it is it's given a non-negative integer num non-negative integer num non-negative integer num which means zero or a positive number repeatedly add all its digits until the result has only one digit so you give some examples like 38 and he says output is two and the process is like 3 plus 8 is 11 true and then now you add 11's digits which is 1 plus 1 equal to 2 and then you can return 2. so you basically continue to add the digits of the input number and once you um you have to keep resetting the input in a way and this is which suggests kind of a loop and then repeat the process and whenever you find a sum that is less than 10 basically that means it's in single digits you are good to go so i guess that's what we need to do so let's try we will be we're going to do this in c this is our current darling and how do we do that we say let's have a accumulator variable sum and while num so that's where your idea of resetting and doing this in a loop so you get to practice loops in this problem so what should we do we should say sum equal to sum plus some easier accumulator and what you want to do is you want to grab one of the last digits in num so that is kind of extracting digits from num so this is like for example 38 num mod 10 would be what 8 because it completes it divides by 3 and the remainder will be 8 so you get 8 here so somewhere at this point will be 8 actually 0 because with 0 here now what do we do now um we see that if um if at this point you need to see if your num is less than now you see what are the things so at this point you see that num will be equal to you could say num divided by 10 and this is integer division it gets rid of the last digit in num so that means number now would be 3 and we will go back to the loop and as long as here num is um when you come inside this you would see this loop would continue to go on as long as num has num is having some value they say num is not zero so but if you come inside the loop with num being like in single digits like three now you know that this next time around you will not be coming here so what is the idea you need to make sure that your now what is asking is saying whenever your sum is less in single digits so you say if some less than 10 we might say break and here we might say hey return sum but what is the gotcha here the gaucher is we still have to make sure that we do not prematurely get out of while loop because what happens if your you should do this only when you know that you have no more digits to be uh to be gotten from num so you say so if num is less than 10 what does it tell you that the next line will give you zero and if next line is going to give you zero you know that you basically run out of the digits in the num so what we should do is we should say here that if num is equal to 0 that means we have run out of the uh the digits in num right if num equal to 0 basically is num is equal to zero what do we need to reset num so num would be equal to sum and sum has to be reset back to zero so now you take the example of like 38 we said while i'm 38 sum is eight first time here in line seven if num less than third ten no num is actually thirty eight and sum is eight so we don't break out so now num is 3 because 8 is already taken care of 3 now there's this number quadrature no so we go back sum becomes 11 now because num is 3 more t and 3 is 3 and sum was already 8 so we have 11. now 11 again if num less than 10 sure number is less than 10 because num is actually 3 but is some less than 10 because we are supposed to return only when the sum of the digits is equal to less than is in single digits so we still don't break out of it and num now goes to 0 when num goes to 0 we say we reset num to the current sum which is 11 so num becomes eleven now sum becomes zero we follow the process again at some point what happens is we get one we get again one now it becomes two then what happens num is less than one ten one and sum is because we know that whenever the num is in single digit over here on line 10 you will end up with 0 and the loop is done so that is why we try to put this before getting the last digit here say if num less than 10 is in single digit and sum is already in single digits which you can simply break out of it because you're not going to go in the loop again at this point unless you reset numdu whenever you see that the num is zero has become zero you can reset it but we already know that we have some in single digits so there's no point in doing all this we can simply break out and then just return some so let's see what we get so far in testing when we pass the test case okay cool so that works let's see submit and that works as well so it's all looking good um i guess it was a relatively easy problem and no wonder it has been characterized as easy by late code but nothing wrong in doing one of these easy problems and keeping your creative coding juices going i wish you all the best and i'll see you in the next video until then take care good bye
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
15
hey everyone today we're doing thre sum and thre sum is a problem that is medium and if you understand what two sum is it should follow what three sum is but I'm going to read the problem statement out and I'm going to say it's given an integer array nums return all the triplets nums I nums J and nums K such that I is not equal to j i is not equal to K and J is not equal to K so basically we don't want duplicates it's going to repeat that here the solution set must not contain duplicate triplets anyways the target is going to be zero so while this whole duplicate thing makes the problem a bit of a pain in the ass the concept is not hard at all and we should draw on our knowledge of two some as you may know leak code is all about pattern recognition so let's go ahead and try and do Tome first now here is a part where a lot of people trip up because TM is most commonly taught using the hashmap method in other words using a dictionary and storing the complement and this is a very simple and intuitive way to through the problem it has the benefit of just works and it makes a lot of sense so why don't we use the dictionary when we want to extrapolate it through threesome does the dictionary work and the answer is not really as well as we want to because what is the step for us to get from two sum to three sum in other words how do we reduce thre sum into two sum well let's think about it this way we have instead of two numbers we have three numbers we need to find and we need to find all possible combinations of three numbers that would sum to our Target but what's way one way we can figure it out only using two numbers let's say we had two sum just as a function how could we make this function how could we use this function to work in our implementation of thre sum well what if we thought backwards a little bit what is a triplet well a triplet is you know we have i j and k so we have all these values sorry that my handwriting is terrible and the main thing is that they all sum to zero right now that means that let's say we move nums I to the other side we can also state that nums J plus nums K is equal to negative nums I this intuition does not take a lot of math to understand it's very basic math if all these are supposed to sum to zero our Target then the sum of two of them should equal to zero minus that Target and if we find all the not sure what to call them I guess duplets if we find all these duplets that sum to this number then we've actually reduced the problem into two sum because we can just go ahead and add nums I duplate one nums I duplate 2 and remember each duplate is just a j and a k we can just use all of these and these are the three sums and if we do it for every possible I then we've solved three sum so basically to State it in more simple terms three sum is two sum for all Targets 0 minus nums of I and for all I in nums now why does the dictionary approach not work and let's go ahead and go down here so the dictionary approach takes a lot of memory it only takes o and of time to run but it also takes o n memory so you can see how if we're doing o and memory for each element in nums that would be of n s memory and this can get out of hand really fast and we don't want that because memory in general is not very scalable right when you have a lot of elements it's easier to then default to runtime because then memory will become your bottleneck So to avoid having to make a dictionary for every single element and store all those dictionaries together you know and it just becomes very convoluted what we can do instead is go to another method of two sum this is the two sum dictionary we'll go to another method of two sum that is slower but uses less memory sorry to some pointer or sliding window and this actually does not take any memory it just uses the original array it's going to take n log n run time all right to do this two sum because we're going to have to sort the array but you'll see why that is in a second I'll walk through an example for two some and it takes of constant memory so you can see how this can help us reduce the amount of memory we're using when we are running through this algorithm in threeome let me clarify that this is the runtime and this is the memory so let's go ahead and run through it so imagine that your array is sorted and you want to find all the duplets that sum to zero well we have our array here and we have our Target which is zero so how do we consider all the pairs that might sum to zero well General theme in sliding window is that you start at the ends and you move inwards this works a lot with sorted arrays and I'll show you why that is the intuition for that in a second but the idea is that if your array goes to some crazy negative number right and it's sorted of course and there is some huge positive number let's just say 9 8 74 if there's something that sums to zero there's going to be one on this side and this side of zero because a negative number and a positive number the only way two numbers can sum to zero is if one is positive and one is negative so we start from the left and we start from the right in order to find those possible pairs now they could not exist for example let's say we had the array -2 and one just because had the array -2 and one just because had the array -2 and one just because there is a positive number and a negative number does not mean that the sum to zero but if there is a pair that sums to zero one has to be negative and one has to be positive and a very intuitive way to search for that is to start at the ends because our array is sorted and this will side will be positive the right side be positive and the left side will start with the negatives and if you follow this intuition then you can extrapolate for numbers that are not zero targets that are not zero if there is a sum that adds that Target then one will be on the left side and one will be on the right side of the array and you can find that possible pairing by moving through the array with your pointers but let's go ahead and run through our little trivial example here so our left pointer is going to be pointing at Nega 1 and our right pointer is going to be pointing at one so -1 + 1 what does that equal it's so -1 + 1 what does that equal it's so -1 + 1 what does that equal it's equal to zero so clearly that means that we found a solution so -1 and one is a we found a solution so -1 and one is a we found a solution so -1 and one is a possible pair so what else should we do now well we should move both our left and right pointers because we don't want duplicates we don't want to consider this negative one and this one again and then we move them both into the middle so we move them both into the middle and now they're both pointing at the same thing and obviously we don't want to add z0 because that is not a duplate that is just one element being repeated twice so an important thing we have to watch out for is that L should always be less than R this has to be true we have to make sure that L is less than R when we're doing the sliding window method because if they're pointing at the same elements that means that we should end our Loop so that's the basic idea now let's consider a little bit of a more complicated array so how do we adjust our left and right pointers in this case well of course we start at the ends of the array and let me move this so it's out of FR so of course we start at the ends of the array like we did before but now we see that -2 and 3 are equal to now we see that -2 and 3 are equal to now we see that -2 and 3 are equal to one so if our Target is 0o right this is not a valid pair so how should we adjust our pointers so that we consider a valid pair well the concept is when our sum when our current sum is greater than our Target we should try to adjust our pointer so that it gets closer to zero and one way of doing that is moving R right because R is currently pointing at a larger element why don't we move R so that's pointing at a smaller element so instead of having r pointed here now R can point to here and you can see that this will reduce our sum to equal to zero so we have indeed found something that adds to zero we found a two sum or a dupl whatever you want to call it we found one so this will be added to our answer is now going to have -2 and two in is now going to have -2 and two in is now going to have -2 and two in it if we do that same thing where we move both L's to the if we both move both pointers to the middle now they're going to both be pointing at Nega one and we know that our three sum or excuse me our two sum is now done so we adjust our pointers based on the sum in order to consider all possible pairs that might add to our Target in this case that meant adjusting our right pointer by one to get our desired result that's how you do two sum with a two- pointer method how do we two- pointer method how do we two- pointer method how do we extrapolate this to threeome well like we said before there is a way to just run two sum on all the complements that are possible in this given array we're going to sort it first because we need to do that for our two-pointer solution to do that for our two-pointer solution to do that for our two-pointer solution and how are we going to get the three sum of this well remember if we run two sum n times for each Target minus nums I for I in nums we'll get all the triplets we need so if we partition in the array let's say this is I this is the starting we just need to find all the duplets here or all the pairs here that sum to 0 - -4 which is equal to 4 as long as a + - -4 which is equal to 4 as long as a + - -4 which is equal to 4 as long as a + b is equal to 4 this means that 4 + A + b is equal to 4 this means that 4 + A + b is equal to 4 this means that 4 + A + B will equal zero so we just run our two sum on this array so run two sum on -11 0 let me do a shorthand here right -11 0 let me do a shorthand here right -11 0 let me do a shorthand here right run two sum on this blue square this blue box until we have for the Target equal to four that's how we'll find the triplets and you can see here that there aren't going to be any triplets that include -4 what do we do triplets that include -4 what do we do triplets that include -4 what do we do next so we saw that there were no triplets that include -4 so what is our new element that we -4 so what is our new element that we -4 so what is our new element that we need to consider the complement for well NE the next one would be-1 and what should we run two sum on be-1 and what should we run two sum on be-1 and what should we run two sum on well we should run to some on the rest of this array here the remainder part of the array and what is our Target well our Target should be whatever 0 minus -1 our Target should be whatever 0 minus -1 our Target should be whatever 0 minus -1 is which is one so our new Target is one this is our Target and let me do that for you really quickly if our left pointer is here and our right pointer is here well we can see that -1 + 2 is here well we can see that -1 + 2 is here well we can see that -1 + 2 is equal to one so we found a good triplet we found a triplet that adds to zero that triplet is -1 as well as -1 and two that triplet is -1 as well as -1 and two that triplet is -1 as well as -1 and two our lnr so that's how we do it and we can move L andr again so now they Point here and you can see that now 0 + 1 is here and you can see that now 0 + 1 is here and you can see that now 0 + 1 is also equal to one so we found yet another triplet so you can see how we're finding these triplets right now we have that same -1 and this time we have 0 and that same -1 and this time we have 0 and that same -1 and this time we have 0 and one and you can see that the sum here is in fact zero so now L and R we're going to subtract the so L has crossed R and we'll see that our Loop can no longer continue but that's the general idea it's going to take a while to really understand this but as long as you get this part you have basically solved the question now if you solve just for this you're going to get duplicates but I will go ahead and just show you how this works like we said we're going to reduce thre sum to two sum so let's just go ahead and forget that the problem is three sum and just write two sum using the sliding window method so let's just say our Target is equal to zero and this is arbitrary I'm just going to choose zero and you'll see that we'll change this later because you know this is not the problem but for our purposes we'll just say the target is zero and we're going to say that L is equal to zero l is going to point to the first element and R is going to point to the last element and these are indices so L and R are indices we're going to have L be the left side of the window R be the right side of the window and we're going to slide them in order to find the elements of those pairs that are going to add up to zero and what do we do here well while L is less than R remember we don't want our edges of the window to slide into each other over each other we're going to say that if nums L plus nums R is equal to our Target then we found a good pair so we need to keep track of our answers right our pairs so let's have a array to do that and we'll go ahead and append L and R to that array and let's say that n this uh the sum so M nums L plus nums R is less than the target well what should we do well we should adjust our L pointer to be greater because remember our array is sorted now did we ever sort that array no so we should go ahead and do that so let's go ahead and sort our Ray to begin with that's very easy to do in Python now that we've done that you can see that our sum is less than Target so we have to increase our l in order to make sure that we are now considering a bigger elements at L like for example in this array it's already sorted you can see like obviously if our Target was two hypothetically and we're considering zero and one we would want our L to move over here because zero and one are only something to one we want our Target to be two so we need to make sure our L is moving to consider something that might be a possible pair so let's do that and else well you already know R is going to move as well and it's important when we find a pair that reaches our Target that we also move our window to no longer include those elements because we need to progress we can't just consider the same elements over and over again we want to make sure our window is always moving and that our problem size is always becoming smaller so let's go ahead and just run this notice that we did not solve the problem but this is a two sum implementation so let's see if it's doing a two sum here actually I don't think it is oh because I never returned answer so return answer so you can see here that oh so the question actually doesn't ask for the indices it asks for the elements so we can go ahead and fix that really quickly here so I remember I'm not trying to solve threesome here I'm just trying to solve two sum so yeah you can see here that we're finding these pairs and we're finding these pairs here and yeah this implementation seems to work for two sum now let's make this three sum and remember the magic step we're just going to consider all the complements for every Ed nums like I said we have to consider each complement in the array so let's go ahead and do this so now we have I so our Target is going to be 0 minus nums I because this is the complement that we are looking for this is the target we're going to be looking for and instead of our pairs here we're going to make triplets so it's going to be the element at I that's going to be our answer and instead of L being zero every time L is going to be I + 1 I'm going to time L is going to be I + 1 I'm going to time L is going to be I + 1 I'm going to tell you ahead of time that it's not going to pass every case but let's see if it passes any cases yeah and you can see it's passing case two and it's passing case three it's failing case 4 and it's failing case one what is the problem with four and one well if we look at our output you can see that we're still getting duplicates now here is something you should do in an interview if you don't know how you can fix this problem well you can do a little trick if you know something about data structures and you can just have our answer be a set and a set gets rid of duplicates automatically for you so what we can go ahead and do is append instead of a array you can append a tuple which you can put in a set because set has to have immutable elements so if we go ahead and do something like this doesn't have a pen so you have to do like add I think and yeah it will actually work but this is actually not the most efficient way although I don't believe it actually changes the runtime like dramatically although checking for membership in a set um checking if a set is still valid essentially that there are no duplicates might be the reason why it's taking so long you've technically solved the problem in a clever way but instead of using a set the actual way to do it is to instead consider what we're doing here right when we append this so we've already avoided duplicates in a way by moving our L pointer to I + one instead moving our L pointer to I + one instead moving our L pointer to I + one instead of repeating from zero all the time but there's also something that we should consider here too if for example let's go ahead and use one of those test cases we're failing here let's go ahead and consider this example which is obviously creating duplicates now why is it doing that so first our I is going to be here and then our L is going to be here and our R is going to be here so obviously what is our Target well our Target is going to be two because 2 + -2 will going to be two because 2 + -2 will going to be two because 2 + -2 will equal to zero so we obviously have that right off the B would we have -2 right off the B would we have -2 right off the B would we have -2 which is this we have zero and two so this is a valid triplet so what do we move lnr and now lnr Point here and you can see our obvious problem because this is also Zer and two so it's the same triplet and it's also valid but that causes a problem and let me use red here to kind of show you exactly what is the problem this lnr is this 0 and two but there's also an lnr that's this 0 and two so how do we avoid that well there's a little trick is that when you find an answer you don't want to consider any other answer that has the same element as its L because that's how you get duplicates this other zero existing being the same as this zero is how we got duplicates so if we just go ahead and check that every time we get this answer when we do those movements we need to consider if L is the same as the L that it was before and we can just do that by checking that nums of L is equal to nums excuse me nums of L minus one and if they are equal that means that we might make a duplicate so we don't want to Pro proed we want to instead move L to the so make L = to L + instead move L to the so make L = to L + instead move L to the so make L = to L + 1 until nums of L is not equal to nums of L + one so remember we have moved our L + one so remember we have moved our L + one so remember we have moved our lnr now it's time to see if nums of L is equal to nums of L minus one this means that our element is the same as the one preceding if it is then let's go ahead and move L and we don't want to do this just once we want to do it as long as it is true so let's go ahead and do this and now we have avoided this problem it should be fixed now so let's go ahead and run this and let's make sure L is less than R cuz L can definit increase too much and there's also just another stupid case where you might have duplicate triplets just based on their being duplicate elements and uh this is also extremely unfortunate I'm going to go ahead and run here and you can see that we're still failing case one and I'm going to go ahead and make yeah so case one is failing because if we go ahead and sort this array so -1 oh sorry this array so -1 oh sorry this array so -1 oh sorry -41 0 1 2 why is it failing so we're -41 0 1 2 why is it failing so we're -41 0 1 2 why is it failing so we're going to consider L being here R being here Target once again is one so -1 + 2 is equal to one again is one so -1 + 2 is equal to one again is one so -1 + 2 is equal to one so we have our good triplet 1 and two this is red and this is blue these blue ones these red ones now what do we do in that circumstance well we move our pointers so let's go ahead and move them now it's pointing here and R is pointing here and yes 0 + 1 does equal to one so here and yes 0 + 1 does equal to one so here and yes 0 + 1 does equal to one so now we have 0 and one so we found the triplets the problem is when we use this element as our I this case I is equal to two when this element is our I then we're going to get the exact same triplets we're going to get once again 1 and two or excuse me we won't get 1 and two but we will get -1 and get 1 and two but we will get -1 and get 1 and two but we will get -1 and two we're going to get a duplicate of this because let's see if we run through this right let me just prove that really trivially so once again our R is pointing at here it's not going to 0 + 2 pointing at here it's not going to 0 + 2 pointing at here it's not going to 0 + 2 is not equal to one so now if we move our to the left we are once again going to get - 1 0 oh man 0 and one you can to get - 1 0 oh man 0 and one you can to get - 1 0 oh man 0 and one you can see that these two look the same but they use different negative 1es and thanks to that they become duplicates let see a more different color this negative one is from this but it doesn't matter because the result is a duplicate and we do not want duplicates so how do we prevent this well we do the same thing we shift our I if we see that is equal to the Past eye so when we're here right when our eye is here we check is it equal to the Past eye if it was then we move forward and we'll just consider I as being zero so that's how we get around this little caveat okay back to code let's go ahead and Implement that really quickly so when we consider the I if nums I isal to nums IUS one then we'll continue we don't want to consider it excuse me because all we're going to make is duplicates let's go ahead and run now it's failing so one little caveat once again and this is really annoying but you can see here that let's say I is zero nums 0 minus one is nums negative 1 and it's calculating that zero is equal to zero here so obviously we don't want to use the wraparound array like stupid thing of python so going to make sure that I is not equal to zero okay in fact we can yeah now it should be fine and yeah you can see we now passed that case because it's no longer comparing nums negative one and nums zero so that's just a little stupid python thing that you have to account for but you know it's not even python thing it's just important to always be aware of what your indices are because if you're indexing outside the ray or if you're indexing somewhere you don't expect could cause problems so let's go ahead and submit and see if we finally covered all the edge cases and we have we've covered all the edge cases now if you cannot come up with these edge cases in an interview remember that you can always use the set solution to kind of wiggle your way out of that one and yeah this is an annoying problem with some caveats due to the uh not wanting duplicates rule but if you just think logically you should be able to get around those exeptions and really the base logic is not that much more complicated than tuum you're just doing two sum end times for each element and each possible complement and this can be extrapolated to four sum to five sum to n sum however many elements you want in your little arrays you can come up with a solution so yeah that's it for this video
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery 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 for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
1,486
okay let's go over 1486 xor operations in array so question says given an integer n so n is a lumber and integer start and start is also number defined an array gnomes where lumps at index I is equal to start plus two times I and we start at index zero so already Nam's is going to be an array with numbers and n is equal to the length of the in numbers array we turn the bitwise XOR of all limits on numbers so before we solve this problem we have to know two things one is binary numbers and second one is how X or our operation works okay let's go over binary numbers first so binary numbers so if you're not familiar with the binary numbers just kind of write a bunch of them down one - kind of write a bunch of them down one - kind of write a bunch of them down one - all right these are numbers in binary numbers so one is 0 1 7 is 0 1 and each binary number is evaluated this way so the last one is 2 to the 0 increases 2 to the 1 2 to the 2nd and 2 to the 3rd it's based on - that's why it's called it's based on - that's why it's called it's based on - that's why it's called binary numbers and let's work with the first one number one we have 0 1 as our binary number right and 1 this where one is that it's 2 to the 0 right so ignore all the zeros so what's 2 to the 0 evaluator tutors anything to the power of 0 evaluates to 1 so that's 1 that's how we get the number 1 let's look at 5 so 5 is 0 1 right so again this is 2 to the 0 and this one is 2 to the second so what is ii value evaluates to 4 and this one again 2 to 0 evaluates to 1 right and i said ii values 2 4 I think I said one before and what we do is we add these 2 so 4 plus 1 is equal to 5 that's how we convert binary numbers to regular numbers and now let's go over on X our operation okay so we're gonna have X Y and X to the Y alright and just gonna write the whole thing down again okay you know XOR operation when you have the same thing like 0 and 1 it's gonna evaluate to 0 and when you have different digits like 0 and 1 or 1 and 0 it's going to evaluate to 1 so think of this as if you remember in your math class arm when you do like plus minus an operation this is usually so this thing that you're multiplying a positive number and the negative number it's gotta be negative right and you do negative and negative it's positive and you do positive and positive it's positive and your negative and positive its negative this is pretty much the same let's go over an example so in example one we have n is equal to five and star is equal to zero and somehow we get an output of eight so when n is equal to five times the length of our array is going to be five you know what we get as our array is 0 2 4 6 8 so it has a length of 8 right and it's the numbers are start plus two times I okay so what we want to do is you want to write all these numbers in binary so 0 is gonna be 0 and 2 is 1 0 4 and 0 1 0 6 is 0 1 0 &amp; 8 is 1000 1 0 6 is 0 1 0 &amp; 8 is 1000 1 0 6 is 0 1 0 &amp; 8 is 1000 1 0 and that we want to perform XOR operations so let's go for a few ones zero and zero is gonna evaluate to 0 is also kind of evaluate to 0 is gonna evaluate to 0 and 1 here is gonna evaluate to 1 and we do this for all the columns like this ok so I did all the calculations and you can try it on yourself too we're left with 1 0 you remember I binary numbers this is 2 to the 0 2 to the 1 2 to the second and finally this is 2 to the 3rd so all these stuff just zeros you know where and what's 2 to the 3rd 2 to the third is 8 so if you look at our output we get an 8 right and that's how we get our final result so now that we know our binding what binary number is and what exactly XOR operation is the structure code our solution so first thing I'm gonna do is I'm gonna make an array of whatever numbers that we were supposed to get so I'm gonna do start plus 2 times I for each number okay so let's just make it a variable that nuns alright and I'm just gonna set equal to an empty array and for that is equal to 0 and I start at index 0 is less than and increment by 1 and what I'm going to do is I'm going to dump in the number after doing the operation so it's telling us to do start plus 2 times I we're just doing this because the problem is telling us to do this for each numbers array and let's just check our array so we need to return nums array thumbs up thumbs already dot push so we get 0 2 4 6 8 so 0 2 4 6 8 &amp; 3 5 7 so we get 0 2 4 6 8 so 0 2 4 6 8 &amp; 3 5 7 so we get 0 2 4 6 8 so 0 2 4 6 8 &amp; 3 5 7 9 so this was correct so we 9 so 3 5 7 9 so this was correct so we now have an array of the operations that a problem wanted us to do so stop plus 2 times I and if we check the length oh and for the first one is 5 right so we have 5 numbers here four numbers here one number here and 10 numbers here okay next thing I'm gonna do is now we have to do the XOR operation so I'm just gonna make a variable named result and now I want to return result here me salt all right so I'm just gonna do another for loop here so for that I is equal to 0 is less than tons or a darling and increment by one so I want to go to the numbers array and want to do the X or operation right and XOR operation is performed like this hat is equal to nuns array index I so we're gonna do the XOR operation on the current number at index I and if you check our answer just in 872 right and if you go back and check our answers on the top I'll put eight seven two so there we go that's our solution you know guys let's go over our cool one more time just to understand it a little better so we declare our function XOR operation which takes in two parameters and then start which is an integer and first thing we want to do is we want to actually do the operations that are problem one since it so numbs array is going to have an array with numbers and the operations that we do is start plus two times I and that's what we do here so we big ski or change the numbers or to get change numbers because that's what the problem wanted us to do and next after we are done with that we do XOR operation here so we go through all the numbers in our array and we perform XOR operation here and that's done with hat and an equal sign at current number and finally when we're done with both of these two loops we return our result let's go over one more example just to get a better understanding so example two is for n is equal to four and start at three right so we get an array with three five seven and nine here we go that's the already that we get and what was three and binary number so binary number is 0 1 4 3 5 is 0 1 and 7 is zero 1 and 9 is zero I mean 1 0 1 and if you remember your X or operation so basically if it's same at 0 different is 1 so 0 we have mantises can evaluate to 0 1 is gonna evaluate to 1 and we have 0 here 1 here and desk evaluate to 1 again and 0 1 is 1 right on the side 1 0 is 1 the same evaluates to 0 so 1 0 is 1 again and so this is a meteor so we have 1 0 is not evaluate to 0 so ya 1 0 right and 1 0 is gonna evaluate to 2 to the 0 2 to the 1 2 to the 2nd 2 to the 3rd so what's 2 to the 3rd 2 to the third that's 8 that's how we can eat again and the rest is pretty much the same for numbers 3 &amp; is pretty much the same for numbers 3 &amp; is pretty much the same for numbers 3 &amp; 4 you know if I were you I would just practice the writing everything down just for practice or just to get a better understanding overall
XOR Operation in an Array
find-the-distance-value-between-two-arrays
You are given an integer `n` and an integer `start`. Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`. Return _the bitwise XOR of all elements of_ `nums`. **Example 1:** **Input:** n = 5, start = 0 **Output:** 8 **Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^ " corresponds to bitwise XOR operator. **Example 2:** **Input:** n = 4, start = 3 **Output:** 8 **Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8. **Constraints:** * `1 <= n <= 1000` * `0 <= start <= 1000` * `n == nums.length`
Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn).
Array,Two Pointers,Binary Search,Sorting
Easy
null
283
hello guys I hope you are all doing well in this video I will explain and show you how to solve the problem of zero so let's get started so the problem is that they give you an array of integers and they ask you to move all the zeros to the end of it while maintaining the relative order of the non-zero element relative order of the non-zero element relative order of the non-zero element and also we must do this in place without making a copy of the array means a constant space complexity so to solve this problem we're going to use the two pointer technique to iterate throughout the array of integers so here is how the technique gonna work the first point you're gonna be pointing at the first number in the array and also the second part you're gonna start at the first number and the array because there is a case when we only have integers that are not equal to zero inside the array so even if we swap them the pointer is going to be pointing at the same position so nothing gonna change so the second point we're gonna keep moving inside the array and searching for integers that are not equal to zero once we found it we swap the integer at the position of the first puncher with the integer at the current position of pointer of the second pointer and remove the first pointer to the next position so let's say we have this input array of integers we initialize two pointers the two pointer star at the integer zero then we're gonna Loop route the array using the second pointer so here the second integers are not zero so we swap him with the first integer 0 using the two pointer index then we move the two pointers one position so here to pointer two are pointing to an integer that's equal to zero so we don't need to do anything when we move the pointer 2 to the next integer we have three means we need to execute the swap technique between the two integers and then we move the two pointer one position and we have the number 12 so we swap them with the position of the puncher one and we stop the loop because we reach this is guys so let's jump out code in the solution first to initialize the eye pointer to be zero and the g pointer to be zero then we use the eye punch which is start a loop inside the array of integers and each time we check if the current integer is not equal to zero we swap the integer at index I we with the integer at index G then we increment the I pointer by 1 and the g pointer by 1 to keep track of the non-zero numbers and keep track of the non-zero numbers and keep track of the non-zero numbers and zeros so that's how we're gonna move all the right number in order to be the right and all the zeros to the left finally the function returned the modified array of integers so we can make the code more easier I don't know if it's more Azure complex we can start by initializing a pointer and then Loop over the nums and each time check if the nums are not equal to zero we change the current position using the pointer to be the current knob there that are not equal to zero and we keep repeating the same thing until we found all the integers that are not equal to zero then we initialize a second Loop inside the array starting at the position of the first pointer until the end and we change all the remaining numbers inside the array to 0 using the second pointer so you can use now the two pointer techniques you have seen how we can use it to come up with a solution it's easy so the time complexity for the solution is often because we are iterating throughout the array of integers once and the space complexity is all fun because we're modifying the array in place and we are not using an extra space inside the memory thanks for watching see you on the next video
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
1,732
hey guys welcome back to my channel and i'm back again with another really interesting coding interpretation video this time guys we are going to solve question number 1732 find the highest altitude before i start with the problem statement guys if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos let's get started with the problem statement now so basically guys there is a biker uh going on a road trip and this road trip contains n plus one points and all these points are at different attitudes okay so let's say the biker is starting a strip on point zero and at zero point the altitude is zero we are given an integer array in which every value of the integer array actually represents the gain the net altitude gain which is taken from the i minus one at point to ith point okay so for example if the biker started at point zero then when he went to point one then he gained a attitude of minus five points which means he really went down a valley and then in the next uh in the next point he gained a altitude of one point so if we see here the first point the altitude was zero then the altitude was minus five then he gained an altitude of unit one so minus five plus one becomes equals to minus four so his next altitude became minus four and then he gained an altitude of five so if you uh do minus four plus five he is right now at a height of one unit of uh one unit of height right and then he it was a flat surface so he went forward and the height gain was again the same so uh the altitude remain at one and then he went down so the altitude gain was minus seven and thereby in the end he is at an altitude of minus six points okay so if you see this array here the area of attitudes the highest attitude the biker has been there is the altitude of one and this is the value which we have to return another example here pretty much straight forward you can see the right hand started from magnitude 0 went to minus 4 then to minus 7 minus 9 10 minus 6 minus 3 minus 1 so he is basically going down and up but the point which he started from was the highest point so that's why the answer is 0 in this case the constraints are that the value of array the total amount of elements in the array range from 1 to 100 and the gain values range from minus 100 to plus 100 okay now let's get started with the solution part so we know that guys that we have to return a value of the highest altitude so let me create a variable here called as highest and i'm gonna uh by default make it to zero and we all know that the biker is starting from the default attitude of zero so let me create another variable here altitude becomes equals to zero now that we have our initialized variables already let's start with traversing the gain array so for integer i equals to zero to i less than gain dot length i plus simply what we have to do is traverse this array uh let me fix the bracket here so now we are traversing this array so we have to sum up the altitude of the gain value so attitude becomes equal to altitude plus the gain i value okay now we have to find out the maximum altitude so in the highest variable we are going to do math dot max either the attitude value or the highest value itself so using this line finally in the highest variable we will have the highest altitude and then in the end just return the highest altitude value let's run this code guys let's see if this works for our examples and there you go it works for one and hopefully yes so it works for all other example cases as well talking about the time complexity guys tom time complexity is order of n because we are going through a for loop of n elements and each element is traversed only once that's why the time complexity is order of n ah talking about the space complexity is order of one because we are not using any extra space here okay so that was the solution guys i hope you guys like the solution and i hope your coding practice became a little bit better with this if it has guys then please do not forget to like this video and share this video with your friends write down in the comment section below anything you want to say to me any feedback is definitely welcome uh please do subscribe to my channel if you have not yet subscribed and hit the bell icon for future notifications thank you so much for watching guys i'll see you guys in the next video until then take care and bye
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
494
hello everyone welcome to clean coder youtube channel so today we are going to solve this uh lead code problem number 494 which is target sum it's a medium level liquid problem so let's go through the problem statement quickly uh this problem says you are given an integer error in nums and an integer target you want to build an expression out of nums by adding one of the symbols plus and minus before each integer in nums and then concatenate all the integers okay so it has given an example uh numsaray 2 1 we can add a plus before 2 or a minus before 1 and concatenate them to build the expression plus 2 minus 1 and we did we need to return the number of different expressions that we can build which evaluates to target so they have also provided an example uh let's check the constraints first so the array length is between 1 to 20 and individual element ranges between 0 to 1 000 and sum of all the array elements is between 0 to 1 000 and the target parameter which they have provided uh that is between negative 1 000 to positive 1 000 so like from the constraint itself like the length of the array is really small so this is also giving an idea that even the optimized brute force solution would work or like dynamic programming is needs to be applied in this problem statement so no problem uh let's check the uh whiteboard and let's dive deep into the problem statement so this is the first example which they have provided to us right the example says that we have nums array uh there are five ones in this array and we have target three we can place a plus or a minus before each place basically we have five places okay we can either place a plus or a minus one here and so on and so forth and it just wants uh the number of ways in which we are able to obtain a target of 3 this is the target so we need to make the sum of all the individual places as this target and we want to compute the number of ways in which we can do this so this i have taken from the problem statement itself they have told that there are five ways to make three uh using this numbers array let's check out how like the first one is we place a negative at the first position and rest of them are positive so it gives a three similarly at second place we keep a negative one and rest of them are positive again it gives us sum of three similarly at third place there is a negative one and rest of them are positive it again gives three and so on and so forth uh so there are five ways in which we can obtain a sum of three so the answer of this test case is five the what would be the brute force solution we need to think of the brute force solution like how we can brute force this problem because from the constraint itself it looks like even the brute force solution would pass the uh problem statement so if we are given five places and we have five integers right we have this is a this b this c this is d this e okay these are the five integers okay so here there are only two possibilities what could come at the first position it would be either plus a or minus a right again at second position there are only two possibilities either plus b or minus b again at third position there are only two possibilities either plus c or minus c similarly plus d or minus d and plus c or minus e so out of all the permutation or what i say combinations all the combinations which i obtain i just want to return the combinations which yield the sum as target right which yield the sum as target i just want to do that so let's try to make the uh brute force tree uh like brute force how in how using brute force we can uh approach the problem statement so let me move to the next slide so this is the previous test case only and this is the target which i want to obtain this is target and this level signifies position 0 of the array like i can either place a plus one or a minus one right and this level signifies position one similarly this level signifies position two similarly this level okay signifies position 3 and the last level this signifies position 4. these are all the ways in which i can keep five numbers at five places right uh using plus and minus of that number right these are all the number of ways right what you can do is you can implement recursion and you can calculate uh all the parts which yield a sum of three so for example let's say i took plus one at first place okay it signifies this and then i again took plus one at second place it signifies this then i took a negative one okay it signifies this then again i took a plus one okay it signifies this then i again took a plus one it signifies this okay what is the sum obtained it's 3 right so the path in this tree is this right this is a valid answer so using all such valid answers i just need to return the number of ways using which i can make the target okay this is the problem statement in crux this is the crux of the problem statement so let's check some optimizations on this tree okay so this three i have drawn again in this slide you can see yourself that this sub tree plus 1 minus 1 this is getting repeated thrice right even more than that i have just marked these three places but it exists much more than this time so what this signifies is there is overlapping sub problem in this problem right these three if the if this answer i have computed here only i can skip these computations just by storing this result right so there exists a overlapping sub problem in this problem so i can write here overlapping sub problem so this part is clear let's move to the next slide okay so i have written the brute force solution for this problem and like if we are able to write the solution using recursion we can say that optimal substructure exists for that problem right so this is the solution i have written this is the brute force solution root force solution and uh what is this doing uh let me explain you line by line so find target somewhere this is given to us num zero is provided this is target s and auxiliary function i have made these nums is the array 0 is the index from which i am starting and 0 the next 0 signifies the sum which i have been able to make till that index and final s you can treat that as target which we are talking earlier so after that i'll jump in this function so there are two possibilities here one is positive one is negative so what positive one is doing nothing but it is adding that number to sum and sum i have initialized to zero so this is uh zero plus one kind of thing and what is the second uh branch negative one doing it is nothing but subtracting one from the sum okay something like this so this branch is signifying this okay so this will go on to recursion until this base condition is reached right when will this base condition reach either uh when i reach the end of the array like this base condition would get hit when i reach the end of the array when i is double equal to nums dot length and when i reach the end of the array if my target is equal to sum right the sum which i have accumulated here is equal to the target right what i can say that is a valid path that way will return me a valid uh combination so i am returning one in that case and in all other cases i am returning 0 so this is the brute force solution i just wanted to talk about and this is the optimal substructure in the problem so what we can conclude that the optimal substructure exists in the problem and there is also an overlapping sub problem that is present in this problem so using these two conditions we can say that we can optimize this using dynamic programming and we can write a better solution using dynamic programming so before that let's uh analyze the time and space complexity of this solution so time complexity of this solution is exponential which is clearly evident so time complexity is exponential in space complexity is order of n square so these are the time and space complexities so now let's try to write a better solution for this problem so i am going to optimize this using memoization because i find memoization a bit easier than writing a bottom up solution so i'll optimize my brute force solution using memoization technique so let's move to the next slide so this is the same function i'll say which i have shown you earlier i've just added a lookup kind of thing the lookup is this 2d matrix dp no problem let me explain you this two functions line by line so this 2d matrix dp i have initialized it to uh like the rows are nubs dot ln plus 1 and columns are 2009. uh i have taken this number uh you can take any number here but like this number is just sufficient for the constraints mentioned in the problem so i have taken this number so after that what is this part doing this is nothing but initializing this matrix each value of this matrix as positive infinity okay i'm initializing each uh value of this matrix as positive infinity after that what i'm doing i'm just calling this recursive function with the all the parameters same and now passing uh one more lookup or dp table dp matrix so what will happen is uh this would come in this function okay so this part this base condition is completely similar to the earlier brute force one the difference i would say is this what would happen like whenever a value exists in the dp table whenever the value exists in the dp table the value at this position dp of i and sum plus 1001 this won't be equal to positive infinity so this indicates that a valid value exists at this table at this position so in that case i am returning directly that value because that is the answer to the sub problem so i am returning this part and these two calls are completely similar now the only difference is this step right instead of directly returning uh whenever i have computed a value i'm storing that in the dp table so this is the only difference from the previous version so using these changes you would be able to optimize the brute force solution and the technique is memoization so let's see what is the time and space complexity now so time complexity now is of n square and space complexity is still the same which is of n square so we would we have been able to optimize this problem using uh dynamic programming memorization technique now let me show you the difference okay let me show you the difference these are my submissions so the top submission this one in this i have used memoization and you can see the runtime is only 18 millisecond and the previous one is brute force solution and you can see the runtime is 528 milliseconds so this is a massive improvement so this is all i wanted to talk about in this problem statement so if you liked my tutorial and if you have sticked still here please subscribe to my channel please like this video and please feel free to add any comments if you see any improvements or you have any suggestions please feel free to add them in the comment section thanks a lot for watching hey guys do check out this instagram channel clean coder community for all the jokes and memes related to software engineering thanks a lot you
Target Sum
target-sum
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`. Return the number of different **expressions** that you can build, which evaluates to `target`. **Example 1:** **Input:** nums = \[1,1,1,1,1\], target = 3 **Output:** 5 **Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 **Example 2:** **Input:** nums = \[1\], target = 1 **Output:** 1 **Constraints:** * `1 <= nums.length <= 20` * `0 <= nums[i] <= 1000` * `0 <= sum(nums[i]) <= 1000` * `-1000 <= target <= 1000`
null
Array,Dynamic Programming,Backtracking
Medium
282
283
hi everyone today we are going to solve the little question move zeros so you are given integer array numbers and move all 0 to the end of array while maintaining the relative order of the nonzero elements so let's see the example so you are given 0 1 0 3 12 and the output should be 1 3 12 0 so we need to move all 0 to the right like this and then also we need to keep the order of non-zero numbers non-zero numbers non-zero numbers like 1 3 12 so that's why output 3 1 3 12. and the most important thing is that we must do this in place so that means we cannot make a copy of the array so let me explain how to solve this question okay so i copy this input array from example one negative zero one zero three twelve so first of all um i initialize uh left pointer with zero so this left pointer is the location where we put the next nonzero number so basically i get it through all numbers like one by one and then when we find a non-zero number find a non-zero number find a non-zero number just swap the current number with the number at the left pointer so let's begin so we are now in excel this is a the client number is zero so we don't do anything just uh move next so now index is one so we find another number in that case um swap current number and the number at left pointer so swap like this so index 0 should be 1 and the index 1 should be 0. and then when we swap the numbers and just update the left pointer to next and then move next and then check the current number the number is zero so we don't do anything so move next so we find a nonzero number in the case swap the numbers three and the current left is index one so zero so swap the number like this so index one should be three and the index three should be zero so by the way our index two is a zero and then so we swap the numbers so update left number to next and then keep going so move next so again we find the nonzero number 12 so in that case swap the numbers like uh in the case index 2 and index 4 so like this so 12 is going to index 2 and index 2 going to index 4 and then move next but there is no number and stop working and then all we have to do is just a return input array so output should be 1 3 12 0 so we successfully all cells to the right place and then also we keep the order of non-zero numbers like a non-zero numbers like a non-zero numbers like a so original input array is like 1 3 12 so 1 3 12 we keep the order of numbers i think looks good so that is a basic idea to solve this question so with that being said let's jump into the code okay so let's sides are called actually it's not difficult so first of all initialize left pointer with zero and then start looping and taking index i in range and the length of input array and then as i explained earlier if current number is not zero in that case we need to swap so how can we swap the numbers so it's easy in person so like we can write like this so index i so current number and the number at least pointer equal and number at the left pointer and current number so we can write like this and then when we swap the numbers so update the left pointer to next so left last one so after exactly after that just return input array so let me submit it oh so we got error ah sorry typo nam sorry me summit again yeah so this solution works so time complexity of this solution should be order of n because i carry it to all numbers like one by one and the space complexity is one because i don't use like extra memory so let me summarize step by step algorithm this is a step-by-step algorithm of move this is a step-by-step algorithm of move this is a step-by-step algorithm of move zeros step one initialize left pointer with zero step two start looping super number at left pointer and the current number if the current number is non-zero and if the current number is non-zero and if the current number is non-zero and move left pointer to next only when you swap the numbers 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
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
334
Co whatsapp ka dubai apna talking about were elite problem ne and increasing classical okay and medium it kar koi problem hai account spoke very interesting hai via statement piece given interior alarms return to exit from up in this is jain with good spots pimple As per K A Viruddh R Also In The Interim Order Book On Main Ishq 97 Interested In You Have Provision For Its Rich Look And K Beej Ko Next Alarm Set Up The Light Off Kar Do Ki Kudi Implement Suresh Chandra Trans In Form Of Giving Time Complexity And Join This Page For Recipe Soy That Is Possible War Want In Space Free 209 Latest Result Department Ko Winter Below Simple And Lucid Affairs Us Loud Blackness 1972 Direction Shirish Kunder Indexes 2002 Edison Increasing Order So One To Three Acid Sir Morning Return Who- Which one go ok now my tablet servi spider-man my tablet servi spider-man my tablet servi spider-man 2 62f birthday in it roshni ko because i one is the minimum hello hair and 5s maximum hair as per in history decreasing order to right a for stay degree sudeshwar possible two for adultery performance pandey Map of a special Lata Anshu notice for this placement a wick in your name meaning and maximum 29 2007 I am giving you only that of light in English that Udaipur check everyone proper friends forget Navodaya a better than friend virudh and not copy e to pause Temple The Lord In Treatment Methoded In This Problem For It From Starting Index To The Independence Honge I Ulte Gandharva * Yudhishtar Two Drops I Ulte Gandharva * Yudhishtar Two Drops I Ulte Gandharva * Yudhishtar Two Drops There Greater Than 200 And Saying So One Should Find The Minimum Domestic Series Vitamin E Saw Google Play Store Minimum Gurus Ko on how to add widgets with oo how to reduce time minimum shari udhar greater than how to okay so absolutely sir maximum do mere ko maximum punishment thank you surya store maximum 21 minutes ago a very interesting things and avoid funtu 1100 * events of interim order Toe Any 1100 * events of interim order Toe Any 1100 * events of interim order Toe Any Damages Caused Great Dane Dog Girls That Download It You Sleep Record Abnormal Third 80 Feel Confident Enemy Shift Shyam Not Loose Nandish Limit Nodule Should Return For Cheese Is To Shampoo Ford Foundation Alarm Set's Speech For Any Individual In Return For More Lates Jaunga Code Hai Loot Hindi Song Paun Inch Mein Dekh Lo Main Surakshit Hota Hai Main English United Loot-Loot Italy Ko Abhi English United Loot-Loot Italy Ko Abhi English United Loot-Loot Italy Ko Abhi Minimum Ho Hello Friends I am That Aap Image Com Math Solve Ki Film Restore The Hindu Business Line Tracks Main Book Kar Two Hello Friends Kondagaon Satisfy His Friend That Friend Wish Them Ones He Defeated Light BCMO Dr The Fourth Addiction That Bigg Boss Finally Bigg Boss Right One To Three Years In 3D Model School Return How To Do Kar Do MP3 Song All Email Facility This Offer Water To Force In English Songs Saudi Aloo Telugu Dance For Kids From Disco Hua Hai Mein Ek Straight So Let's Suffer Ke Special Judge O Hai Coffee
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
138
hello friends welcome to joy of life so today we are going to look at another medium level problem from leadput the problem number is 138. the name of the problem is copy list with random pointer so it has a quite a long description so let's check it a link list of length n is given such that each node contains an additional random pointer which could point to any node in the list or to null okay uh construct a deep copy of the list the deep copy should consist of exactly n brand new nodes okay where each node has its value set to the value of its corresponding original node okay got it okay both the next and the random pointer of the new node should point to the new nodes in the copied list such that the pointers in the original list and copied list represent the same list state none of the pointers in the new list should point to nodes in the original list for example if there are two nodes x and y in the original list where x dot random points to y then for the corresponding two nodes x and y the copied list x dot random should point to y okay return the head of the copied linked list the linked list is represented in the input output as a list of n nodes each node is represented as a pair of value random index where val equals an integer representing node.val random index the index of the node.val random index the index of the node.val random index the index of the node range from 0 to n minus 1 that the random pointer points to or null if it does not point to any of the node your code will only be given the head of the original linked list okay and they have given some example so let's understand this example in little details so here i have a value so these are each nodes right these represent one node so each of the node like a linked list has a value and it has a pointer to the next node but it has a random pointer as well which can point to any node in the linked list including null and self as well so as you see over here that in the first node points to a null the second nodes random point to the first node so it might point anywhere it can it has no fixed order it can go anywhere and so what do we need to do we are supposed to do a deep copy of this linked list so we should be returning exactly a clone of this list which is a deep clone so deep clone means when i create this random should not go and point back to the original list it should remain in the same list so that is the problem all about so yeah this is the problem all about do give it a try there are a different type of solution available for this kind of problem is a linear time solution with constant space solution some knife solution so do give it a try before you check out the solution that we discussed here i plan to create multiple videos on this one at least discussing two of the solution two of the most optimal solution that i have in mind for this problem so let's move over to the board and check out how the solution looks so here i have taken an example and over here you can see that each of the node has three boxes the first one contains the value the second one contains the random pointer and the third one contains the next pointer so over here you can see that we are pointing the next pointer to the next node and the last node is pointing to null and the random seven is pointing to five twelve is pointing to eight four is pointing to himself uh five is pointing to twelve eight is pointing to seven so i have created this lesson we are going to look at how we can solve this so when you uh so first let's understand what is the biggest problem what is the problem that we are trying to address over here okay so what if we do a copy of the linkage link list that we generally do so what is the problem with that so the problem is that uh let's say i start creating the list so let's say this is the first note that i have created which corresponds to this one so what i'm going to do over here is i'm going to copy the value from this node right now what happens is 7 points to a random node which is not yet created in the new list right which is yet to be created so where do i point this node over here the next node where do i point this i have not created this linked list as of now so let's say i create the normal linked list let's not so let's look at the solution how we can approach this so let's say i start creating the list so i create the next node i am not creating the uh pointers as of now so i'm just constructing the nodes over here and i'm trying to put the value and the next pointer that's it for the time being okay so let us create that so what we do over here we copy the value 12 and what we do is we establish a link between these two right and i put the null to the last node so how do we populate the random pointer now so if i start iterating it all over again the old list so let's say this is my old list so let me put the names over here right so i have created this list but now how do i from seven how do i know that i have to point it to the node five right seven sevens random is pointing to five how do i know that and how do i locate that five over here so i should i start all over again looking for five so if i do that's going to give me a very bad complexity right so for each of the node over here i have to traverse this and entire linked list from start to the bottom so i find i get a 5 from this node say i search for 5 and i find the 5 and i put this link i get a 12 and i start all over again starting from the very first node and look everywhere where do i get a 8 so 12 is pointing to 8 right so i search for 8 and i do that so this makes the algorithm very inefficient right so basically for each of the nodes you are doing a search all over again so the complexity would go ahead and hit to a order of n square right for each of the node over here you are traversing this entire list so this has a nodes and for each node you are traversing the full list again so it's a n square time complexity we are getting so how can we improve this one how can we solve this problem so let's say when we are building this list over here so this is the first pass that we are building the list over here so at that time let's say what we do is we create a map and which holds the node to node what does this map contain so this map basically contains when i create this node when i created this node who is my counterpart in the new node i'll be storing that right so let's say we put some address to this nodes uh like since they have the same value so uh or let me just distinguish them with color so what i'll do is i will store a blue7 as a key and the value would be a yellow seven right so this is the period that we are storing seven to seven but i do remember they have a different address right because it's a new node that we have created over here only for 12 we are going to do the same thing we are going to put a yellow 12 mapping over here again for four so this is we are populating this map when we are creating this list itself right but we are not taking an extra iteration for this one so we'll start iterating this uh the old list say it's pointed by a variable n so what i'm going to simply do is i am going to use my lookup map over here the one that we have created over here so i am just going to tell him that map give me ends random so n is pointing to 7 right and let's see this list is denoted by n1 right so n dot random is denoted by the node 5 right and now when i do a map.get so right and now when i do a map.get so right and now when i do a map.get so when we do this operation on this node map dot get off and random what do we get so if you see this map so 5 will give me that new 5 right that mapping that we have created so we will get this 5 this yellow 5 over here so what we are going to do is we are going to set n1.random equals to that set n1.random equals to that set n1.random equals to that new 5 that we have got so what will essentially happen with that statement is this node over here will basically this so basically what will happen is we will establish the same mapping that we have over here right so you can see that we have replicated that relation so now let's do it for one more node rest all will follow so let's say for n also we do the same thing right so n points to 12 n dot random which is a constant time lookup points to eight and when we do a map dot get on uh this random so what does eight have yellow eight and we put that yellow eight to establish the relation between twelve and eight so what will happen is we are going to put this relationship back so same thing will happen for four points to itself right so if four points to itself then what is going to happen is we are going to get a four for four and we are going to point it back and again so for four what will happen is it will find to self and if you if a particular node has a null mapping also in that case also we are going to have that null mapping only in place just for your example over here so let's say i have a single node let's say i have a couple of nodes over here so there are two nodes so this guy's random points to null and this guy's a random point to this guy and this guy point to this guy and let's say this is one and two so when we create this mapping one will point to one two will point to two so two's next so two is random or once uh so once random what we'll get is a null and when we do a lookup using map dot get of a null and null is nowhere in this map what we are going to get is a null back from the map because this mapping does not exist so we are going to put that null into the new newly created node as well so for null we don't have to explicitly do anything it will be established by itself so first you are creating this list without the random pointer right so you are so let's put down over here the steps so first thing clone the list without the random pointer right create the lookup map and so these two are i have written with the same color because they are they'll be done as a part of the same iteration so this will be done in the iteration one now comes the second part so use the lookup map so we are going to iterate it again so iteration 2 this one is going to be so what will happen is we have a order of n for this entire list traversal creation and this is your runtime right and you are also going to take up some space and what is that space all about you are going to take that order of n space so if there are n nodes there will be n entries in your uh in your map which you are going to use for the lookup right and here runtime is again going to be order of n and space we are not taking any extra space so not applicable right so this is how it's going to look like so again order of 2n it will be your runtime and your space will be order of n so this is as you know that the constant doesn't matter over here so we are going to cut this off and we can simply say that both our runtime and our space complexity is order of n so we are going to go over to the lead code and quickly check it check out the solution so as discussed the first thing that we need is a map and it will store nodes so both the key and the values are nothing but nodes and we are going to call it lookup and let's say this is a hash map right so we have our lookup map ready over here and what i'm going to do is i am going to create a new head for the new list and let's say this is a new node we are not going to return this so basically what we can do is uh rather than calling it new 8 i can call it a fake head so this is just a fake node and the entire list will be appended on its back the new list so what i'll be doing at the end is i am going to return the fakehead.next okay so basically we are going to create a node this node is going to point to the old list so it's going to point to the head and we are going to have a new node as well which will point to the fake head right so next what we are going to do is we are going to iterate over this old list until we get a null so until the end of the list basically we are traversing the entire list to create node every time so let's call it temp and we are going to use the old nodes value right and it will point to new nodes next so this is where we establish only the next uh relation to the next pointer not the current random pointer this will be pointing to your temp and also we are going to populate the lookup map so we are going to put the node and the new node the corresponding mapping so this will ensure that we have this uh this thing established properly okay so once we are done with that what we are going to do is we are going to do a node so we have to iterate this node right to the next node so that's what we are doing so we just pointing it to the next so this is new node this is time the relationship is established now time should become the new node so let's do that also so new node is equals to temp so we are done with our first iteration where we have built the lookup map and we have created the uh list with the next pointer now we have to establish the random pointer part so again let's initialize it back to the same value and we are going to iterate again with the same condition while node not equals to null and what we are going to do is for the new node we have to set the random pointer in place so we are going to call the lookup map and do a get and we should check with the old nodes random right to get that value so we are passing that and getting it and now what we need to do is to increment both the list right so we have to do node.next node.next node.next as well as newnode.next right and at the end fake it so we are removing this and just passing the next one to it so this is the code all about so just let's run and see and there could be some errors so we'll fix them and move on okay so one big mistake new node we are putting the new node over here right so new node is assigned in a late state so what we'll do is we'll change it to temp or otherwise we could move the statement up also before this line either one is fine so let's run it and see again yep so our answer has been accepted and let's submit and check for a broader range of test cases well it has been accepted and we have a 0 millisecond faster than 100 of the submissions over here so that's a pretty decent thing order of a linear time solution with the in terms of both space and runtime and i'm going to create a video uh sooner uh maybe today itself wherein we are not using this order of extra space as well so um so maybe today i will be creating another video on the same topic and what we are going to do is we will avoid this so now what we have achieved is order of an order of n so there is a possibility that we can have it in constant space as well so we'll have a solution wherein we'll look at a solution wherein we'll be using no extra spaces the solution is going to be tricky you can try that as well i mean in the meantime the video is published and think of a solution that how we can come up with the same that's a very pretty interesting solution it's difficult to present something like that during an interview so i would recommend having a solution like this wherein the solution is very simple very neat very clean and very easy to explain as well so during interviews it's always recommended that you go ahead with a solution that you can finish within 30 minutes of your interview time talk about complexities run times and space complexities throughout the interview have some interaction with your interviewer so this solution fits into that space where we are not using much of um space also we are just using order of n space but definitely i'll make a video wherein we are using the constants uh extra space in order to come up with the solution so yeah that's all from this video so i will jump over to another video to create the solution without using any extra spaces the one that i have mentioned over here right so i am going to work on that and come up with that by the time this video is published maybe the other video will be available in couple of hours time i will put a card into this video at itself over here somewhere over here and also put a link in the description so that you can refer back to that and yeah that is all from this video do let me know what you think about the solution i feel this is a pretty cool solution a very neat clean and simple solution but i would like to hear from you guys what do you guys feel about the solution and yeah see you very soon again do look do like subscribe comment and keep supporting the channel thank you and have a great day see you soon bye
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
921
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 921 minimum add to make parentheses valid if you haven't seen my video on minimum remove to make parentheses valid i'd highly recommend you watch that video first because a lot of the concepts that we're going to use to solve this problem are actually going to be used in that problem uh and in parentheses questions in general so you should watch that one first or you can watch this one again although some of the explanations may not be as detailed because we went into quite uh depth in that question that being said let's read the question prompt you are given a parenthesis string s in one move you can insert a parenthesis at any position of the string for example if s equals left parenthesis right parentheses right parenthesis you can insert an opening parentheses um or a closing parenthesis at that point okay that's a terrible example elite code should really prove through these return the minimum example of moves required to make s valid so essentially what we want to do is we're given a string s and we want to insert the minimum number of parentheses we can for it to be a valid parenthesis string and remember that a valid parenthesis string is simply a string whose who all left parentheses are closed by right parentheses and vice versa so the approach that we're going to take to solve this problem is actually really similar to the approach we used for minimum remove uh to make a valid parenthesis in that we want to go from left to right of our string and we're gonna keep track of a left count and we're gonna keep track of a right count and this is going to keep track of you know the number of left parentheses we've seen and the number of right parentheses we've seen and this time we're going to keep track of the number of parentheses we had to add so this is initially going to be zero obviously we haven't seen any and this is zero and obviously added is also going to be zero so what we want to do here is we want to go from left to right and every time we see a left parenthesis we're going to take it in a greedy manner the reason for this is if we don't take a left parenthesis and it turns out we needed it later there's no way for us to go back so we have to take all the left parentheses that we see because we don't know whether they will be closed later on in the string we can only assume that they would be but we can't be for certain whereas with a right parenthesis we always know if a right parentheses is valid or not so if we look at the first um example here we have a left parenthesis then we have a right parenthesis and we know that this right parenthesis is valid because it has a left parenthesis before it that closes it and here the left count you know is one and the right count is also one then when we get to the second one we can see that because left count is actually equal to right count if we took this parentheses here then we would no longer have a valid string because there is no left parenthesis to close it in this case what we need to do when we have something like this where we can't take a right parenthesis then this is the case where we need to add a left parenthesis to close it and then we're simply going to continue through our string and close any right parentheses that should not have been opened in the first place so every time we get to a right parenthesis and the right count is not strictly less than the left count then what we have to do is add a parenthesis and in this case we're not going to count it uh as part of the right count then when we get to the end like i said you know we're going to be taking parentheses in a greedy manner right so if we look at you know example two you know we would take three left parentheses so at the end our left would be three but obviously you know we don't have a valid parenthesis string because there's none to close it and in this case right would be zero so at the end what we wanna do is to whatever we've added throughout the string we want to add you know the difference between uh the current left count and the right count so that will account for all of those right parentheses that we took in a greedy manner and then we'll add them back at the end because we never should have taken them in the first place and we need to close them with their corresponding right parentheses so that's the algorithm that we want to use it's relatively simple we're just going to go from left to right every time we see a left parenthesis we're gonna increment our left count by one every time we see a right parenthesis if the left count is strictly less than the right count then we say our count you know plus one otherwise that right parentheses is not valid and we're simply going to add one to our added count and continue we're not going to increment right count when the uh left count is actually less than the right count so or actually yeah uh or less than or equal to sorry yeah that's what i meant to say um and in that case we're going to add one to added and then at the very end the last thing we need to do is just account for all of the extra lefts that we may have taken greedily by adding the difference between the left count and the right count at the very end and that's how you're going to come up with your solution and that's going to be the minimum amount of parentheses that you need to add so hopefully that made sense if it didn't when we go into the code editor you're going to see it line by line and you know when we submit it you're going to see that this is actually the you know best solution we have here um so you know you can be rest assured that this is the algorithm that you want to use uh in your interview so we're going to go over to the code editor write the code and submit it make sure that it works okay i'll see you there we're in the code editor now let's write the code remember we're going to need a left count we're going to need a right count and we're going to keep track of the amount of parentheses that we've added so far when we're doing our iteration so let's set up those variables we're going to say left count equals to right count equals to added which is going to be equal to zero now remember what we need to do is we need to go left uh left to right from in our string so we're going to say four character in s we're gonna say if the character equals to a left parenthesis remember that we increment our left count and we take it greedily so we're gonna say l count plus equals to one otherwise we have a right parentheses and remember we can only take the right parentheses and increment right count if left count is strictly greater than the right count so we're going to say if our count is less than l count then what we want to do here is we want to take that right parenthesis because we can be sure that there's a left parenthesis to close it otherwise if there's no left parenthesis that closes it at this point then taking this right parenthesis would be invalid so that means that we need to add a left parenthesis here to close this right parenthesis otherwise obviously a parenthesis a right parenthesis can't be closed by a left parenthesis that comes after it has to be before it so that's why we need to insert a parenthesis at that point because we know that there's no you know left parentheses that could have closed it at that point if our count is less uh greater than or equal to left count so that's the reason why we are adding one here instead of incrementing the right count so we're going to say added plus equals 1 because we need to increment the added at this point because we need to add that left parenthesis and that's really all you have to do for the actual processing now remember we need to add the difference between left count and right count because we were taking left parentheses uh greedily um because we didn't know whether or not they would be closed by a right parentheses later down in the string now we can account for the fact that we have taken extra left parenthesis if we have even taken extra left parentheses and add them back in at the end so we're going to do that so we're going to say added we're going to add to added the difference between l count and right count right because if they're the same now and our string is fine then obviously you know the two numbers minus each other is just going to be zero so we're not really adding anything to zero in the case that l count equals our count it's only when left count is actually greater than our account and remember it's impossible for our count to be greater than left count because we never take a right parenthesis when you know uh our count is less than or greater than or equal to outcount we only append to added so our count will always be strictly less than left count so we don't have to worry about some sort of like negative number being added here if we do an addition here it will always be positive so last thing we need to do is simply return added and we can submit our solution and we shall see that it works so what is the time and space complexity for this algorithm well we need to go from left to right um through our string and process every single character in it so this is just going to be a pretty standard big o of n operation where you know we are bounded by you know the size of s so that's just going to be a big o of n uh runtime and for the space complexity we're not actually defining any sort of data structures we just have three kind of you know placeholder values which are just holding the integer counts for left count right count and added those are all going to be constant space allocations so we're not actually using any space here it's just going to be a constant space allocation and you know that's going to be your most optimal algorithm you cannot do better than this and this is you know what your interviewer is looking for so hopefully you enjoyed this solution video if you did please leave a like comment subscribe if there's any videos you'd like me to make or topics you'd like me to cover or interview tips or anything like that please do let me know in the comment section below i'm more than happy to make these videos for you guys but i just need to know what you want to see so i can go ahead and make the video that being said um good luck with your elite coding preparation and bye
Minimum Add to Make Parentheses Valid
spiral-matrix-iii
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string. * For example, if `s = "())) "`, you can insert an opening parenthesis to be `"(**(**))) "` or a closing parenthesis to be `"())**)**) "`. Return _the minimum number of moves required to make_ `s` _valid_. **Example 1:** **Input:** s = "()) " **Output:** 1 **Example 2:** **Input:** s = "((( " **Output:** 3 **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'('` or `')'`.
null
Array,Matrix,Simulation
Medium
54,59
1,759
hello welcome back today let's try to serve another liquid problem 1759 called number of homogenous substance so for this problem the homogeneous system is all characters of three that are same and the substrate is a contiguous sequence of the characters with inner string it means for example this is CCC as contiguous and for this PP is also contiguous and they are the same characters so for this we gonna call it we're going to call it homo centers string so we're going to need the two code how many of them so in total there are 13. so normally for this kind of a problem it is a list groups problem for example we're going to list how many A's and for B and B we're gonna code how many bits and for the CCC we're going to code how many cities why it is made by a medium problem normally it's such kind of problems would be easy problem only because we are giving we need to return a modular so 10 to the power of 9 plus 7 for this one you need to take care if you forget yeah it will be wrong and for another case is you need to do code like numbers three through three if you have a three consecutive threes you need to count how many of them normally for this one it is one plus two plus three for the formula you need to get familiar with it basically this is just the high school mathematics knowledge and for because there are you need three so when you call the unique three there are three when you cut this consecutive three and three there are two and then you count three there's only one so this is y one plus two plus three yeah and you also need to know the Formula 1 plus 2 plus 3 until plus 2N it should be equal to let me write this some see more until plus you need to get familiar with the high school mathematics formula so it should be a times n plus 1 divided by two yeah basically this is just it's not so difficult now let me start my coding so let me write the template so for the result it is faster number so it's a counter and I'm going to prepare iporter and a number n so n is the length of the string so the result as I said is counter it will be start from 0 and index will start from 0 and N is the length of the screen now and the template while loop so while I less than foreign let me wait for a few seconds yeah it's really slow so this is the outer while loop now I'm going to prepare a start should equal to I and then the inner Loops will be I less than and minus one and nums I It's it's not nums so s i equal to s i Plus 1. if there is a true I'm going to set it as I by 1. now I'm going to count the length of the consecutive numbers so say should equal to I minus start plus one now I'm going to count to the result so it will be in this formula so it will be say times say plus 1 divided by 2. after that I'm going to update my I to the right side by one place now I'm going to return the result now let me submit a little tag if it really works yeah this is because as I said there's a modular so the result should be modular my mod so the mod will be this number will be 10 to the power of 9 plus 7 so indeed code the modular is always this number so it should be plus seven now let me submit it again to tag if it can pass all the testing cases yeah let's first beautiful a few seconds and by the way the time complexity is the first one even here we use the some calculations but basically it is a soft01 strictly speaking it may be O3 or o4 for the times for the plus it is o1 but it is still a 01 for the catalysis and here even we have two while loop basically the I just Loop through first of all the I accepted from 0 to n minus 1 and the start is a software record as you can see it passed and it's pretty fast same thing for watching if you think this is helpful please like And subscribe I will upload the money called permanent success see you next time
Count Number of Homogenous Substrings
find-the-missing-ids
Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`. A string is **homogenous** if all the characters of the string are the same. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "abbcccaa " **Output:** 13 **Explanation:** The homogenous substrings are listed as below: "a " appears 3 times. "aa " appears 1 time. "b " appears 2 times. "bb " appears 1 time. "c " appears 3 times. "cc " appears 2 times. "ccc " appears 1 time. 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. **Example 2:** **Input:** s = "xy " **Output:** 2 **Explanation:** The homogenous substrings are "x " and "y ". **Example 3:** **Input:** s = "zzzzz " **Output:** 15 **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase letters.
null
Database
Medium
1357,1420,1467
926
Hee gas welcome back to my channel so today our problem is Philip Sting you are monotone increasing so this problem statement bay what have you given us here you have given us a binary sting in which you will not only have zeros and ones but okay what do you have to do Here you have to flip SI, in flip you can convert from zero to WAN, from WAN you can convert to zero, basically what you have to do is here you have to convert S into string in monotone increasing i.e. what should be your i.e. what should be your i.e. what should be your If there is 01 at the beginning in the string, then see if there is zero van in the string, then what will be there in the initial, there will be only zero, after that whatever will be van, then you can see here what is given here, this string is given ok. And here we can convert it into this string, which is a mono door in increasing. Okay, so how many flips have you had to do this, so you have to try to do the minimum flip up and what to do with that. Change it to monotone increasing string. Okay, so what do we do? Let us understand through the example what is the problem and how can we solve it. So in the first example, you see what we have given to you, give zero one van zero. Okay, now what you have to do is change it to monitor increasing, so here we can flip the van to zero to van, so you have to do the minimum tree, so if you change it to van, then this What will become zero van i.e. if you had to do only one flip then you did the i.e. if you had to do only one flip then you did the i.e. if you had to do only one flip then you did the minimum flip here so what will be the answer your van will be ok now let us also look at the second example zero van zero ok now what do we have to do with this flip Okay, so how can we do it here, so look here, what is there, you can make zero into van, you can make van into zero, if you make it van here, then all will have to be man. This zero will also have to be done. Okay, so if you do zero in van, then you will have to do three. Okay, and this has been done in van. 000 means these two, still you will have to do three, so what is the minimum? Yours became two. Okay, so in this way, what will be the answer here? What will be your two? Is there zero in it, zero van zero, there is zero later too, that is, if you convert 0 now into van, then you will have to do this also, not here. If you have to do it, you will have to do it here, then it will be in increasing right, so if you do it here, you will have to do three here. Okay, if you just convert these two vans into zero, then all the 0's will become 0 here. So you have to do only two, so what will we do here? Without DP, how will we solve this problem? Look, what is the meaning of momentum increasing? Here, you may have only zero in the string, only one or if zero. If van remains then it should be in increasing order. Okay, after 00 there should be 11, so what we will do here is that if zero comes after van, then we will flip the zero to the zero. Okay, so here. Look, it is zero, it is van, it is zero, it is right, we will leave it, when van A goes, then after van, when zero A goes, then what will we do with it, we will convert it by van, okay, we will do it if you come to know. That here you have gone and done three or four flips, you have done it in the van in zero and here you have only two or one van, here on the left side, if we had flipped it then it would have been less, okay, I am using the example. Through samjhaungi, how to see what is here, basically what will be our logic that if we do not come zero then we will let it be, if van has not come and after van, zero has come, which is your monitone, if it is not there, then after van, if zero has come. When it comes, we will try to convert it into van. Okay, so what will we do here? Next, there is zero, we will increase next, there is 0, here there is van, okay, we got one count of van, okay, then here we got it, we got two counts. When we come here, we will check whether the van's part was found here, did you find it, what does it mean that there is no van on its left side, so what do we do, we convert it into a van also. How many flips have you done in the van? Here you have converted zero to van by doing van. You have converted one to one here, hence one is your count. If you had thought in this way that you would have converted your van by converting zero into van and then converting zero into van. How much did you have to do to make it zero, how much count off did you get, here is the total count of van, you got it in coming till here, then it is better to do flip van, otherwise what will we do, let it be flip van only and We will return it, okay, now we come here, this thing will be clear after going here, okay for you, we start from here, what about us is that as long as we get zero in the initial, it is okay, if we get zero after van, then we will try to It's okay to flip the zero here, there is van, here, there is zero here, there is van, so the account of van is now found, okay, when we move ahead, there is zero, so we know that there is a count of van, it means there is van on the left of it. So what do we do, we flip it, if we do it, then how much will be the count of flip? Van, you have supported it, convert it into Van, okay, after that, if you come here, then come to Van, you are their account here. Pay is three, okay then you come here, you know that this side is okay, if you want that you are converting the van to zero, then till this far you will have to do three, okay, so which one is less. If we have to do it from zero to van, then what will we do about the return? Here, here we will return the tour. The answer is also yours, what are you? Okay, now let's come to this example. Look through this example. 00 1100 So what are we doing? As long as we get zero here, we are moving ahead, go ahead, big, if we get a van here, what will we do about counting the van, will we keep the van in the van, then we will move ahead, it will be you, when we come here, we will understand that we are not here. If we have got the van, then this side will be zero here, because if we have to convert it in the mountain increasing, then somewhere we will have to do it, so the count of flip has become van, okay, if we do one van, then two have to do it now. Till here, only the van had to do it. Okay, then move ahead. So you know which side is the van. Okay, if there is a van, then let's flip it. So, if Zero had to be flipped, then if the van had to do it, then the van would also have to do it. You had to do it but again you got zero i.e. you came to but again you got zero i.e. you came to but again you got zero i.e. you came to know that you have to flip zero only three times and you can flip van only twice. Which of the two is less, if it is less then what is the return name? You will do 2, you will do it, okay see what you have to do, from zero to van. If you want to do it from van to zero, then on whom will we decide, the one who gets less, the one who has to reduce, we will do it, so you have come till here, so now two Philip's. Like when you come here you come to know that you have to flip three, then it is better for me to flip it, otherwise we will see the minimum, who is the minimum among the two till now, we will take the one which is minimum, so this is the minimum. You will turn this to us, if we convert it then it can be converted like this, okay, it is better than these three, it is better to convert these two to zero, then your amount and increasing will also change, so what do you do once? Let's look at the code, see here what we have done, we have taken two variables, Kant flv and Kant van, OK, we have taken the loop. We will first see got, that is, after van, if you look here, we have got zero. It is correct if van is your greater than zero. Is the date main, if you have got the van here before coming to zero, then this is your amount and increasing, otherwise what will we do, we will flip it, okay we will flip plus, then we will check here only, do you know who is better to buy the van? Flipping or flipping 0 then count van if your less give is count that means you have flipped the video more than this what is better to do than you flip the count van to zero so what will we do Flipping the ears which is count We will make it equal to the van, okay, in this way we will go till the last, the one who will get less in the conflict, if we make us equal, then what will be the time complexity of the van because we have done only one look at it and what will be the space complexity, that will be the van. Right, I hope you have understood this. If you liked the video, please like, share and subscribe. Thank you.
Flip String to Monotone Increasing
find-and-replace-pattern
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Array,Hash Table,String
Medium
null
24
hi guys welcome back to the channel today we are back with another very famous question today's question is swept notes in pairs given a linked list swept every two adjacent nodes and returned its head you may not modify the values in the list nodes only nodes itself may be changed so we are given with an example one two three four you should return to and one four and three so we are swapping two and one and three and four so it is a very easy question just few lines of code we will first do it on pen and paper after that you write the code so we are given with the linked list one two three and four and we need to return like this what we can do to achieve this thing as our output so our head is pointing here suppose I say that we are taking a dummy node over here so we are taking dummy node at zero and this is our P and this is our Q so what will be the value P will is gonna be due to next and Q will gonna be D dot next or next over you can say P dope next and D dot next is head because the head is here so this was our initial English first our aim is to swipe this bill and we have the minute over to what we should do with these three pointers that it will give us this thing so we need to do something with these three-pointers so let me with these three-pointers so let me with these three-pointers so let me write down here we need to take care of d dot next P dot next and Q dot next this is a tea this is our P this is our cue what I do with this pointer that we get this thing to me I need to point it to Q it was too easy Q what I need to do with this pointer so that I can get this thing so it's pointing to this value which is Q dot next and what I need to do with Q dot next which is this point I need to make it here that it points at one so cute Annette next will point to P so we are done with this weapon so if I say our result will after first iteration will be after first this line of code will be like this and now our P is here Q is here and D is here and we are done with this part but we are remaining with this part and so on so what we're gonna do to do on this part we need to have P over here Q and T over here so that again we can apply these things so ad then what we're going to do we'll make a equal to P so here now our D will be at this position this will gonna be out of me no and now again we will do this operation in this 3 &amp; 4 so will do this operation in this 3 &amp; 4 so will do this operation in this 3 &amp; 4 so this is the only dish of the problem please try it by yourself and then come to the go and let me tell you one more thing till what time you will gonna do these things while d dot next and du dot next or next is note none or you can say till the time P and Q or not none we will gonna keep doing this for step and at then we will get our answer so let's first make off dummy node so we are making two dummy node so that because at the end we need to return something it is not very chill and do dot next good point to hat because it's a singly linked list so we don't have any things are such previous so why do to the next end do you doubt next is not what we want to do we will simply be equal to T rotten X and Q equal to P dot next or you can send Dido next and now come those three things to change the point oh dude open X P dot next and Q root X so we need to chase these three pointers dude open X P dot next and Q dot next to Q dot next then P respectively do you do next to Q P dot next to Q root next and Q dot next to be under then we will take care of our dummy value we will again put it equal to P and then we will return D 1 dot next because that in the starting we took these two and we are just returning did out next with it's a dummy node we don't want P to print so let's see the answer is correct and it's yeah it's a pretty good answer and I would say please try it by yourself and if you any problem please to let us know in the comment section I will try my level best to help you out and please don't forget to subscribe thank you
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[2,1,4,3\] **Example 2:** **Input:** head = \[\] **Output:** \[\] **Example 3:** **Input:** head = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. * `0 <= Node.val <= 100`
null
Linked List,Recursion
Medium
25,528
1,817
hello everyone welcome to another video now in this video we are going to look at another arrays medium level question now although it says it is although it is tagged in arrays but it is more of a map and set kind of question so let's jump into the question what it says and then we'll try to uh understand like how we are going to solve this so I have already written what the first example and what it says so we'll understand it by the example so what we are given here is that we are given an array to the array and it has each array inside the array has two has an array with two values so one is going to be the ID and second is going to be minute now what is our this ID is so if you see this ID it indicates that this user ID was active at this particular minute okay that is what it says so zero was activated five fifth minute one was active as second minute and so on so what we want to find over here is that we need to find the unique active minutes of a user okay first thing that we need to find is a unique active minutes of a user okay and what is the total unique active minute of the of a user and how many users had that many total active minutes it is complex to understand so let's break it down so let's say we have zero index we have one index zero one okay we have only two IDs right now zero was active at fifth minute one was activated second minute zero was activated second minute zeros is activated fifth minute but since we already have fifth minute it is not unique so we are not going to add it again and one was activate third minute okay so this is our ID this is our unique active minutes okay these are the unique active minutes how many unique active minutes are there two for this also to one two okay now how many users have this unique activity one two okay this we have to add in our answer array how are we going to add this okay how are we going to add this so basically what they're asking is that this answer array it is one indexed array that means it starts from 1. okay and we have to find the total number of users with unique active minutes equals to this index okay so how many users have unique active minutes as one so we have two we do not have any one right so this is going to be 0. how many users have unique active minutes too so we have 1 and 2 this is two how many do we have two so we are going to write it 2. do we have any three no four no five no okay it is really that simple if you did not understood this let's take another example number two that is given to us this is going to change and this will also change this K it signifies the length of our answer okay the second example it is given four one two three how many IDs do we have one and two what is the unique active minutes for one only one for two it is two and three okay how many unique active minutes this have one how many unique equivalents this has 2 1 2 okay now we need to find this value how many total users have unique active minutes equals to one we have only one so we are going to write it one over here how many users have unique active minutes too we have only two here okay only one value so we're going to write 1. for 3 we do not have any three four also we do not have any 4. okay so I hope you understood this what the question is asking for okay now let's jump into the uh theory part like how are we going to solve this so um if you see over here let me write it down again 0 and the first example okay 2 and 5 2 and 3 okay this looks like a map okay well this is our key and this is our value okay also if you will see the value that we have it is in the form of a set because we want only unique elements okay so for that what we are going to do is that we'll create a map whose key is going to be integer and whose value is going to be a set okay and what we'll do is that whatever value do we get at this particular key will add it in the set okay so at the end we will get a map of 2 comma 5 1 is going to 0.22 comma 3. okay and 5 1 is going to 0.22 comma 3. okay and 5 1 is going to 0.22 comma 3. okay and at the after this what we are going to do let me write it down the answer is going to be one two three four five okay we will find the size of this and will decrement minus like decrement one value y1 because this is one indexed okay no matter what kind of index the question is asking for the computer is always going to take the array as 0 indexed okay so for Value 2 we want to insert the value at index one that's why we are negating 1 over here okay and we will in the size of this will add it to that particular uh value sorry we'll find the size and negate one and at that particular index will increment a value so this is 2 right now okay 2 minus 1 is 1 so index 1 will increment we find another two we'll negate 1 that is one again will increment so this will become 2. all other values are going to be 0. okay now I hope you understood this and you can try to code it by yourself it's really simple uh if not then we can jump into the code part okay so let's go through that okay so the first thing that we need over here is our result Vector right so let's create that okay and I'm also going to specify the size that is going to be k now the next thing that we need over here is our map okay so let me create that as well and it is going to have set okay and this is going to be and let me say this as m okay now another thing that we need to do is that we let's go through our logs okay so what we are going to do is that I will go I'll do the for each Loop right okay and I will go to logs and what we'll do here is that at index of map which one temp of zero because this is our ID right I will insert temp of 1. okay it's really that simple and our half of the task is already done and after this what we'll do we'll go through our map how are you going to do that since this map is nothing but a pair right so I will create that pair of paint comma set of end okay let me see the system and we are going to go to our map okay now we need to add in our result at what value so first we'll go to the temp and temps second value okay second is our set right so we'll go through second dot size minus one and we will increment this okay and at the end I will simply return our result so it's done let me submit this okay so it's really that simple and it's really that easy all we need to do all we needed to do was to understand how the map and set works so yeah I hope you like this and understood this and you learned something new and yeah that's it for this video and do let me know if you have any other problems for me to solve something in the platform thank you for watching I will see you in the next one till then keep coding
Finding the Users Active Minutes
calculate-money-in-leetcode-bank
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Math
Easy
null
797
hey hello there let's talk about today's liquidity challenge question all passes from source to target given the directed acyclic graph dag we want to find all possible paths from node 0 to n minus 1 and return them in any order so it's obviously a graph problem and we're dealing with stack so the input to us is the adjacency list representing the outgoing edges so if you look at the first entry one and two that means node zero has outgoing edge towards node one and they also have an outgoing edge towards node two uh so that's the input to us and the acyclic part is a guarantee that there is no cycle in the graph so whenever we whatever traversal strategy that we pick dfs or bfs if we follow that to explore the graph there's no way we're going to end up in an infinite loop in there so we don't have to worry about that it's just which is nice a couple more things to talk about uh based on the problem text is that we want to find all the possible passwords from a given node to the target node so for that reason we want to use dfs rather than bfs because we're not looking for the shortest path if we're looking for the shortest path we want to use bfs so we can terminate early but if we really want to explore all the graph then dfs is going to give us a better space less space requirement because bfs you know all the temporary paths is going to be stored in there and you just end up using a lot of space but for dfs all you have is the current path so currently past your exploring so it's much less space and one last thing is that it's not really counting the number of unique ways from 0 to n minus 1. if you just do counting all you need is just the node you don't have to keep track of the prior path to that given node so since that we really want to keep a history of the traverse we want to use backtracking so that's the analysis on the problem let's talk about this time complexity because in the worst case the graph is fully connected every node is connecting to every other node inside this graph and then we're looking from the starting 0 to n minus 1. so there are n minus 2 total nodes in between and since it's a fully connected graph the we pretty got much gonna uh all the possible paths here are gonna leads to from zero to n minus one so the total for that is just enumerating over all the possibilities by turning on including or excluding one of the node inside this path so the total is going to be 2 to the power of n minus 2 unique different passes in the worst case and for every pass it takes an order of n time to generate that so that's just approximately 2 to the n multiplied by n that's the time complexity so that's the time complexity and for pa for space complexity if we use dfs it's going to be order of n we only keep the current path that we are exploring so that's uh that's why dfs or backtracking is given better space for bfs is going to be a lot worse and this is this space requirement is excluding the space required to hold the return returned passes so if we keep track if you also count that in that would be 2 to the n multiplied by n it would be the same value as the time complexity so with that i'm just going to dive into the code here so we use a list to container to store all the possible passes and what else do we need to find the number of nodes inside this graph because we are given the adjacency list and it's full so it's just going to be the length of it and yeah we're just going to call the backtrack on the initial candidate pass which is the initial node 0. so that's pretty much the skeleton of the code all the detail is going to be in this backtrack procedure it's taking a candidate pass here so the criteria that we promote this candidate to the final solution is that it ends up with the target node we want so that's the last node here if it's n minus one then we want to put this path onto the collection and then return and that we have to make a physical copy because otherwise it will be if we just append a pointer to this list it's going to be changed later on in the code so that's why we created a physical copy that's order of end time to do this otherwise we're going to expand the candidate paths by exploring all the possible nodes we can go from the last node here so that just means that we have a number of different choices that we can do at this given time so that's looking at from the latest node in the past in the temporary candidate pass where can we go next so for each of those choices we append that node to the temporary candidate pass and call this backtracking on the expanded candidate pass and after that we want to remove that so this should be it yeah so the code is pretty clean actually yeah just initialize the container to hold all the passes and we start with a candidate path that's just the starting node in each back tracking call we determine whether the candidate pass can be promoted to a legit path from node 0 to a minus 1 by checking the very last node in the temporary pass if it's n minus 1 the last node that we're looking for we add that to the container and return from the backtrack otherwise we'll use that last node to guide us towards all the possible next positions expand the candidate paths by adding that new node called backtracking again after that we're going to pop it off to restore the original candidate path so the space here if we exclude the space requirement for the pass here it's going to be only this candidate here it's going to be order of n um and the backtracking car in the stockhold will be also of rfn so it's a linear with respect to the number of nodes uh so that's what i put it here and the time is this one 2 to the n multiplied by n that's the worst case when everything is interconnected with each other so there are 2 to the power of n minus 2 different passes from 0 to n minus 1. and each of those would take end time to generate also take end time to copy over the worst cases take in order of end time to copy it onto the pass so that's the time and space analysis for the problem uh yeah
All Paths From Source to Target
rabbits-in-forest
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**. The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`). **Example 1:** **Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\] **Output:** \[\[0,1,3\],\[0,2,3\]\] **Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. **Example 2:** **Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\] **Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\] **Constraints:** * `n == graph.length` * `2 <= n <= 15` * `0 <= graph[i][j] < n` * `graph[i][j] != i` (i.e., there will be no self-loops). * All the elements of `graph[i]` are **unique**. * The input graph is **guaranteed** to be a **DAG**.
null
Array,Hash Table,Math,Greedy
Medium
null
18
foreign and welcome back to another YouTube video so today I'll be following the lead code question for thumb okay so one thing I would really recommend before going on with the solution to this is I would highly recommend that you first solve the previous questions that are twosome and threesome I have made videos for both of them as well if you want to check them out but I would really recommend first doing those two questions because when you do those you would try to you will be able to come up with a pattern to solve this question as well but yeah so that being said let's start on with this question so like the previous questions the goal is to find quadruplets so four unique numbers such that when you add all of them they equal to the Target that is provided so in this case for example we have these numbers and we're supposed to find quadruplets such that when you add them you get a target of zero okay that's the goal pretty simple question but now let's actually see how we're going to solve this okay so we're going to start off before actually showing you the example we want to I want to First just go through the previous questions so let's say you have two some now the goal here is you have to find two numbers that add up to a Target now how do we solve this so the way we solve this is we first assumed that we're going to take a number and then based on that we look for a number X and this number X is nothing else but the target minus the assumed number so essentially we assume that we when we come across a number we assume we have that and then when we come across the number X which is the target minus that number that means that we've found a pair right so essentially for the two thumb problem well all we did is by assuming one number we're only looking for one extra value right so now let's look at presum in this case what do we do so the way we solve three sum is we assumed one number okay and then what we did is we so the remaining nums that we had so uh let's just call this the remaining numbers this was treated as the twosome problem essentially from this we assumed another number let's say x and then we just found the last missing value okay so essentially at this point we had a number well and so we had this number dot plus two other values X and Y let's call it which equals to Target then we simplified it even more by assuming a value for x and then we were only looking for the value y so essentially we just kept breaking it down so that we're not looking for three numbers instead at a specific time we are just looking for one extra number so now let's try to follow this pattern and do the same thing for four thumb okay so essentially what we're going to do is we have to look for quadruplets and I will just assume them to be x y z and let's say a sorry called n a and this is equal to Target okay so first thing that we would do is we would assume a value X okay so I'll just do this alongside so let's say we assume the value one so we know the value 1 is going to be there now what we do is we look at the remaining numbers what are the remaining numbers well these are the remaining numbers okay so 0 negative 1 0 negative two and two now what happens is the target changes so now we have a value for y and we're only searching for y set and a right so now what we do is instead of searching for uh X Plus y plus Z plus a equals the Target now what we search for is y plus Z plus a is equal to Target minus X okay and now we basically update the target to beat Target minus X this is what we're searching for okay now this is the same and we're searching for three numbers this is the same as three sum right so now we assume the value of y okay and we do the same thing and then we look at the remaining numbers so let's say we assume a value of y to be zero right so in this case the remaining values are negative one zero negative two and two again that's it okay so now uh we have the values of X and Y and now we update our Target again so the Target that we're looking for is Target minus x minus y we're only looking for the values of Z and a or is that an a right so now we do the same thing we assume a value for Z and we look for the value of a so a is essentially all we're looking for now what we're going to do is we're going to kind of back propagate sorry like just go back each step now let's say we found a value for a over here that also means we have found a value for this because by so now let's say we have a value for a okay so let's just break it down so for Target minus x minus y let's say we found a valid a and set okay so now we want to find a value for Target minus X well that is nothing else but the same A and Z Plus the value y so that will give us Target minus X that's it and if you don't believe me on that it's a plus Z is equal to Target minus x minus y and just by simple algebra if you add y on both sides this is going to cancel out right so that's it we're just going back each step now we go back another step so now instead of Target minus X if you want to get the entire Target all we have to do is add X on both sides this is a plus Z Plus y plus X that's it that is going to be our solution for four thumb so hopefully that makes sense and if you could uh I would highly recommend trying this out once on a array and you should get a solution so this is all we're going to implement and I'm not going to do this by hand because I feel like looking at the code does make it a lot more clear but now there's going to be a small problem now this question has clearly told us that we want unique values so this is small so we could do so a basic naive solution for this is that we could get the results we could sort all of the individual results and then we can remove all of the ones that are repeating obviously we could do that but let's try to look for a solution without doing that so and what we could do is we could just sort this okay uh show you what I'm trying to prove so let me just sort the value so that's negative to negative one zero one and two cool um yeah cool okay so now what we're gonna do is let's say we assume the first value to be zero let's do zero okay because there is a repetition for zero so let's say this is X now what is the goal here actually just to make it simpler I will add a value three and I will add a Target I'll make the target uh let's say five okay in this case so essentially what I'm going to prove is that let's say I chose the first number to be zero X is zero now I'm finding the other three numbers so for this case obviously a possible solution would just be zero two three so now what happens is let's say now I go to another zero over here in this case well actually I don't even get to the Target file but this is the sake of it let's say I add another zero here so in this case I would get the same solution right so these are the numbers I'm considering so I would get the exact same solution 0 2 3. now both of them are valid but again I do I only want unique Solutions so how do I fix this problem so this is nice simple fix that we could do because the numbers are sorted all of the numbers would be clumped together right so all the zeros would be together so if at any point we have found a solution for so let's say first we found the first solution with the first zero obviously so any zero after that right so if we go over here or if we go over here no matter what we either come up with the same solution or we don't come up with a solution at all okay so that is the essential point over here so this is exactly what we're going to try to do and uh what we're essentially going to do is that each time is let's say we found a solution with this zero now the next number is zero again since we have found a solution with a0 right we found it with one of the zeros the solution with the next zero is either going to be the same or it's not going to exist so there's no point of checking it at all so we're just going to skip it okay so that is exactly how we're going to solve this problem of not having unique Solutions uh cool and essentially uh the same thing that I showed you by just choosing one number the same thing works with the two sum and threesome approach as well right so let's say I finalize this is X and this is why I would do the same thing in this case right so for this y uh that I chose over here I would get the same solution uh if I'm at this zero so what I mean by that is let's say I'm searching for two numbers that add up to five that's three and two out the same rule right so I would look for a solution with the zero and since I found it two and three the next number is also the same number so in that case I would either get the same solution or no solution at all so I could just stop right so let's take a look at the code now okay so the first thing we're going to do is so first we're going to break this problem down right so now we're gonna essentially we're solving for three sum right so let's do that so we're going to get index one comma index two and enumerate nums cool okay so now essentially what we're doing over here is we are assuming the first value think of this as the X this is the first number we have assumed so now what we're going to do is we're going to look at a new Target okay so Target one and this is going to be our new Target so this is nothing else but the original Target that we have over here minus num1 again all that is doing is I'm assuming I have taken this number and I am now going to instead of doing four sum and looking for four numbers I'm only going to look for three numbers but for Target one okay so let's write a comments so uh three sum for Target one that's essentially all we're going to do right now okay so now we're gonna have another for Loop so I'll just do this for index two and num2 in uh enumerate cool so in this case now what I'm going to do is I'm going to get a new Target so this is Target 2 and this is going to be Target one minus num2 okay so what exactly does this mean again so this is the same thing again I'm breaking it down even more so essentially now I've made it a two thumb problem but for Target Two okay so just real quickly I've assumed the number one first and then I have assumed the number two that's it right and now I'm just doing two thumb which is something we've solved earlier and it's a lot easier to solve right we're just breaking it down okay now let's actually write the code properly right so or in this case we get these values now one thing that we have to be very careful for is in this case do we have to search all of the values well no because let's say we get to the last uh three values right we're looking for four values so there's no point of going up to the last value so we could just go up to the last uh but three values okay so up to negative three so there's that um now another thing that we would do is uh same thing over here is the simple thing you would do is you just do index one plus one all the way to the ending but again same thing over here we don't have to go all the way to the ending because we're looking for three values so we could just do negative two perfect okay so now we're gonna do the two sum parts so let's write the code for that so I will be using a hash map approach uh and another thing you could do is you could use a two pointer approach alongside with a sorted area but I'll just use the hash mark approach okay so in this case we're getting for num3 and nums okay now this is very important what is the range of values you're going to choose well the basic thing that you might think is the correct answer is index two till the ending but that is actually wrong because what we want to actually do is index two in this case right so in this case we're only looking at a subset of the value use now we're looking at a smaller subset of that now in this case the first index is always going to be zero so it's not with respect to nums index instead it's with respect to this okay the same thing over here especially over here actually uh we're looking at index one plus one right uh so num zero is not the same as in the zero plus one or anything else right so we have to be very careful about that so in this case the indexing is actually going to be index two plus index one and we want to get the next one right so plus one but now that's another important thing because over here when you notice we're doing index one plus one right it's not just index one so this would actually be indexed uh one plus two okay so cool so now over here we're going to do the same thing so um so we're going to initialize a set so normally we actually use a hash map but we don't need to do that because we don't need to keep track of the indices so in this case we're gonna first check if whatever number we're on is part of the set and now if it is that means that we have found a solution but if that's not the case we're going to add the remaining value to the set now this is going to be Target 2 minus the current number we're on which is the number three okay perfect okay so now the basic thing that you might think to do is right now you can just directly append the result over here so let's actually first do that and I will show you what that looks like so press dot append uh so let's just append num3 uh the remaining value so that is just going to be Target 2 minus num3 and then we're going to have num1 and num2 now this is going to give you the correct solution but the problem with this over here is that we have not accounted for the uh for getting repetitions right we're not going to get a unique solution so let's take a look at that okay so cool now for this example over here we our solution was accepted right we just appended the result and it worked but now let's say we look at this example over here so let me show you what happens in this case we actually end up YouTube several times now Technically when you just look at the indices all of these twos probably have different indices and they're still unique values but this is not a correct solution because they're still not unique right we want the values to be unique so this is where we go back to what we spoke about earlier which is we want to keep track of the values that were used beforehand okay so let us do this one by one okay so first we're going to do that with of this over here so we're going to make sure that into some if we find the same two numbers we have to make sure that is not going to be added okay so for that the way we're going to do that is we're going to keep track of all the results of two sum so let's just do results of sum two over here now if at any time we found a result okay we're going to add that to this over here now one thing to be careful is we're only going to be tracking these two values right because only those two are produced for two thumbs right the result of two especially so we got this over here and now one thing we have to make sure is the condition that there's no the same solution is not being repeated now how do we do that so we first got to have this condition obviously to see if we've even found an answer now besides that we have to first check if whatever value we're on which is num3 is not the same as the previous value that we were using so that is just going to be the last value of Rise of sum and we're looking at num3 which is at the zeroth index now one small thing just to add on is if this is empty then for the first time we're going to let it through right so let's just check the length of it and if the length is equal to zero then we let it through okay but if that's not the case then if the current number right like as I showed earlier if the zero yeah if the zero over here is the same as the previous number right so if there is a repetition there is no point of checking it because we would just get the same solution or again no solution at all so that is exactly what we are doing over here so we've added that to Russell the result of sum two perfect so now we actually have to do this for the other two as well so let's do the same thing but for the three sum values okay so over here let's do result of sum but some three in this case and let's just initialize that as an empty area cool and now we also got to go to add the solutions with respect to three sum over here right so the solution would be found at the same place right uh but except we're going to have one extra number now that number is going to be num2 over here okay so we just add that as well okay so now we're going to have to check for three of them so the same way how we checked for a repetition for two sum where exactly do we check for repetitions of three thumb now that would be over here right so the way we're going to do that is the same thing so let me actually just copy this over here oh sorry this part so it's the exact same condition instead we're going to check if the length of rest of sum 3 is equal to zero or number three so the current number we're on sorry that's going to be num2 if num two right is the same as the last uh solution found for rest of sum three okay so rather sum three then in that case we're just going to continue we're going to skip this number and continue that's it uh also sorry about this uh if it is not empty sorry so we got to check if it's not empty and if this is true that's it because if it was equal to zero we don't want to continue then in that case we wanted to pause and go and do all of this stuff cool now we do it for the last step which is for res itself so I'm sure you understand the pattern by now so I'll just copy it now in this case the final result is stored in res so we're just going to do the same thing if lentils rise is not equal to zero num one which is what is for uh res is not the same so if num1 is the same as the previous value so in this case if we chose the X as zero and now we're also choosing X is zero again well there's no point because we have already found a solution with the first X that's all we're doing now in this case we don't have to continue the entire thing so we'll just break out we continue and move on to the next number perfect okay so now the final thing is we've done all of this but we have we've never added the values to result so that would be done right outside of this for Loop right so in this case what we would do is we would get all of the values inside of breadth of sum 3. now the reason we're doing reset sum 3 and not resosum two is because outside of this for Loop right the value of num2 could actually change right so uh what was actually proper over here might not be the same value when we're outside of the for Loop right obviously so in this case we have rest of some three but when we're in this indentation the number one is still going to be the same so we can just directly add that so for X inverse of sum 3 we first have to add the number one so let's extend so extend num one and now we're just going to append this to our final result so press dot append X all right so I did make a few small mistakes um so sorry about that I'll just go through them quickly so the first was I did not I forgot to sort in the values again like I said if you do not Source them then this whole condition of checking the previous values is not going to work now one thing I really messed up when I just copy and pasted this is the fact that uh over here what I'm doing is I am checking for the length if it's zero or if the loss value is not equal to the same thing then in that case I am adding that value but in these two conditions over here what I'm doing is I'm checking for the opposite right because I want to make sure that uh if the same if they are the same value then in that case I want to skip the entire thing and if they are not the same value well I want to go ahead and look for a solution so essentially in this case I'm checking if they are the same and if they are the same well I continue which essentially means I just skip it and look for the next value so the same thing applies over here now another small mistake I made is I just copied this value over here but for a result of sum 3 I'm comparing the number two not the number one so if I look at the index 0 that will give me the number three sorry uh but instead I want to get the number two which is the Lost index same for res right I'm comparing number one is the loss of Index right it's in the loss index if I submit this should get accepted um yeah sorry about that and hopefully this video did help you out and thanks a lot for watching oh
4Sum
4sum
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that: * `0 <= a, b, c, d < n` * `a`, `b`, `c`, and `d` are **distinct**. * `nums[a] + nums[b] + nums[c] + nums[d] == target` You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,0,-1,0,-2,2\], target = 0 **Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\] **Example 2:** **Input:** nums = \[2,2,2,2,2\], target = 8 **Output:** \[\[2,2,2,2\]\] **Constraints:** * `1 <= nums.length <= 200` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109`
null
Array,Two Pointers,Sorting
Medium
1,15,454,2122
316
hey guys how's everything going this is Jay sir in this video I'm going to take a look at three one six remove dupli-color at three one six remove dupli-color at three one six remove dupli-color letters to be honest I didn't make it about this question I tried for like 30 minutes and I couldn't find the solution as something similar but digital find the trick of it and I take a look at the solution I finally understand it so I rewrote it with my own way and the finally got it through so in this video I'm going to try to explain it as simple as possible okay I hope it helps okay let's begin so we're given a string which contains only lower letter lowercase letters removeduplicates letters so that every letter appears once make a unique right and we must make sure that results is the smallest in lexicographical order among possible results like a b c ABC okay first three letters are unique and then we add bead so there are double B so remove one we can remove this speed but after we move this B we could remove see here I'll remove see here we're gonna get ABC we just start with a comparing into BCA this is a much smaller in lexicographic order right so we're doing that about CBA CD C BC is take to the technically the same but a CD speed is the smallest in lexicographical order so how could you solve this for each disco problem I suggest that we dive into examples and try to list up the iterations of all the steps and try to find a pattern or some nice track and we start with example two obviously is much longer than big simple one right okay let's begin so first we look at a C right it's unique and yeah and we could just say okay this is the only one option right and then we got be the same everything is unique so here we already see that we could use how can I say that B doesn't exist before right okay we could use a set actually set use a set to keep track of all the letters unique and okay right a is unique so we add it so we have CBA now we got C again so this is a problem we have C we have also see here so which one should we remove well at the first I took us nice approach I just compared that okay I won't drop this C because if I drop this C I will have a word starting with B right if ice to keep this seed was start with C well the idea is right but it is not right for the whole picture let's continue okay see BAC okay so like the first idea of mine was okay one two options we could key CBA or we could escape BAC right so C is smaller bigger than B so we'll drop it so we keep piece BAC now this is wrong actually only right for this small step so let's continue anyway oh and we got D right it's unique okay we got C again C is smaller than D we keep bacd right and then we got B again be bigger than a so we drop it so we have a CD B and then we got C smart and D of course we keep this so we got a CD B it seems rise to write to this example but actually it's not we're only changing one step right if you only change into this one this letter we drop all the possibilities of the right but actually it's path first for example we have BC ABC whatever happened well we have b c8 and a game B right be smaller than C so we drop this B keep the BCA and then we have C and the BCA C and C's what are they so we drop this C so we have PC a but actually we need to ABC if the easiest the basic example doesn't give us a dozen cannot be soft power approach so it's not right so let's again take a look at the BCA to see why we're wrong okay the first letter we got is bead and then we got C okay so far so good an a so if I'm so good and now becomes right so for B obviously this B cannot be checked be used right for if we start with see it cannot be used in speed but actually there's a trick is that actually this post PC could remove because we won't find any we're going to choose ABC right we're going to remove this B and remove these speed just keep the rest so what's the problem here it probably isn't actually the problem is actually if we consider B and we do nothing but if a kinder sitter in C right here we consider in C there is another C at the end actually after this B right after this so Anna C speaker than a and there's another C after this a so why don't we just choose the latter one right so these give another hand that when we add at a when we add a alright see you speaker than a and there's a sea after a then we should remove this C to keep it like ba right B a and then there's a ba B's V today there is a be after PA so we don't need this B right so we could shrink it to a and now we have a B C so this just is a small step two to the final a solution let's consider some letters okay let's say is okay some letters like we don't know what it is so if it's ascending in lexicographic order so it's a small s right this smallest the only thing that we could improve this only chance we could improve the list is that there must be some letters going for downward right is that there is some downward slope suppose I and J and the SI is bigger than J so this is downward slope and there is another si after s J right if there is no another si it means this is a unique we have to keep it the position cannot be changed so you still we cannot improve this is only case we can improve right so we actually find in the negative case to the opposite of this problem and so our idea is just to remove though these pop posit oppose it opposite cases right so this is a general idea let's go back to our BC ABC case here so okay we're going to be let's review it one time was once more we get beat okay now we have C right see if you're gonna be are we do nothing and then we go to a C is bigger than eight and we have to know whether there's a lotta C out after a right for that we could just a pre count counts the numbers right and do we know directly whether there's a sea after a okay we know now there's a sea after a we should pop it right we should remove it and now we're comparing BNA right bees began hey there's another beat so we got a right so typically this is a stab we hold B and C and now we're going to push a we watch at against the top elements and a pop them and then finally we pushed it push it in right so now we have a and then we got B C and he's not there we'd be and then we got C right so this is it so this is how the approach we need to pre counting numbers and use a stack keep track of the letters when we are having a new letters we compare it to the each element and you who found it is bigger than it and has a future numbers we remove it and that letters will be pushed it in you know in the future right so that gives us the smallest one okay so now they start our code the first we need to count the numbers right it's as simple we use a count map okay we have counted and now we need to use a stack to keep track of our optimal result right in a waveform we just say this is okay we use a stack and then while loops relog let the is Unitas okay yes and besides we need to use a set right here to keep track of all the letters to check it instantly about they use a duplicate or not okay this is a that's a result stack this is a result of a set okay first one if we did we doesn't have this num have this number if you get already in what happens okay if it is already there let's see we haven't seen this case Yeah right suppose we have like a B C a and then we got be okay wait a minute so this ascending right something a and B and C now we have C again okay maybe not we have a again what happens well we pop we check that C is bigger than it we update it which it was due to the same right it act doesn't matter whether these slider is in it or not if this have it be we pop beat see and we stopped at be so we'll when do we pushed it in well there may be some duplicates so actually there should be not should not be any duplicates actually if you remember that if there's a be here if this is a duplicate case actually if this be could be switched to this be it is already handled when they first be is in good right it is pushed it is kept there because this B cannot be switched to this B right we'll do it from the first empty and then second one so it means when we handle B a and B and C it's okay so now we have B we cannot switch you can like there is something bigger than P wait a minute there is something that means there's something smaller than being this array and that could be done much sooner than SP arrives right so we cannot switch the B so we only check it exists or not if it exists we're just scared so we only handle when it doesn't have this letter as we analyze to what should we do we'll all keep popping the annamund and compare it right so we see get the elements if okay we might there's a case that we don't pop anything so we just compare with the top element first Wow we stop we wow we resolve stack is not empty top we don't pop it yeah okay so if these Edmond is smaller than the character then it means we should stop right so if it is some other than our character or if you figure than it but there's no so the this condition should be the opposite of the case here so if you're smarter than it or there's no number and no duplicates after our character so which means the count map it get week at the top is zero right if this is the case then we should stop we stop here is no more needs to go to the previous letter yeah letters if this is the case we break right yeah and if it's not the case we should pop it right we pop it and doing it for next one so if we pop it when we pop it means the set should be also be able to update it so we delete D top okay so and after this whatever they need ready we will push this character in it right okay we push factor and then result set a doctor yeah there's not a case don't forget that we've hat we do through all the characters these counts should be updated also so can map set capture get character nice one so this is it finally we get to the results tag we will always return resolve the stack and join it let's see great let's see what actually the intermediate stack for these input okay to make it clear okay let's log okay so now we have C right and then we got B C's bigger than B and there's another C after B so this stack we won't use the first see it's not optimal so we use we keep only be in it and updates the count of C to 3 right the first it was 4 okay we not be that we met a be speak and I hey now there's a B after a so we stopped using this B we only keep a so the be updated with one we've them there's something wrong with the count I'll push be here is becomes one there's something wrong here I think anyway the stack is right C is 4 B 3 a is 1 DS 1 we got - ah he is - yeah is 1 DS 1 we got - ah he is - yeah is 1 DS 1 we got - ah he is - yeah all right it's CBA DBC okay now we ate and then we got AC its ascending si D ascending Dean is 0 XE d is as an ac/dc C is already in is 0 XE d is as an ac/dc C is already in is 0 XE d is as an ac/dc C is already in it so there's no need to do anything and we can't be again be these bigger than B but there's no D after it so we do nothing and then the C's already in it so we get a CVP what happens is for the first one this is much more this is might be more interesting okay first we got B and then B C right ascending that's a C's bigger than a there is a seat so we stop using c e speaker than a is a B so we stopped using be with keen a and the ABC ascending yeah this is a short it so pretty I think this is a pretty interesting problem but it's not that easy I didn't make it and okay and it's analyzed the time and space for this one okay but for the space actually we use a map and a stack and a sad yeah this is generally it should be linear time a linear space I'm sorry 3n it's linear space and this time what is the time okay this is an e no time to count this is an e no time to eat rate and the set is constant and this will be I think so the maximum of the set is actually is okay this is a maximum actually owed 26 right letters this is 26 and this isn't 26 actually so we say this actually is 26 it's typically constant I think okay and this here is still this is constant even though here's a while loop they were maximum 26 numbers right a letters and I mean do it and for ass so yeah it's still it's cause it's constant times 26 right so it's linear time cool that's it hope he helps see you next time bye
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
63
Hello Gas Lead Ko Daily Challenge We have come again today on Gyan Portal, your channel and okay for you, so today's question is our great question and great pe this question which has been given to us is that of macros n. One wait is great, okay and what we have to do is that our robot is standing at the top corner meaning zero and we have to say brother we have to go to the right corner, great M - 1 and N - 1 and what they have is that great M - 1 and N - 1 and what they have is that great M - 1 and N - 1 and what they have is that you have obstacles. Marked with one and zero, whatever is you, whatever is the space, that means you can move there, our robot can move on whatever is there, okay, we have to return, how will we do it and for this, who am I? Ours is okay like we took the grid like this okay in space we can move so we can move here we have a gone here can we move here no here We can go here, we can go here, our point is again, so if we see, how many units do we have two units, five, for my love, we cannot walk in this because this is our block, okay? If we have to consider one like a block, then we have asked such a question, but what we mean to do in such a question is to extract all the urine from the text that whatever is at the bottom, you can go to Dr. Okay, so friend, let us know. That is, whenever we get such a question that is possible, what does it mean, it means that how can you do this question, how many days can you do it, then basically if we see, then in such questions we What to put, this is what we are going to solve through the process of analysis and if we talk about analysis, what do we do for analysis, we have to express what we have in simple expression in terms of I and G. Okay and We are going to do all those things and whatever it is, I will get more time and I will study and here we are going to give you all the three solutions from calculation and memorization and how do we convert one after the other? What do I need to do for tabulation , I don't know anything, let me do for tabulation , I don't know anything, let me do for tabulation , I don't know anything, let me make a function, let's read it and take it, okay so let's take N. I am lying in these, what is ours, I will make it a little smaller, I will grid it, make it great dot size and eat ours, great, okay and then on that, what did we do? We said, brother, now what do we do? Now we will go from here M - 1 M - 1 M - 1 and N - 1 and along with it we will also and N - 1 and along with it we will also and N - 1 and along with it we will also keep taking our grid, okay because our chameleon is also very important in this thing, so we have concentrated our grid in the middle and what we have done Here we have returned the function, okay, I donate my grid with whatever is A. First of all, what will we say, brother, if we are taking from the bottom, okay, then what will we say, brother, if I have this zero. It goes successfully and if G becomes zero then what will we do brother return one ok if our I what will happen if our I has become big, it does not mean big, sorry it has become small, if it has become small then what will we do? If we give it then we will give it brother, return it zero and inside this we will have to pass DP which is our vector, so this is not our great, okay and in the last, what will we do, we will return it if it is plus then submit. Let's do this okay, so what did they do? What did they do? Brother, okay, we put small gas, first of all, the gas was ours, so we made a mess, brother, what did we do, we reduced the out of off one, why because we and So we have to put more here, okay, and the second thing brother, this is our condition, we will put it above, such a test will be done because if there is only one element and that is the block, then our water is there. Will it come ok and this is our time limit showing acid like we said because this question is not going to happen what will we have to do we will always have to convert these memos solution so for memos solution we had also told yesterday what we have to do. We simply have to create a DP vector and what we will do in the DP vector is that we will pass our DP vector here and it will be storing our possible solution on it and it will be saying that the story should be locked. Okay, so we have made this DP and we do not have to do anything else, we simply have to add one condition here that brother, DPO of I and DPO of K, if our two notes are equal to minus one, then return the DP here and I and DP object is fine, that is, if it is already a student and here what do we have to do, here we have to give every solution to P of I, OK, here we have not passed DP, wait, there is some network issue First of all. So gas, this is our solution that has been submitted, but I will also tell you the tabulation approach, so I will discuss with you in the tabulation approach. Okay, how far do we have to run from zero, we have to run mines Banta and inside this, where should we hint from zero to I? Till j = n - 1 and k plus has to be done Till j = n - 1 and k plus has to be done Till j = n - 1 and k plus has to be done and inside this now we have to pass on our conditions and the conditions which we had discussed above will come, okay this condition will come for us, will it come what brother if our This is what is right if our condition is simply if we say that brother if DP of 20 equals tu band kar do simple ki wahi agar hamara jo hai he both already jo is hamara greater than zero hai this equals tu zero hai And yes, our greater than equals is zero, okay, so here we will say that brother, store DT of I as zero, okay, so this is our second condition which we will have to keep first, okay and after this is our help condition. And in the last, our ok is increased from zero to sari bada zero Mines, what will we do? In the last, we run DP of I and DP of J = Run
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,897
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 redistribute characters to make all strings equal so in this question we given a string array called words in one operation we can pick two distinct indices I and J which means you can pick two strings from the words array and we can move one character from one word into any position into other word so if there are two words I and J so if this is I and this is J you can pick one character from I for example if we pick a and we can move it to any position inside J so if you pick a from that word will become BC and that picked a if you want to move it into the word at J and move it at the last position it was initially a b c it will and if you add a it will become a b c a so this is one operation so after performing any number of operations like any number of times if you perform this operation and if you are able to make every string in the words are equal then we have to return true else we have to return false as the output so let's take this example and see how we can solve this question so I've taken the same example as example one this is the index positions of the words present inside the words array so here you can see if you pick one a from this and send it to the second word the words will become this word will remain the same this will become a b c last word will also become AB BC since all the words are equal we will return true as the output for this question which is matching the expected output here so how are you able to choose which letter to pick from which word and send it to the word which is needed to make the all the strings equal so you can count the number of characters inside each word so I'll make a frequency array of length 26 because it is given as constraints that every word consists only lowercase English letter since there are 26 lowercase English letters I create an array of size 26 so I created an array of length 26 so let's iterate through the input words from left to right starting with the first index so I will start from here now I will convert this word into a character array so it will become a b c now I'll iterate through this character array from left to right where the indexes start from 0 1 2 and I will count the frequency of that so first letter is a increment its frequency initially everything is zero so it will be one increment B to 1 it will be one increment C to one it will be one now I pick the second word I convert this into a character array so this will become a b c now I iterate through this character array to access each character and increment the count in the same array so this will become two now the second character in that word is again so incremented two will become three next character is B so increment it one will become two next character is C so increment it one will become two again now we finish the first two words then we go to the next word convert this into a character array this will become B comma C iterate this and pick one character at a time and increment those frequency B's frequency will be changed from 2 to 3 in the next iteration we pick C increment its frequency C's frequency will become from 2 to 3 now we finished all the words so now you notice that the length of the input array words array is three there are three words and the final word that all those words will become common to is ABC and you need three ABCs right so ABC a b c are the three words so here you get A's count as one B's count as one C's count as one and here again same so total A's count is Three B's count is three and C's count is three so now we iterating through the input array from left to right and you pick one value at a time so you first you pick three and if you mod it with the length of the total array which is three you get zero if this is not zero if you get any remainer which is not equal to zero then you can return false as the output because you won't be able to use that character to divide it equally among the length of all the words here you can see the length of the words are is three which means there are three words a count as three so each word will have one so you need to check if the characters count can be equally divided among the input words length so if this was 6 mod 3 is equal to 0 so you are able to divide 6 a equally among three words so each word will have 2 a for example if there were 5 A's and there were three words the REM remainer is 2 which is not equal to zero it means that you won't be able to divide this 5 a equal equally among three words so that is what you're checking for every Letter's count and in this case all the letters have equally divided so it means you can equally divide the characters among the words length so this is the main condition you have to iterate through the character array and check if the characters count which I'm taking it as num and mod it with the length of the words array and this should give you zero so if this condition is passing which means that characters count can be equally divided among the length of the words now let's implement this in a Java program so this is the input words given to us first we're doing a base check if the length of the words are is one then we return true which means there is no need to perform any operation so there is no need to perform any operation if length is one we can directly return true as the output now I'm creating a frequency array of length 26 I'm iterating through the words array from left to right so if I take the word words area I'm iterating from left to right then I'm picking each word at a time so first I'll start with this word I'm accessing the characters inside the word so first I'll pick a then I'll pick B then I'll pick C so we start with a and if you do a minus a you get zero so in the zeroth position you will increment the count by a so 0 frequency of 0 Plus+ similarly in the next of 0 Plus+ similarly in the next of 0 Plus+ similarly in the next iteration we will pick this word then we will count the frequency for every character in that word then we'll pick this word then we'll count the frequency of characters in that word and now I'm going to iterate through the frequency array using a for each Loop this will represent the frequency of every variable now I'm checking if that by using the modulus operator with the length of that words array I'm checking if it is leaving a remainer of zero or not if it is not leaving a remainer of zero then it is not possible to make all the words equal and if this condition is failing and I finished iterating through all the words inside the frequency array and it has never return false I will come out and I will return true so for this question true will be the output so the time complexity of this approach is O of n into m n is the length of the input words array and M is the length of the longest word inside the words aray and the space complexity is constant o of one because we're using a constant space of O of 26 which is constant for every solution so o of 1 is the space complexity that's it guys thank you for watching and I'll see you in the next video
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
6
okay so this problem goes like this so i have a string okay i have a string and let's say that it says we are hiring okay so this is the original string now i can i write the string in a zigzag pattern okay so on let's say on the three rows okay so what that looks like is we are high all right so if you read from top left so w-e-a is the first column right then w-e-a is the first column right then w-e-a is the first column right then so this you know then r e diagonally right then from e uh you know i have h i right and diagonally i have r i then i have the vertically i have i ing right so this is what i mean when i say you know this the string is written in a zigzag pattern on three rows right lines four five six there are three rows of course you know this can be you know we can convert this we can write this in a zigzag pattern on four rows right which would look like a r uh e h i and g i think this is right oh i missed r and g this is right we are right okay does it make sense so far well yeah as much good yeah okay so now after writing this zigzag in a zigzag pattern we're going to read line by line so in the first example when we're writing this on three rows if you read it right line by line you will get wei e-r-h-r-n-a-i-g wei e-r-h-r-n-a-i-g wei e-r-h-r-n-a-i-g all right so in the second example on four rows if you read them line by line the first line will read w-i then the first line will read w-i then the first line will read w-i then the second row will read e-h-r the third one second row will read e-h-r the third one second row will read e-h-r the third one will read a-e-i-g the last one will read a-e-i-g the last one will read a-e-i-g the last one will read r-n right so r-n right so r-n right so the question is i give you the original string and i tell you how many rows am i doing this exact pattern right and you're supposed to return the final result uh read uh line by line all right so your function should return so the input in the first example one the input will just be we are hiring and the num rows will be equal to three and this will be your output right and uh in the next one yeah the input will be the same uh the input stream will be the same but the numbers will be different any questions about this one so if it's under string then of course the option empty i'm destroying if string is shorter than number of rows then it would just be uh same string right yes that's what it will look like yeah if amount of rows is one that's again same string yeah so you can assume that the number of rows is positive like it will not be zero all right um is there a lead code reference to this yeah okay let's take a look into this example so yeah i'm not sure yet how to solve it so i'm leaning towards just trying to simulate this behavior so yeah there should be some pattern and the pattern that i see now is that for example this string has three rows that means that first three steps we just put character by character intervals one by one then next one step which is uh yeah which is three minus two so next amount of rows minus two steps we just decrement and then put and put those characters into the respective rows and then we then repeat the process yes so i'm thinking about the template that looks like that um num rows we'll just do something like roblox plus and uh row some ice and some index right num rolls minus two steps okay so yeah that makes this make sense yeah so fix it a little bit yeah um so i will be counter of overall right yeah place basically something like that j will be just um the counter that goes up increments all the time and goes to all the other of uh s so yeah um let's scroll through something more complex yeah so here we'll just do four steps so it will be row zero one three zero one two three and then two steps back backwards two one and then again okay so uh this seems to be working so yeah and rinse and repeat until j runs out of our string and in the end we'll just take all these rows and we'll just concatenate them into one single string um yeah so each row will be basically a string builder so yeah all right so that's uh that's how it should work in general uh there are a couple of things to uh still to look into such as check for this index because at some point here or here we will run out of string class so we need to protect ourselves against that and it's rather simple and uh this here so every time we run out of string here we just stop and we just do not start this loop we stop immediately right and then we go to this check and we're done we just exit all right let's just let me just do a dry run here okay so when we start doing rows and num rows is uh three in this case so yeah here just every okay so also this would just work yeah it would just initialize several using program okay yeah i will not go in details in this one yeah this is not that as interesting as this one so now so when we go down j's equal to zero right okay so this is jay now we go through all these rows so first we are in here so we append so we take first item then we encounter then we take this guy and put it into same happens to y so now we are pointing to b now all right now i okay i forgot to play this value anyway it is equal to 3 now that means that this is false so we just exit out of this loop we go into this one so this is where things get more interesting so i equals one now we take our character which is p and you just yeah i just forget to late every time this is right here right oh wait no it will not work like this because this condition says more than i greater than one and we are at i greater than one so we expect to actually pick up this character but we did not so i made a mistake here it should be actually but you know what i think you should look this is more clear right so where were we okay so we just picked up b we moved to a now we just do i minus so i is equal to zero so this is false so we go to the next iteration and the next iteration i equals zero again j is pointing to a so we'll just put a here all right so and then we'll just repeat this pattern so i think you're just looking yeah it does looking good um to be honest i do not want to go through yeah this looks good to me too i mean we went through the full cycle first time now i'll just yeah all these uh boundary checks look good to me so yeah okay cool good yeah uh good job in solving this one any comments from uh four or four alex yeah it's like uh so i was uh actually i mean yeah this is great the in the time that he was doing this i was actually working on the mathematics of these indices and it seems like there is a formula possible and the formula looks different for odd and even numbers so basically in if the number is odd like three then middle one is an arithmetic sequence of n minus one so you'll have one three five seven nine like that and the ones above and below it are arithmetic sequences of n plus one so uh in this case it'll be four now when you look at bigger numbers like say x or five so there is a clear pattern so in the ones which are neither at the top nor at the bottom nor in the middle there are two arithmetic sequences which are intertwined is it like okay now like i'm sure given more time i would have worked it out but i think i would have messed it up because firstly like in the full time that i think to solve the problem i was still playing with the numbers and working out the arithmetic this which could be disaster in an interview situation is it like uh on at this point yeah so you're asking like doing a real interview like do you want to introduce but yeah continue thinking about the mathematics or should you just like um you know okay so my recommendation is now even if you are able to work through the mathematics right like but how would that improve our solution like still i mean currently we are you know uh the simulation solution um is already we're just scanning the string once and uh you know we're using of and you know we're using linear time which you cannot avoid right i mean no matter what you have to read a string at least once right to generate the zigzag string so the space would be better because you wouldn't make lifting windows right for all practical purposes yes space would be better you just locate the resulting character array once and you just fill it out you just pick characters from the input and put it into that output and that's it still yes because you're just you know you're changing you know number of rows of string builders into just one string builder but you know i mean still it's off and space so i wouldn't oh fine i can take my entire code right i can do something like this and it still will be all fun i mean you get my point so from yeah you can yeah instead of you know initiating a number of rows number of string builders you can just put the characters in the right place yeah so from big offense perspective both solutions are the same but in a real job right double closer non-double quotes right double closer non-double quotes right double closer non-double quotes the solutions i think the question right the question is that if you like do you get any brownie points for solving the puzzle because i think there is a like there's a certain amount of ingenuity and discovering the yeah so i mean like you know so the most important thing is solving it right so now if you are first able to solve it one way you know using simulation or use math uh you know that's good right the main thing is you want to like if so okay so if you're super confident that you're able to write the working write a working solution like whether write a non-mathematical solution non-mathematical solution non-mathematical solution very quickly then fine like you can definitely feel free to you know spend 20 minutes on trying to figure out a mathematical way right now i you know like you know i would not do that right i would first try to solve it using uh in this case simulation but like any like working solution uh right i would first try to solve it um right then you know we when we have extra time i would you know maybe we have extra 20 extra minutes then we can think okay maybe there's a way to um solve it mathematically right and also when i'm mentioning you know when i'm sort of proposing that we can solve it mathematically i'm also like you know observing the interviewer very carefully right i want to see their reaction right if they're like if they're very enthusiastic um then yeah maybe there is a mathematical solution right now if they're like uh you know if they're not very enthusiastic then you know that either they don't care that you cancel them mathematically or they know that there's they're not aware of a mathematical way like either way is a discouragement right so you know i would you know in that case i would i mean of course i would not just stop just because you know they didn't show enthusiasm right so i mean i would try briefly but you know then i would just mention okay you know maybe we can solve it but you know it will probably take some time and then you know then they will usually move on right because just because you're able to solve a problem in i mean this problem doesn't look very difficult right um like you know if you're able to solve this one in 20 minutes then it's very likely that the interviewer actually has one more problem in mind right now you'd rather you know solve both problems um like you know give them working solution correct solution then you know just spending a lot of time on the on one you know the first problem they give you right because you they will never tell you how many problems they intend to ask you right so you'd rather be um you know try to basically solve a problem asap and just move on right if they don't have another extra problem i mean you can easily tell that right if they don't actually have a problem in mind um then you know then they will usually say oh you know uh yeah it looks like we have some extra time do you have any questions for me okay at that point if you know if you have way too much extra time then you can say okay actually you know um in the last problem maybe we can solve it mathematically do you want us to think about that or um or you know that there's no way we can solve mathematically right and see what they say okay yeah but remember the main the most important thing is you know get to a working like a optimal working solution i don't know maybe the mathematical solution is even more optimal but i mean i think like it you know the solution that we currently have is at least very close to being optimal um so i would stop there and uh see you know what the interviewers plan uh right if they have extra problems for me if they don't then sure we can think longer about the mathematical way but still i would try to get a working solution first people either way right even though i'm confident that i can write a working solution in 10 minutes still i would just do that right then um yeah only then when i think about you know fancy resolutions
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
232
hi students welcome back today we are going to look at implementing a queue using two stacks okay so let's see the problem statement first the problem statement says implemented first in first node which is Q using only two stacks the implemented queue should support all the functions of a normal queue which is push p cop and MD so my the queue which is called my queue in this case should contain all the operations push it should push an integer X pop it should remove the first in uh element from the queue following fifo which is first in first dot Peak also should follow if you fall and show the first element of the queue empty should return if the queue is empty or not okay and we are allowed to use only standard operations of a stack we can't use a regular queue data structure which is already available in the in Java okay so let's look at an example so the example says uh we are pushing a element one to the queue so the queue now has one now when we push another element Q has one and two when we Peak it should show the first element so it is showing one but the queue will still have one and two at this point when you pop one is removed so the queue has two when you check if the queue is empty since the queue still has two it is saying it's false so let's see this with an example how to implement this so we have to take two stacks correct so Q is a V4 first in first out stack is a lifo last in first out it's completely opposite of q Returns the oldest first stack Returns the newest first okay let's say we have two stacks so to return the whole list first we have to have a stack which has elements in the reverse order basically so let's call this stack with oldest first and this is a regular stack which is a lifo last in first stop so let's say we have to in insert these three elements to the stack what we will do every time we need to insert is we will empty the contents of this stack we will insert our new element and we will push back the contents to this tag why are we doing that because we want the last element on the top oldest element on the top so that when we return it we will follow the fifo so let's say we are inserting one and we are inserting one there is nothing to empty here so nothing is added to this stack one is added here okay and if there was anything else we would have added it okay now let's take a look at inserting two and we are inserting to what we should do first we should empty this stack and add it here okay next add the current element whatever we are inserting to this stack then bring back elements from this stack to this stack again so one comes here if you see since we put in the other stack and brought it back the order is reversed and oldest became on top automatically now when we try to insert three again we follow the same logic we push one we push 2 then we insert the current element then we move elements from here to here if you see since we are doing the reverse operation the order is clearly maintained now if we follow and 4 and 5 it's the same thing now for the other operations of Pop we just remove the top element of the stack and Peak we just Peak the top element of this stack is empty we just return if this stack is empty or not this is just a helper stack we are maintaining our FIFA order in this stack by using this stack okay so let's try to implement this okay let's say so this is what lead code has already given us okay let's Define a cube sorry stack two stacks we need two stacks so the two stacks are integer Stacks one is a regular stack and one is a stack with oldest on top okay now okay finish off let's initialize them in the Constructor instead of initializing here okay now you push an element what we what should we do while the stack with oldest on top while that is not empty okay well that is not empty we push it to the Second Step which is a regular step dot push stack width or list on top dot pop so we are popping every element from this stack and pushing there okay so we moved all our elements from this stack to that stack then to the stack with oldest on top we push whatever element we are given then we bring back whatever we have pushed to the other step the others while it is not empty the not empty check is important otherwise it will throw away null pointer exception so we have to bring back elements to the oldest on top stack so okay that's all so that is the this maintains the order with stack with oldest on top and popping and all is just a regular operation now Peak is you just call the peak of it okay is empties also is empty okay so when we are pushing the elements to the temporary stack inserting our element at the bottom and bringing back our elements pop is since we are maintaining the correct order in oldest on top stack we always have the elements so we just pop and P candy is empty so what is the time complexity of this the top Peak and empty are order of one because we are just returning the top elements of the stack whereas for push we are moving it to another stack bringing back another stack so the stack is full it would be order of n similarly the time complexity also would be order of n because sorry space complexity would also be order of n because we are using additional stacks okay let's run this code yeah it got submitted that's all for today if you have any questions please do leave a comment please like share and subscribe our videos please help us spread the word happy coding
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
371
hey guys welcome back to the channel in our previous video we solved this problem sum of two integers just pretty much saying given decimal numbers a and b we want to add them up without using the plus and minus sign okay we solved the user c because he was the better tool than python so today we're going to explain this solution why it works okay so to do this okay let's just first write let's get some examples with three bits binary number so again you could use any number of bits for them i like three so let's just write the binary numbers so zero in binary is just zero if we decided three bit implementation one zero one two okay so these are binary numbers again so like we said two things we need to keep track of this or we need to keep track of our x or okay and simple x or table is so if we have a and a b okay zero one okay x are just gonna give us if both are zero if both are one zero if either is one okay it's different than or it's called x exclusive or let's also have an n table and table okay a b and results okay i'll just leave results very well empty okay zero one okay it's pretty similar okay if both are one is one if either is zero it's zero okay cool now let's take some example cases okay in our first example let's add three okay plus four okay three in binary is just zero one four is one zero if we wanna add him it's just straightforward one which is seven right okay correct we want to add him okay so there's two steps we did here but you didn't really see the two steps the first step was to export him the next step was to end him and keep doing that in this example just because it was straightforward we didn't see it let's take an example where it's not as straightforward let's take three plus five okay and then we'll see what we're doing okay so three again zero one five is one zero one okay in this case one plus one is zero right but there's a carry okay one plus one is still zero does it carry one plus one is zero that's a carry okay and this is eight okay now this problem just like the first problem can be broken into two steps okay the first step okay i'm just gonna right here the first problem to follow these two steps but we didn't really care about it because it was straightforward but let's see the first problem okay is what i call the xor problem okay where we can break this problem into so i'm gonna call this the xor so we can simply break them into three x or five okay and in this case three x of five is just simply like i said in binary three is zero one five is one zero one okay now let's actually order using the xor table excel table says if they're both one we get a zero so this would be a zero either is one okay either is one we get on one so okay keep in mind so three x of five is what is six three x of five is six okay now the second problem is the and problem okay but not just any end the left shift end that shift by one and okay so let's do it again so three okay this was xor five is one zero one okay now what operation are we doing we're adding okay so one and one obviously is one and zero okay simply this is our end but now we need to apply the last shift to him so once we left shift him by one this is gonna give us zero one zero okay so now keep in mind this is gonna become our new a this is gonna become our new b okay and now keep in mind this is six this is two so now the problem is we have to do this again so this problem now becomes six plus two does that make sense okay so now we're gonna have to break him up into two parts again okay six in binary okay the first part is the xor just exactly what we did before so x of six x or two okay excerpt of six xo two so what is six is just one zero two is zero one zero once we do the exclusive or okay let me scroll down a little bit once we do the exclusive r of these guys okay exclusive r says if both are zero okay if both are one zero one okay so this is four okay exclusive or if these guys give us four okay so let's just this becomes our new a which is four okay next the second part of the problem just like before is the end left shift by one okay so now let's six is one zero okay and two zero one zero okay let's end it if both are one is one okay else is otherwise is zero okay now let's left shift him by one for left shifting by one that gives us one zero okay which this becomes our new b and b is what this is for okay so let's keep going okay this becomes a is for plus four this is our new problem now to solve okay again he breaks up in two parts okay first part is the xo problem okay the exo problem just says four x or four okay so let's do four is just one zero okay one zero x or says if they're both zero but one zero right from our excel table up here if they're about one we get zero okay so this is our new a which is zero okay so second part of the problem is our iron case and case let's shift it by one okay so let's have one zero four one zero this is four so we wanna end it here with x already zero one and one what is one and one according to our end if it's one on one we get one so this is back four okay this is our new so let's shift him so we want to left shift him next by one if we left shifting by one this becomes what does he become he becomes eight one zero the third zero comes which becomes our new b which is eight okay good again this problem goes one step further because now we have he becomes a zero plus b eight okay this is what our wow look if you look at the code this is what our while loop is doing he's doing him consistently okay so again still a two-part problem the first again still a two-part problem the first again still a two-part problem the first part is the xor case and so k says zero x or eight okay what is zero four beats okay because eight is four bit eight is just one zero you want to x or this case okay so xor says if eta is one it becomes one otherwise is zero so this guy's one everyone else is zero so this becomes our new a which is eight we did second case is the end case okay here we xor okay and case zero one and zero and eight everything here is gonna be zero straight zeros if you left shift zero still zeros so this becomes our new b which is zero okay so now simply we have a base case once b is zero our while loop stops because it says while b our while loop stops and then we just return a okay and what's what is a is simply eight so we return a equals eight again kind of like we expected three plus five equals eight we did the same thing here but it wasn't as obvious okay so that's it for the video guys i hope this was helpful in understanding how this code works again all we're doing is the xor first then calculating the carry like that shifted and then we're assigning this xor to a carry to b and we're doing it all over again till b becomes zero i'll see you guys in the next one
Sum of Two Integers
sum-of-two-integers
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`. **Example 1:** **Input:** a = 1, b = 2 **Output:** 3 **Example 2:** **Input:** a = 2, b = 3 **Output:** 5 **Constraints:** * `-1000 <= a, b <= 1000`
null
Math,Bit Manipulation
Medium
2
64
Hello hello everyone welcome to my channel's studio will discuss some problem from list co DC minimum alarm of I will come in this problem is highly recommend you to the public number 6 to Chinese path 163 Amazing bathroom after going through this problem delivery me gift you To understand this problem and suffering from good will you will give in which contain mintu and grid given this field with no negative numbers now it start from this point you can access point hai to information returned love you can go to the right side and dance side like this college will not come from start to the end and patti or coming in food and all the numbers present in the sale ₹10 minimum numbers present in the sale ₹10 minimum numbers present in the sale ₹10 minimum unwanted result you to return serial back to 13151 421 is orange color CPI(M) flow 13151 421 is orange color CPI(M) flow 13151 421 is orange color CPI(M) flow days total Samudra Product Vikas Is The Meaning Of Money Plant An Answer Notification Problem And Goal Is Travels From This Point To Point So They Can Take Help Dynamic Programming And Se Technique And Can Divide This Problem Means The This And Not Here And Near By Check The Pant Pims Pollution And From Where They Can Get Some Idea And Solve This Problem Why Not Think This Info Point In Here You To Come From One Such Things To Start From Mouni Phir Rich One Din Fertilizer Muktipath Atul Want To Plate Nine From One To Three Years Only One Way Can Go And What Is Some Points 54 A Civilian Relief From One To Inform Others Also Only One Possible Cut Is Vansh 32 Notification For Better Life And Plus 216 That Effect Come To 20072 For The Part Of 1324 Because Only Right Side And soon that moment jal road show is kand ko like this is it surya follow this path 1956 122 come to the sale sauda 500 one plus two class for similar come from want to do a timely plus two 112 Light Switch From Kumbh's Perspective Left Side Is Note People Boat Na Kevatu Computer Sale How Can We Can Yes And No Hotel Minimum And Minimum 500 600 800 Chief Guest Number 4 That Police May Pass In The Evening A Similar Way If You To Come Hair 9224 and situations minimum that is 4 plus 303 487 which hair only to be between 0 minimum set plus 2 and not with the parts of oo inside trophy ki full movie in between 104 and this minimum fennel and plus hadith 428 which hair between 1000 Minimum Seven Plus Two 9 Admit Vinod Same To You Can Speak Any One No Plus 3 Even One Behind 12th Key Twenty-20 Slice 100 Even One Behind 12th Key Twenty-20 Slice 100 Even One Behind 12th Key Twenty-20 Slice 100 Song Tourist Spot V No. Co Army 20-10-2016 Plus 212 300 Army 20-10-2016 Plus 212 300 Army 20-10-2016 Plus 212 300 Students Will Be Our Answer A This supreme want to this point to come pure minimum sum requested this point to be 12th so 12th and answer a that needle to 12:00 and answer handed over city needle to 12:00 and answer handed over city needle to 12:00 and answer handed over city finance for this problem first feature interview will ask you to understand and question at this Tell Me The Path Like Following Which Parthiv Ka Dahez Pay How You Can Solve Intestine What You Can Do For That Is Vikram Dua Backtracking On That We Are Here To Help You To Check Which Where Is The Minimum Laptop Left Is Minimum Cut Means Vikram Hadith Root Right That boat we three cricketer laptop guys minimum 4th same that take any one interested spot on unmute tomorrow state bathroom hair oil solar plate dinner date with different color and going back to the spot will complete first hindi essay on this word from nine to back In the intensive will choose 737 minimum from 0360 juice 41 justice minimum of twenty three and four one is minimum 30 to back and only one choice is west of words between a pleasant school building my path select market or check result that printed total Value British OnePlus One Plus One Class 12th Part Co Share And In The Same Thing From Top Or Jeans Top Is Minimum Market Between 4 And 804 Market Mein 4500 Kal Swimming Spot Is The Song Regular Seven Plus Two Plus One Plus Form Plus One Plus 2 2012 Sui Got to 5,000 Result One Plus 2 2012 Sui Got to 5,000 Result One Plus 2 2012 Sui Got to 5,000 Result Tip Interview While You Know It's Like Time Complexity This Problem Row and Column easy-to-follow Time Complexity of 12th Result 2012 Result Subscribe To Know You Can And Smell Things Where In Food Are You Got To Derivatives Interior Studio Breed So Insted Of Maintaining On Saturday Fear You Can Keep Or Editing That Was Also And You Can Give The Result Late And Updater Result Declared Today At Times You Need To Take Any Express Will Be Then Steve One Time is the third one status but in that case song the incident details with emergency minutes letter words from to back tractor time you will not give the path will get up after butterflies book the a surujmal about this avam example the calling let's talk about The problem nature define what is the chairman of 12th targets input birth difficulty are of a man in the first time to calculate this point like this row how to calculate hotel with hello possible to give one plus one four days plus 15273 are doing for the Record This Is Different From The Tarzan For Doing The Same Thing Inside Checking Gift Only One Who Is Present In His Subordinate Sections Presidents Of Its Structure The Time This System Does One Right Shoulder BDPO 100 Depend Matrix Only This Column Is Present Only One Column The Times They Whole Turn On This Value End PM - 20 Value End PM - 20 Value End PM - 20 That Know The Question Read Work Starting Sometime Starting From Equal To One Is Equal To One This Point Super This Point Calculation What You're Doing And Checking What's My Like Top Balloon What's My Glue follow in between the twist minimum the time choosing and with the time wedding ka current dhalu and updating the dp are doing this for parisad is corner loot andar dip this - wave and minus one note white is this or Vishwakarma thanks for watching see
Minimum Path Sum
minimum-path-sum
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\] **Output:** 7 **Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum. **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\]\] **Output:** 12 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `0 <= grid[i][j] <= 100`
null
Array,Dynamic Programming,Matrix
Medium
62,174,741,2067,2192
1,753
hey everybody this is larry this is me going over weekly contest 227 uh q2 maximum score from removing stones um hit the like button hit the subscribe button join me on this card ask me questions about this one i think this one is really tricky uh it let's see it took me about four minutes to do this but uh well people are really much faster about it on this one than i am um and it's just a math problem and for me with these math farms i'm actually is definitely one of my weaker points i have to kind of prove to myself like i even have pen and paper to kind of write it out um but once you see the solution it kind of you could kind of maybe reason against it but um but yeah but there's really only two scenarios right one is where the biggest number um so i wrote it this way the biggest number is i don't even need total i didn't end up using it but the biggest number is oh yeah so the first thing let me step back for a second so the thing to notice is that n is less than 10 to the fifth so i was like okay but that's still going to be too big to do some kind of like because my first intimation is okay maybe we do some breakfast search or heap search or something like that you know some sort of greedy with heap or something right but n is equal 10 to the fifth that's gonna be too slow so then i'm trying to find um a sort of a greedy mathematical solution and here it is which is that if the biggest number is bigger than the other two combined then the logic here is that let's say you have 100 or a thousand or okay 100 you have like 20 and 20 or even 20 and four or something like that then you know that um that what does this mean right that means that for we can the strategy here is to take one from the biggest pile and then just take one from any either one of the two piles and then keep on doing it because the biggest power is bigger than the smaller two compounds combined so you so the number of operations that you can do here is it's just equal to the smaller number of the r2 or the sum of um you know uh the sum of the two numbers because that's gonna be a constraint because you know you're never gonna run out the biggest number right uh and then in this case i actually have trouble to prove um which is that if you have some numbers that's just you know like they match up okay then what happens right then actually it turns out that you can just greet it um you could use or you could basically use every um you could use every pile all the stones unless there's an odd number um or like if there's an odd leftover then that's um the answer so basically that's pretty much it and the proof is kind of i don't know i for me especially during the contest to be honest i just um i just ran a lot of cases and i kind of guessed and yolo'd a little bit during the contest to kind of hope this was right uh and thankfully it was um but the proof is that you can kind of i think you could do a proof by greedy and always taking the biggest num biggest two piles and then kind of draw it down and then kind of do the math that way that's basically the way that i kind of prove to myself to submit um but yeah let me know what you think this is constant time constant space so yeah um cool uh that's all i have you could watch me during the contest next this is way mathy that's okay and this is all math you otherwise what happens it should come up you hey uh yeah thanks for watching hit the like button to subscribe and join me in discord um let me know what you think about this problem and the solution this explanation um and yeah do have a good day and a good weekend stay good stay healthy to a good mental health and i will see you next problem bye
Maximum Score From Removing Stones
path-with-minimum-effort
You are playing a solitaire game with **three piles** of stones of sizes `a`​​​​​​, `b`,​​​​​​ and `c`​​​​​​ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there are no more available moves). Given three integers `a`​​​​​, `b`,​​​​​ and `c`​​​​​, return _the_ **_maximum_** _**score** you can get._ **Example 1:** **Input:** a = 2, b = 4, c = 6 **Output:** 6 **Explanation:** The starting state is (2, 4, 6). One optimal set of moves is: - Take from 1st and 3rd piles, state is now (1, 4, 5) - Take from 1st and 3rd piles, state is now (0, 4, 4) - Take from 2nd and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 6 points. **Example 2:** **Input:** a = 4, b = 4, c = 6 **Output:** 7 **Explanation:** The starting state is (4, 4, 6). One optimal set of moves is: - Take from 1st and 2nd piles, state is now (3, 3, 6) - Take from 1st and 3rd piles, state is now (2, 3, 5) - Take from 1st and 3rd piles, state is now (1, 3, 4) - Take from 1st and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 7 points. **Example 3:** **Input:** a = 1, b = 8, c = 8 **Output:** 8 **Explanation:** One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty. After that, there are fewer than two non-empty piles, so the game ends. **Constraints:** * `1 <= a, b, c <= 105`
Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value.
Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
Medium
794,1099
1,617
everybody is larry does me going with q4 of the weekly contest 210 uh count subtrees with max distance between cities uh hit the like button hit the subscribe and join me on discord so i was able to solve this in about 12 to 13 minutes during the contest or during the virtual contest which is sad um so i think one thing to note this is that um there's a lot of things to read i guess that's i think that's the easiest observation so i wasn't sure so i took a look at the example the subtree was a little bit confusing uh well maybe not but then when i look at here the explanation was actually pretty good uh i was like okay subtree so that means that there's some you know um some combinations there and i was like that's gonna be a little bit like at this point i was thinking about some sort of um recursion type thing uh and uh some kind of running count with max distance um and then luckily when i looked down i saw anderson go to 15. um sometimes i miss it right uh at least miss it until like later on but this time i saw it early sometimes i don't know why it took me so long but so n is to go to 15 i was like okay then it becomes easy um maybe not easy usually because i you know it's hard to say something it's easy when a lot of people had trouble with this one but it became components that i was able to figure out because well the first thing that happens is that when i see n is equal to 15 i go well can i prove first 2 to the 15 something like that right and then the answer is yes because when you have you know when you take a subtree um on to one of the two to the 15 possibilities that describes it may not describe a tree but it might describe a subset of um a subset of nodes that we're trying to figure out you know the max distance and the max distance if you recognize is also um just the diameter of a tree which is uh something that um i've solved on stream before as well but definitely uh google it is a little bit of a prerequisite and also it's kind of annoying i would say because if you didn't know that or you're not familiar with diameter of a tree you're probably not going to solve this um maybe you could google it with like during the contest for like you know in general it makes it harder right um but once you know that then it becomes straightforward it becomes an implementation problem because you just have proof force uh backtracking or whatever uh on 2-15 uh on 2-15 uh on 2-15 and then for each of those uh sub for each of those notes each of those subtrees are possible subtrees it becomes um you know a diam max diamond problem um and or a diameter of a tree problem and if you know the literature you could find the diameter between of n times right and then when you kind of put everything together you could do stuff roughly and n squared to the end time and it'll be fast enough um and we'll go over my implementation after building that and you can watch me solve this live i did it pretty quickly i had a couple of off by ones because i didn't notice that these were one index until later on um and i was at a oh and i also returned the index in this uh the d in a silly way because i was just also off by one so that said like you know if i stopped in 13 minutes including off by once i feel pretty good about it um i don't know right um but yeah uh so now uh yeah so you know now that i've broken the algo the problem solving into multiple components uh this is what you know how i'm gonna go through it right which is that for each mask of this tree which means for each version of this tree um you know i put in the list you could do it in a number of ways i wasn't really consistent about it and then this just gets the diameter of a tree and then for each diameter of the tree we increment it from d right and this is just the results they ask you which is you know count the number of elements for each length and then you know that's it right and then this gets the diameter of a tree i naming is terrible during competitive programming but uh that's the possible diameter of the tree and this is a well-known of the tree and this is a well-known of the tree and this is a well-known algorithm so i'm not going to go with too much it's very google uh but basically the idea the short tldr idea behind that i'm going to retreat is that you could take any node on a tree you do a default search to find the farthest node and then you do that again meaning the farthest note you take that note you do a definition to find it no that's voice on that note and then that will give you the diameter of the tree uh and there are proofs and stuff like that i'm going to skip that because you'll have to do your research on that one but basically that's about how my code works um essentially uh i take the first node i do therefore search to find the farthest node and i do this thing that is that if uh if all the nodes are not visited then we turn negative one because then it's not connected it's not a tree so i just return negative one um yeah and then again if we are able to visit all the nodes then we take the previous folders and then we do a different depth first search again uh that's pretty much it and this that first search is pretty standard around tree depth research and just making sure that it doesn't you know loop and all that stuff uh by checking its parents and stuff like that so yeah so i was able to do this race quickly because i did recognize the end it goes 15-bit uh i think that for me it goes 15-bit uh i think that for me it goes 15-bit uh i think that for me that's the key observation the other stuff is be about a little bit more about knowledge and trivia in which you don't have to pre-work you don't have to pre-work pre-work you don't have to pre-work pre-work you don't have to pre-work uh i think it's just something to study about but yeah but that's all i have for this prom uh let me know what you think uh hit the and oh yeah and watch me solve this live next oh yeah going over the complexity of this algorithm so i forgot to um go with the bit mask a bit uh so this is a bit mask way of doing uh exhaustive checking every possibilities um you can also have done this with that tracking uh in which you make sure that it's a connected graph and stuff like that host but the way that i have learned uh from competitive programming mostly is that i just do this with a bit mask and what is a bit mask well bit mask is that this thing which will count from one to two to the n minus one right so basically this counts from someone like you know binary yeah i'm just writing a binary number so to this right um and the reason why i started at one is so that i don't have to start at zero because we if we don't count the case where there's no notes in the subtree that's the reason uh but now we start with one and we go to two to the n minus one um then for each of these uh so we go for every possibility and that when we get to line 54 55 you have some like binary string right oops that's four is not a binary number in case you're wondering but and what does this mean right so we do a for loop uh so position one that means word text one is a one so that means that vertex one is in the subtree right so that's basically what we're doing uh and then we have a zero in this case uh vertex 2 is a 0 so that means that vertex 2 is not in the subtree so basically what we're doing here is just doing every possible case which is the exhaustive search point um yeah so then now you may ask what is the complexity of this problem uh because i skipped it that's my bad um so in terms of um time as we mentioned this is going to go up to the n so 2 to the n is the number of loops uh you can see that we already do at least o of n work and we're gonna we're going to calculate um i'll go over the complexity of the this first but for now let's just say it's o if n is linear so that means that okay let's see so loop has two to the n iterations and each iteration does all of n work so total complexity if i could spell correctly is equal to o of n times two to the n um okay uh and let's kind of show this diameter i'll go through the diameter of the tree to go for the complexity as well um which is that okay so this is a set or this is linear so of n so far you know you can trust me on this one uh because it's just going through list and then we have two depth first search so then we have to look at the complexity of that first search and here you can see that because we never um there's no cycle and we look at each node at most once then that means that this is going to be linear right because we look at you know each node once so this is linear and that means this entire thing is linear uh but as you know that first search at least in this case uh in the worst case you can have um a linked list so this is going to take off and space in terms of uh stack space right uh and it's something that uh that's pretty much it uh because the actual space complexity for us it's gonna be n uh well all e where e is the number of edges because we have an etched list uh we have some o of n sprinkled in places but uh so all v plus g is your space complexity but um but in this case note that because this is a tree yi is the number of edges is always going to be vertex's vertices uh it's gonna be vertex minus one right so that means that it's gonna be over v and that means that the space computers complexity will be all real linear in the size of the input um okay i think now i'm good uh let me know if i you know let me know if you have any questions uh hit the like button to hit all the buttons and you can watch me solve this live during the virtual contest now account subtrees with maximum distance between cities so usually i refresh to see how many people have solved it and obviously this is not live so i'm going to take a quick peek just to kind of see if i could gauge the difficulty of the prom that would be ninth uh but of course this is not a real contest so there are n numbers from 1 to n and no one seems to have submitted to q4 yet that's what i'm just going to say uh anyway there are nc summit moment n you're giving an array direction of x from uv to x is a unique pattern right where the city is on three okay so there's a tree subtree is it every city switch like a subject this is usually strongly directed thing trying to connect the component phrasing but i don't know what you do find this up trees maximum distance between two same subtrees to go to d what this is very wordy okay you have these edges so i'll put three four zero what does that mean oh so for d one two's maximum distance two four is one two three subtree is two which is fair oh it's only 15 okay so that's what i'm noticing because i was like this is going to be really hard but it's only 15 then we can only look at the sub trees and basically this is going to be exhaustive uh maybe with dp this is only 15 and then you just keep track of the arrays and then just do math on them is that even true is it connected in a diamond of a tree okay i think that's all i got to do um okay this is actually not that bad it's just uh exhaustive search and the dynamic of a tree which is over n so this is going to be all of n times two to the n or something like that uh or n squared times two to the n uh okay i have ideas in my head i'm thinking about implementation that's what i'm doing now um yeah and this is all very interesting okay let's create an edges first i still like um to put them in uh in a in an adjacency list so yeah so that's what i'm doing now uh so maybe that's not necessary if but okay but now we are going to um yeah okay so now we just have d is equal to zero times n minus one okay and now we just do the exhaustive search yeah i've now i wish i was in this contest because i think i would have done really okay uh knock on wood um okay so this is mask if this is greater than zero i sub three at x uh and don't really even need it that way well weird but um okay so then uh max is equal to i don't know go subtree like i said numbering as well terrible but um okay and that's pretty much it for the framework and now we just have to get the diameter of the subtree right which is not that difficult and theory in theory so what is the diameter uh diameter is just two therefore search so let's do that um how do i get the first number of a set i always forget i guess there's a half does this have to be a set now is that it could be a list let's make it a list um and also let's just pass in the mask because i'm being a little bit silly um i know i wanted it to be a set okay fine let's i'm being silly this is i'm like spending a lot of time doing weird things and this is how you don't finish top 10 though uh okay but okay so now let's do okay let's see if oh let's also make sure there is at least one element i was going to add that tree but um okay so then first as you go to subtree sub zero uh and then let's just do it that first church i have just went somewhere but um of the first so okay so basically what we want is we want the furthest node as you go to none um and then okay so that's basically how you would do the diameter with some really weird bad code but uh to be honest this is like pretty much it's just about typing at this point and i have to kind of figure out how to do the typing part um let's do this first step is to go to distance uh through this as you go to node okay um otherwise let's go uh we wanted that first search for x or let's say we and these on edges sub node um if we did i do anything with the subtree um change it back to set if we is in s and uh i mean i'm a little bit rusty on the tree stuff just got back that's my story and i'm sticking to it so if note is or if we is not equal to the parent and we is an s then dfs we know distance one also have to do none more going furthest uh that seems to be really wrong so um okay uh is this did i mess it up because i think i count zero and this is actually from one to four so i have to do something like um what can max be is it that return none now we could just be zero at worse huh distance is greater first what does that mean the furthest step is more than that's not possible or maybe i'm just off by 100 for this distance that's also probably true let's just do this then yeah because i start with zero okay so then the first is that true i don't know let's see uh three four zero that's not right um oh i know because i have to check that this is connected uh i remember thinking about it but i forgot um so okay i have to see that's connected um oh man we're using variable names that's why one character up pretty okay um if s is not you go to visit it i'll return negative one and then let's just go if mx is if one continue uh let's not range what uh debugging is so expensive that's the sad part is that i know how i'm i mean i've been knowing how to do this it's just that i'm not doing it uh okay so c12 oh this is this wants to be three no n and one what am i doing and why is this one wall why is one out bounce am i missing something do i reuse the character somewhere is that right this is what i get for jinxing myself uh let's just print d why is this is at that mess up n is two so we have one element away so that's here what am i looking at the number the maximum distance between two cities right and it's one now because zero cannot exist i'm just really bad at this whoops uh so this is good uh i am dumb uh okay i don't have to put anyone to remove my print statement i guess so let's give it some it only because this retro contest i would probably fit one more okay let's go hey everybody thanks for watching uh hit the like button hit the subscribe button join the discord and i will see y'all next contest bye
Count Subtrees With Max Distance Between Cities
stone-game-iv
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. Return _an array of size_ `n-1` _where the_ `dth` _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. **Notice** that the **distance** between the two cities is the number of edges in the path between them. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,3\],\[2,4\]\] **Output:** \[3,4,0\] **Explanation:** The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. **Example 2:** **Input:** n = 2, edges = \[\[1,2\]\] **Output:** \[1\] **Example 3:** **Input:** n = 3, edges = \[\[1,2\],\[2,3\]\] **Output:** \[2,1\] **Constraints:** * `2 <= n <= 15` * `edges.length == n-1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * All pairs `(ui, vi)` are distinct.
Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.
Math,Dynamic Programming,Game Theory
Hard
1685,1788,1808,2002,2156
143
There are even today 11 times fruit rio de this problem only problem yagya not absolute end list this edition of verses in 12345 one to MP3 take and end definition of Venus which link year note tubelight note second world tour not third last not the sellout mode switch START SOME WORK LINK WITH LAST HERE LAST TO OPPORTUNITY 150 140 TO GROUND ACQUISITION ABCD CO REMOVE AND MAKE A GROUP OF OLD AND EVEN IN THIS WE CAN SEE BUT IF POINT SE 0512 21 2011 READ VOICE MAIL ADDISION LOVE YOU TO VOICE MAIL Inventions And Why She Does Not And Made Them And In The Manner Why Entries Will Be Easy A Manner To Give The Is Meet Least 20 Minutes After Doing A One-Sided Reversing Loop So Come Now A One-Sided Reversing Loop So Come Now A One-Sided Reversing Loop So Come Now To-Do List Demand letter this is my least to To-Do List Demand letter this is my least to To-Do List Demand letter this is my least to diverted to f i have too much f5 he only water and drink this is my phone list hoga post nfo lifeline commitment final match point after death oil reverse aa final match cost of mid of one day series who died Of every river this one sided and country least at Vikram Dev list will not be appropriate to merge Nehru 0.2 to 0.2 1.5 Hridaya this 6 0.2 to 0.2 1.5 Hridaya this 6 0.2 to 0.2 1.5 Hridaya this 6 Four times more problem in 2 directions C that understand with the help of food before moving to this position you have enough of two things First How To Find The Point That Set Alarm Yusuf To Reversal Interest This Is Already Made Videos On Both Of This Problem You Can Check Out Video First After Watching My Video Constructed S Videos After All What Will U Any Time You Will Find The Mid Point That dude take this desi drug don't show is gone through how they find a commitment seed them 2.5 want to have all the fun to 2.5 want to have all the fun to 2.5 want to have all the fun to head and will clients point now I am one and five 13151 point appointed here and have now want to be our division B .Ed and have now want to be our division B .Ed and have now want to be our division B .Ed minute darkness to make notice of middle point in the cases a middle will be to that interrupted now but select short notes - not with special effect first day notes - not with special effect first day notes - not with special effect first day every word you see how to reduce and half minute mid day after finding a Friend In Need Not Worry Be Happy Through Which Will Make Will Revert So Chatting And Wow And Okay Baby I Love You Will Not Get Mid-Day-Meal Mid-Day-Meal Mid-Day-Meal Arranged That I'll Spoil His Sacrifice A Point In The Second Half And But I will be amazed so remedies to individuals is to be taken of this point in this blog and what you did before national and international 80 will be nominated for all over the world who is in the rear seat if participant of which clearly that is situated of universe In English First President of You Can Greatly Reward As You Like And You Will Reduce The I Am Now Returning Previous And Which Will Destroy This So If Reverse Of Winter Reverse You MS Word From Amazon That Know What We Have To Is Applied And Based On What is the Name of the That Destroys Symbol What is the Third Step Strong List Match List I Businessman Whom the List 2nd Episode 351 That How to Make a Simple Liquid Form in They Do I Have to Make Sure Subscribe to This Point From Play Store Bill Gates channel for nanode make this link on a wiki which after that I posted on urd face low to hot side on question on how to put back this language monitor link will be broken Festival of Yamuna River Ganges water from the river of Winter Wear A This Point To 9 Withron In One Middle Age I Length I Reverse Mostly Additional Not Sunshine That I Forces Mays To Take Medicine Noida First Time But Reverse Of This World Wide Awake Toe Online More 210 Forces Thirunal Purpose Problem Time is the time and country for wedding reverse in any way to eliminate ok khush vol-2 eliminate ok khush vol-2 eliminate ok khush vol-2 that time complexity of reverse and will the can do and what will depart at will withdraw your family and they all should 253 quotes of the day in 9 Let's See What Will Be Presented A President Will Not Think Of Vector Generated by 120b to 152 Likes Subscribe and Ajay Ko
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
451
hi everyone it's Soren today we have a problem when we are given a string s and we need to sort it in descending order based on the frequency of the characters so what's that mean so for example in this case e is repeated twice R is repeated once and the t is also repeated once so we need to sort it so e should come first because e is repeated twice and the RT should be followed after e after these two Es so let's say another example let's say we have this example where we have three C's and we have three A's in this case so we can if the if characters are if we have a multiple answers then in that case we can return any of them so what it means for example in this case we can return both c a AA and uh a CCC okay uh let's take our this example and work on it so let's say we have a tree and in this case what we do our first step is that we are going over our string and we are creating a hash map or hash table and we are so counting the frequency of each character so for example in this k e is repeated twice R is repeated once and T is repeated once the next step is that we are adding our character to Max Hep based on the frequency of the character so we are going to have this Max Heap we are going to have e we are going to have R and we are going to have t and the last step the third step we are creating a new string and we are adding character by character so for example first we are taking from our Max Heap e and we are taking the how many times it's repeated twice so we are adding that to our new string the next one we are taking R and T is have the same frequency so it doesn't matter which one we are going to take first so we are taking r and the frequency of R is one again we are adding to our new string and the last one we are adding we are taking t is repeated once so we are adding T to our new string which we are returning and we are returning our result when we don't have any entry left in the max Hep first thing that we do here we are creating a hash map where our key is the our character and the value is being the frequency of that character so we are creating our hashmap and after that the next step is that our second step which is the creating a Max hiip in Java implementation the max hiip is a priority cue so we are sorting our values so we are sorting the charact we are sorting the characters by the frequency we are sorting by the frequency of the characters so for example in this case e would be first and the RT will be followed by E and the next one is that we are adding to our Max we are adding all our key set right so all our entries we are adding to our Max heip and the last step is we are creating a result and to our result we are adding all character until our Maxi is empty so at each step we are taking a current character our current character in this case would be for the example of tree would be e so we are taking e and we are taking the frequency what's the frequency of e is repeated twice so we are taking the frequency and we are adding to our result as many times as that character is repeated so in this case twice right so we are adding that to result and we are repeating the same operation until our Max Hep is empty and at the end we are returning our string that we have built so what's the time and space complexity of this solution the time complexity is determined by these three parts so adding uh for this for Loop this Max adding that to Max Heap and this while loop while we are building right so in this case the time complexity is log of n right going just over the string and adding that to our map this part is K log k is the number of the unique characters and the last part is that is n log K right so adding building our result so as um we are taking the upper Bond upper bond is upper boundary in our case is uh in log case so we are taking that as our time complexity for the space complexity is a again it's determined by this three data structure that we have here in the worst case scenario for all three it's going to be n so it's a three of n 3 n so we are disregarding the three parts so we are taking the uh n as at our time complexity okay uh that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
549
hey everybody this is Larry this is me doing a bonus question uh that haven't done before I have to remember to set premium because for some reason it doesn't always do PM let's do a medium because I think I'm liking a lot of mediums or something uh and then oh yeah to do and yeah let's go and hopefully no SQL phone I really just need the two escal bomb so then they don't come up uh all right let's try again I have to click on this again because that's I don't know all right okay that's good uh okay today is extra Larry problem is 549 binary tree longest consecutive sequence two all right so given a root of a binary tree we've done the length with the longest consecutive path in a tree a consecutive path f is a path where divided to consecutive notes in a path to five one it could be increasing or decreasing uh okay does have to be strictly okay probably the longest consecutive privacy this have to be from because I could oh no this is two one three okay so what this could be one two three over there okay I mean I think this is pretty straightforward maybe I mean no I wouldn't say straight for it but I think understanding is straightforward I think there's just some sort of um you know uh um how do I phrase it I mean it's definitely just recursion and you can do this in linear time but I think it's just very um it is just very easy to make mistakes is what I mean so okay but let's just get started then um yeah so um so then we have node and maybe the parent value something like this I'm not sure I'm not sold on this so don't hold me to it yet but basically and maybe a best variable that's outside um maybe something like yeah I think one more thing I wanted to do was something like uh doubter or something so that we could just be lazy about it I mean I think you can actually do the logic uh much more straightforward but I am going to do the logic much dumbest I don't make silly mistakes hopefully so let's see right so basically now we want to see um so they're really foreign so basically they're really um a couple of scenarios right the scenario is that this current node is the um the route that it goes basically it is the root of the sub tree that contains the longest consecutive sequence right so that's one thing that we'll do um and it's basically either um so basically it's either left uh how do I phase this I say increasing right left increasing is going to Traverse no dot left uh notice the parent and downturn in this case let's just say increasing means that you're going up so uh plus one right um right decreasing in this case as you go Traverse know that right uh node negative one and basically your best is to go to uh that's non-local at first and then in this case best is equal to Max of best uh left increasing plus right decreasing plus one right for the current node so that's basically just saying that left is going up right is going down and then you're just kind of combine it that way and then of course you have the other possibility of left decreasing uh by increasing and then this is just the same idea but symmetric right and then now and this is actually ignoring Delta because and the parent because this is just assuming that this coin the existing node is the node um so we don't have to care about the parent because this is to know that you know you turn your path or whatever right otherwise um if note that value minus parent dot value um let's just say a parent is not none and um if it is in I think I just want to make sure my terms are right uh if this is you go to plus Delta then okay yeah basically now this is saying that we are able to connect to the parent then we um we return Max of oh wait that's fine so if Delta is equal to one that means that we're coming down increasing path so then we want to we follow that in by left increasing right increasing plus one right and then else we return Max of left decreasing right decreasing plus one otherwise we turn zero because that means that we do not match the parent so we don't go up we don't yeah we don't go up that way uh none and stuff it just doesn't really matter I think in this case I have to say Delta is equal to negative one just to be precise and then return best at the way in hopefully this is right um oh because we've returned none and okay fine I mean this is good or obviously the test cases accepted as good but I'm just trying to think whether that is how much effort am I trying to do all right let's give a submit I'm not 100 sold on this is why I kind of hesitate it um but yeah shouldn't time out though um I'm gonna get time I'll be sad huh I'm actually surprised I mean I know that I do two of these but one of these will always be wrong oh I am dumb okay yeah okay I made a mistake I assumed that one of these will always be wrong so it'll be terminated early but because we don't eh I mean um yeah I mean implant yourself because uh yeah because each node is considered that by itself I think I could just add a cache and be over with to be honest uh I am a little bit lazy today I mean um so the right way to fix this to be honest is just by detangling the dependency that we have basically right now each one is calling the same path twice um instead of a regular depth research and that's why this is causing an issue I mean you could definitely solve it with like just memory memorizing it but this plot there's actually probably a queen away um to detangle them but hmm I mean the right way is just to kind of separate them out and do it twice but I think the caching is probably fine I'm a little bit tired today I don't know why uh so I'm just gonna uh yeah basically the idea behind this memorization is that you can only call each note with two different input types uh one is well one is that the note for every node all the parent is always going to be the same and Delta can only be one and negative one so we only call this is the equivalent of making it amortized depth research twice because you look at each node twice and this is why this solves it but I was but honestly I was being sloppy um I shouldn't have kind of resolved to this I probably this is definitely a cleaner way to kind of just um there's definitely a cleaner way to do this but I don't think I did it that way uh yeah I don't know let me know what you think let me know if you have any questions uh this is kind of an annoying one actually to be honest but hmm foreign I mean yeah I guess I could turn it that way I don't know I'm just kind of the way that I did it I think the way that I did it I tried to do it like I said um like very dumb um but maybe it was a little bit too dumb that I kind of messed myself up um because I think you could just be really careful right you could separate out the two logic one is um uh processing each note as the root and then the other logic is processing only the left or the right depending on the Delta right like um and I think that would because these two things um more or less mutually exclusive so we plot I kind of try to do everything too much at the same time but changing into case analysis I don't know how I feel about it I don't know let me know what you feel about this let me know if you have any questions uh that's all I have for today though so let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
Binary Tree Longest Consecutive Sequence II
binary-tree-longest-consecutive-sequence-ii
Given the `root` of a binary tree, return _the length of the longest consecutive path in the tree_. A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing. * For example, `[1,2,3,4]` and `[4,3,2,1]` are both considered valid, but the path `[1,2,4,3]` is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 2 **Explanation:** The longest consecutive path is \[1, 2\] or \[2, 1\]. **Example 2:** **Input:** root = \[2,1,3\] **Output:** 3 **Explanation:** The longest consecutive path is \[1, 2, 3\] or \[3, 2, 1\]. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-3 * 104 <= Node.val <= 3 * 104`
null
Tree,Depth-First Search,Binary Tree
Medium
298,1416
1,004
Hi friends welcome to my channel co destination so as we are continuing this challenge one code one day on my channel so daily we are discussing one problem and with detail analysis so today we are taking one very famous topic sliding window first we will discuss the Concept Behind This Then After That We Will Pick One Question On Very Beautiful Question From Lead Code That Is Medium Level And We Will Solve Using This Leading Window So Basically This Is Technique That Help To Solve The Question In Very Efficient And We Can Visualize How We Can Think That Approach Once We Learn The Concept So Let Me Share My White Bort First Minimize My Screen Or So There's Already Mention Sliding Window Let's Minimize This One Or So Basically This Is The Approach Name Sliding Window So Basically Here There Are Two Word Sliding And Window Basically we will slide the window And we will solve this We use this approach How we can define the window size How we can slide So this is all about this concept like how we can with the name it is suggesting that we have to slide The window is nothing but a particular size like suppose I assume the window size is three so in this case suppose we have this array so in this case a for every window size like three sizes there are total possible 1 2 3 4 5 five windows So here we're sliding this window first we're taking this window a in the concentration so after that once we slide that so the next window will be this one so in this way we're sliding this window and we're all solving the question so suppose I'm Taking one example suppose there are one question a we have to find the maximum sum of length l given length like in this case three a from this given are so like for each window we will calculate the total sum like for this window total sum is Six for the next window Total sum is nine for the next window 15 13 and 11 So we have to maximize this sum here and so maximum value is 15 So we have to return the 15 So this is the basic approach how we can use this finding Wind concept to solve a basic question and how we will use in the code for defining the window so for defining the window we will use two variables like i and j here so our window size defined between i to j like window size is three So I to j there are total three element and every times when we iterate I will move j and i pointer both together like here if I move one times then j move one times that is window size always fixed in this case so in this case window Size is fixed and we will assume this approach like slide i and j variable every time and will calculate in this case like first we will calculate first will calculate the sum initial sum our initial sum will be two 3 p 2 p so in In this case it is so and we slide our so our new sum will be our old sum plus whatever value at the index it will be added because in the next window it is adding the value this z value is adding value in the window And this I index indicate that we are unaware of that previous index value so we will remove that previous index value so we will add this index value and we will remove that index value for every case and suppose again this I slide here so I will be Here and j will be here so again that a new value will be previous and s value plus a j and my a so every time we will remove i element from previous sum and add ga value in the previous sum so in this case We will get we can get a new sum and we will maximize this sum so we will maximize this sum and here in this case we will get the output 15 so in this case we can solve this question using this approach and this is the Fixed size of window but like there is always a variation we can do so in many questions there are such things like the size of our window which has been given three times is fixed, we have to vary it in variable length so question two The question varies but this is our basic approach or we follow it like if I write its pseudo code then what do we have to do, basically we will take I loop, take zero J, at zero our one loop will run which is our J till where. Our total will be A, if the length of the array is A, in this case to 3 4 5 6 is from A, then our Y will move to Sen and what we will do in this is we will take our sum and in the sum we will add our We will continue to do this by taking the value of j, whatever our value of j will be and as many times as this sum value of ours, first we will make it initially even zero here, what will be the sum zero, what will be our three value, what will be our initial three value, then it will be 325 s. Our j here p What will be the value of our h What will be the value of our And we will do j plus as our window continues to move forward and thus we will keep on maximizing here, what will we do in max, we will keep on maximizing the previous sum which will be our previous max and which will be the new sum so what will be our max here. Which will be our maximized sum will come here, so basically, if we want to solve this question in this way, then we can use sliding window, so we will use this approach in our today 's question, so I would minimize it. 's question, so I would minimize it. 's question, so I would minimize it. And let's see how we can solve it, so I will remove it here. Okay, so what is our question, we have given a binary are basically binary contains only zeros and ones and we have given also k indicates that Number of bits zero bits we can flip like in this case if I talk about here we can only do two beats so if I talk about this morning then here our if we flip this two zeros then Our total size will be five and if I talk about this morning and it has two maximum zeros then if I flip them then it will be one then our maximum size will be six so basically here if we look at this question in a different way then basically we will get that morning We have to gate that maximum window in which what is the total number of bits, what is the number of bits which is zero bit, that is the two maximum and one is maximized in it. Basically we have to gate that window in which the maximum number of bits is two. I mean. Let's see in this case, this one of ours which is giving output is of 10 size, so in 10 size, if we move this window, then we will see that our sub-section of 10 size will be there, in this we will give maximum. sub-section of 10 size will be there, in this we will give maximum. sub-section of 10 size will be there, in this we will give maximum. If we swap three bits, turn zero into one, flip sorry, then here our maximum length will be 10, so we can solve this question with the help of sliding window. First, let us discuss how to apply this approach here. So I remove this, okay, so here we see this question, my example is www 0 and www zero, okay, so the maximum of our bits is our two, meaning we can make maximum two zeros as one, so what will we do? First of all, here our window size is not fixed, so first we will create the window size in which maximum to A, then our I suppose is here and J is also ours here, we will move J until our maximum to we consider. Propose my number of J in your window. I have taken the Webble number of zeros. How many zeros will there be in our window. If we keep moving J, then here P is our one, so here too our value of J has not moved. Will also move here, as soon as the value of our J comes here, then what will be the total number of bits in our window, at this time our A is here and J is here, then our total number of bits will be here like First zero must have become one and then two must have happened, then our total number of bits is how many twos are there in this window. Basically, we can consider this as our window because it fulfills the condition that is being said here. That we have to maximize the number of contigs once in the array if you can flip at most I mean in this case two bits we can flip so here we will take a max, we have to maximize this which will tell what is the maximum size. It will be our morning in which we can only flip two bits, so what happened to us in this case, our five will be initially, then what will we do, we moved z and moved here, so what happened to our max here which is the value of z. Three is done, okay, so now our J is done, this is of greater importance, so basically this will not be considered, so you our window was till now, okay, so we will move it and reduce the size of the window. To do this, now the size of our window has been reduced, it will be from here to here, so our come here has been moved here. Okay, our come here was not for this reason, now it will be moved here because we have to reduce the window size because our number This window, which was our previous window, has more than the number of zeros allowed in it, so we cannot consider that, so we will move the i. Okay, so here we can still see our window, our current. This is the window, the number of bits in it is three, so still we cannot consider it, so we will take our maximum which is possible, the size of the window till now will be five, the size of the window will be the means maximum which will be the sub array in which our At most zeros number of zeros will be equal to two k will be equal to 0 sorry will be equal to tutu that is our fifth size so we will consider the fifth size till now and will move our window size further then our I and J both will move together. So in this case, because the size of our window has been fixed, the path is fine here, now our window size will be this, so i will be here and h will be here, still we can give the number of zeros in our window size. Th is greater than 2, so now our i and g will move, okay because our size is still fixed, right now we are Maxima, we cannot increase the window size right now, so our i came here, okay, and the value of h came here. So this window size of ours is F right now, I came here, now here we can give our window size is F and our current window in the window, this one has a total number of bits of three, so still we will not consider it. Okay, then we will move Aa and J, so the size of our next window will be from here to here, so it will be here on this index, basically okay and the value of our Aa will be here on this index, so in this case What happened to our previous, which was here on our eye, so we checked on the eye that our zero was there, this zero has been removed from the window, so what will be the size of our zero, it will be two, so what is our current window? If the size of zeros is two, then we can consider it, so this window size of ours which is the current window, the total number of zeros in this is two which is allowed and our window size is five, so our earlier five which was max. And five remains only, now you see the green window which is our window which is the current window, this one has the maximum number of bit two, so now we will increase the window to J, our J will move here, so what will be our current window. So this is our window from A to Here we count zero to zero which is allowed then we will increase the size of our window basically how we are increasing the size of the window when our number of zero is allowed zero then in that window we have two more less days To is, then I have expanded my window, so our window of window has come here, so our window's which is the j pointer and the pointer is telling this is here and here we have shown that which is the j variable I think j is the index p. When our zero came, we increased the zero count, here we came to three, we saw that our maximum count of zeros is three, which is greater than two, so we cannot consider it, so our size of five will be five, we will update it. If we don't do that, then what is ours? We will be sharing the size of the window. Now our window will be sharing its size, so our I which will be like our window, then I will be plus, so I will come here and we do not want to move J, so our J is this. It will remain at and our first I was here, so our index P was zero, so we also have to reduce the zero count, so what will happen to our this T, will be to. Okay, now it is allowed, so we will calculate its size and this. If we update here, what will be our size - tooth 4, 5, 6, then we will update it by six. Okay, our last index has come, so our tension ends here, we cannot move beyond this, our maximum possible window. If this is possible then our max value will be six, this will tell us that our maximum size of six is ​​possible in which the maximum size of six is ​​possible in which the maximum size of six is ​​possible in which the total number of bits that we are flipping is equal to two, which is fine because we are counting zeroes. According to that, we were shrinking and expanding our window, so here we can see that this size of ours, this one will be our sub array, the maximum of which is zeros to two and this will be the array in which our maximum number Off one will come, if we convert this zero to one and flip this zero to one, then what will be our total tooth? We can get 4 5 s sized teeth which will be maximum, same approach, we will follow the same approach for now. If we write this in quotes then it will be more clear. Okay, so what do we do? We say, what was the zero in our initials? We make it zero. Okay, then we will increase the size of our window. If we are using y then we will increase the value of y on y. What is y? The value of h which will keep increasing and we will keep calculating the number of zeros along with it. So if our number of zero comes number of i, if sorry it doesn't come, we are increasing h, then our j index will be P. If zero comes, okay then we will We will continue to calculate the number of zero, we will put it on plus, so I take a variable on y, we have to keep in mind the zero count also, number of zero which will be initially zero, okay if in any instance our joy number of zero which is number of zero It is greater given that our allowed zeros are total, which means that the window size is more than our required zeros, so if we want to shrink the window size, then to make it horn, we had discussed, what do we do? What we were doing was increasing the value of our aa, which was shrinking the size of our window, so what will we do, we will increase the value of aa, okay, but here we also have to keep this thing in mind that if our aa which Our IA index is beyond that, if any of our data is I think value is on I index, if it is zero then it is zero, sorry if it is zero, then what do I do. The number of counts which is ours of zeros also has to be decreased, so I decrease here. Okay, so this is how we can do it, so and I take a variable, why do we have to maximize it? This is the maximum number of contiguous ones. If we want to find the length, then we are at this point, we take the max lane, its initial value. Inger dot man value will be ok, if we want to maximize it then here we will take our max len which is mdot max and max len ok and how will we find out the size of the window, our proposal is this j index i index or p j index so what is our size? If we extract it in this way then j my a p will be the size of our current window, we have maximized it and what we will do in the last is that we will return our maximum length, so let's run it and see, we used the same code. We have written the logic which we have discussed, it should run OK, so both our tests pass, if we submit it, OK, then it runs, it is taking 4 milliseconds and bits is 27.7 users of Java, so this is an optimized approach. 27.7 users of Java, so this is an optimized approach. 27.7 users of Java, so this is an optimized approach. You see how we Approach discuss sliding window and apply it here in the code in the same manner as we discussed so here I think if max we can remove the max length because our last value is telling that our The maximum allowed which will be the window of the sliding window will be the same. Basically, if we want, we can remove the max from here. The last value of i, we can also calculate the window size with its help, so here we will make it j minus i. So why did I do Z mine aa at I would have suggested or minus, I would have floated, so I would have had to do a minus here, so the same thing I did here, if we submit this, I think this run, then this will also run, or it is taking 2 milliseconds and the bits are 100.00 off. Users, so you have seen how 100.00 off. Users, so you have seen how 100.00 off. Users, so you have seen how we did this by removing a max length here, this increases its time, okay so this approach, we saw how we can apply our logic to the sliding window, basically this variable size of the window. We are sliding the one whose window size is not fixed. Okay, so I hope you have understood this solution. If you understand our logic and intuition and you like it, then like our video and subscribe. Do it and because we put such videos on daily basis and discuss such questions and we understand new topics in easy way and also press our bell icon so that you get notification of new videos, so thank you. Thank you guys for watching my video
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
442
hello and welcome back to the cracking fang youtube channel today we're gonna be solving lead code problem 442. find all duplicates in an array before we read the question prompt i would just like to kindly ask you to subscribe to my channel i have the goal of reaching a thousand subscribers by the end of may and i need your help to get there so please subscribe to this channel because you're getting a lot of value here and it's going to help you get that job in fang so make sure to subscribe get that high paying job okay given an integer array nums of length n where all the integers of nums are in the range from 1 to n inclusive and each integer appears once or twice return an array of all the integers that appear twice you must write an algorithm that runs in bigo of n time and only uses constant extra space and it should be noted here that you can actually use a data structure for the answer creating the result array does not count as constant extra space in case you were wondering how are we supposed to return a list if we can't even do that it just means you can't use any extra space for the actual computation itself so let's look at this example where we have four three two seven eight two three one so obviously from here we can see that the duplicated numbers are going to be 2 and 3 and that's what we want to return so how are we going to do this if we had you know extra space allowed to us then we could just maintain like a set uh and then if we've seen a number um you know when we see a number we're going to put it into the set and if we see it again then that would be added to our result array and then we would just go through the entirety of our array here and the ones that we see twice we would just add them to our result array but obviously we're not allowed to have constant extra space so we can't do that but one thing to notice here which is going to allow us to solve this problem easily is that the values here are going to be in the range of 1 to n and why this is significant is that for 1 they're all positive numbers and two we can actually express every single index in our array here based on the numbers in our um range here so let's think about this if we have the number four then we know that we can mark the value at index four in our array so this is index one two three four okay this is getting messy i think index four is going to zero one two 3 4 we can actually mark this 8 as a negative and why are we going to do that we're going to signify that we have seen a 4 by marking the index 4 with a negative and that way we can keep track of whether or not we've seen a number before so when we see a number we're going to mark the value at that index with a negative and then if we see that number again when we check the index if the index value is negative then that means that we have already seen that number so for example let's go through this and we'll kind of rewrite the array so we see 4 and we're going to mark index 4 as negative so 0 1 2 3 4 actually sorry it needs to be um the index minus one because um we need to be careful since it's the range of uh one to n apologies for that so it needs to be the index um of the value minus one so it's actually gonna be index three we wanna mark as negative so 0 1 2 3. so we're going to mark this 7 with a negative here then we get to the 3 and we want to mark index 2 with a negative so 0 1 2 so this 2 is going to become negative then this 2 we want to mark index 1 with a negative so we're going to mark this with a negative 3 and then we get to the 7 so we're going to mark index 6 with a negative so 0 1 2 3 4 5 6. we want to mark this negative then we get to the eight so we want to mark index seven with a negative so zero so actually it's going to be this one and then we get to this two and we're gonna say okay we need to mark the index one with a negative but it's actually already negative which means that we've already marked this index with a negative which means that we've already seen a two so that means to our result we can add a two because that means that we've seen it before similarly for this three we're going to mark you know three minus one so two with a negative but we can see that zero one two this index is already negative which means that we've already seen the value three so we can add it to our result and then we're gonna do the same thing for one so one we're going to make mark the zeroth index with a negative and then we're actually at the end of the array so that's how we get 2 3. so to recap what we want to do is we want to go from left to right through our array and we want to set the value in the actual array to you know um the absolute value of whatever our current number is because remember we can set it to negative minus 1 we want to set it to we want to multiply that value so nums um times minus 1 right and if the current number so if minus so if it's already less than zero that means that we've seen before right um because the only way it could be zero if we've already seen that number and we've already marked it seen before and we want to add it to the add to res right otherwise we just want to actually mark it so mark as you know minus and that's what we want to do we'll just accumulate all of our um duplicates in res and we'll just return res so it's super simple uh it is a little bit tricky if you don't um kind of have the algorithm click for you but basically what we want to do is we just because we have the range of one to n we know that we can basically mark all of the possible values right so if we see um since it's not possible to see a zero right because that would mean that we'd marking the you know nums minus one which is negative one but since it's in the range of one to n we can actually express every single value in here uh by you know the absolute value of the number minus one and we'll be able to mark those indices accordingly to indicate that we've been there so enough blabbing let's go to the actual code editor and see how we're going to implement this and like i said it's super simple it's about 10 lines of code so i'll see you in the editor in the code editor and it's time to write the code so remember that we're going to need a array to actually store our result so let's define that variable so we can have it for use so we're going to say res is going to equal to an empty list and now what we want to do is iterate through our numbers from left to right so we're going to say for num in nums basically what we want to do now is extract the number at you know whatever index is represented by our current number so what does that mean so we're going to say at index is going to equal to nums of whatever the nums of the absolute value of num minus one remember that we're going to be marking the index minus one uh to mark whether or not we've seen a value before so we're going to get whatever the current value is there and remember that we use absolute value here is because we could have set this number to be negative in a you know prior iteration so we want to make sure that it's um we take the absolute value because then we would be potentially in uh accessing the wrong index here so we want to make sure that it's always the absolute value of the number minus 1. now what we want to do is we want to check whether or not this at index value is already negative if it's already negative then that means that this num um we must have seen it already because we have marked that index as being seen before so we're gonna say if at index is less than zero and remember that we can do this because we know for sure that all the numbers in our array are between 1 and n inclusive so the only way that it could possibly be negative is if we had marked it as negative because we've seen it so if it's negative we're going to say res.append and we want to append the res.append and we want to append the res.append and we want to append the absolute value of whatever our number is because that indicates that we've seen that number otherwise what we want to do is we want to now mark that index represented as so abs of num minus 1 oops minus 1. and we want to multiply whatever value is at that index represented as the absolute value of num minus 1. we want to multiply it by negative 1. and then what we want to do is return res so at the end that's what we want to do let's submit this make sure that it works and int is not subscriptable uh oh this is numbs whoops and now if we submit it okay that should work yes okay cool so what is the time and space complexity for this algorithm well the time complexity is going to be big l of n because all we have to do is make one parse through our nums from left to right and you know we just process every single number in there and all of these checks are going to be constant time checks so we're good there so it's going to be big o of n and then space wise it's going to be big o of 1. for this problem we don't actually um count the result array as space because we need it for our solution there's no way to do it without it so we're not going to count the res here and you know it's not possible to solve it without this res array and again it says uses extra space so this is just for the solution it doesn't count so we can consider this a big-o of count so we can consider this a big-o of count so we can consider this a big-o of one solution because we don't actually um modify we do we just modify the original input in place we don't create any new data structures or anything to help us with the processing so that's going to be your runtime complexity and your space complexity uh that's how you solve this problem again it's super simple as you can see it's like what 10 lines of code maybe even less given all the spaces so yeah pretty straightforward this is a pattern that you're going to see in a few leak code problems where you're given this kind of range from one to n and you're going to need to mark whether or not you've seen something based on you know this pattern of basically the absolute value of your current number minus one to indicate that number has been seen and yeah you just do that because we have the range one to n so you can't get those um out of index uh lookup so that's how you solve this problem i hope you enjoyed this video hope it made sense for you if you enjoyed this please leave a like comment subscribe uh if there's any videos or topics you'd like me to cover please leave them in the comment section below and i'll be happy to get back to you guys i just need to know what you want to see and i'll make those videos otherwise have a nice day thank you for watching bye
Find All Duplicates in an Array
find-all-duplicates-in-an-array
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algorithm that runs in `O(n)` time and uses only constant extra space. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1,2\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` * Each element in `nums` appears **once** or **twice**.
null
Array,Hash Table
Medium
448
434
hey everyone welcome back and today we'll be doing another lead code four three four number of segments in a string and easy one given a string as written the number of segments in the string so if there is a Hello is my name is John there are five words so basically just return the words how many words are in this string so that's it we can use just the split but we are not going to do that but we will code it so it will be pretty easy if you see how it works so count for I in range of length at s and now we will check if I is equal to 0 or s minus s at index of at that certain location is equal to a gap and this should be true or the other case like I if it is not equal to a gap then we can just increment our counter by one and after we are done with this we can just return account so that's it let's see if this version I will explain how this works and it is very easy to understand but I will still explain how this works so what is happening here is when we have like an index 0 Let's Take a smaller example like a b and c d so at index 0 we are going to start this way this whole thing will become a true so and this will be also be true so the counter is increased by one count is one and in the B case uh this is not true so it is in neither of this is true so it is not going to run and in the other if you increase our counter like now the counter is that this position not the counter but I index yes the index is at this position there is nothing happening here and when the inter counter I am again saying counter but this is just our index when our index is at C we can see that the I accept if we subtract I minus 1 it is equal to a gap and I add the certain location is not equal to a gap so it will also increase it by one so we are going to return 2 in this case and that's it this was it
Number of Segments in a String
number-of-segments-in-a-string
Given a string `s`, return _the number of segments in the string_. A **segment** is defined to be a contiguous sequence of **non-space characters**. **Example 1:** **Input:** s = "Hello, my name is John " **Output:** 5 **Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\] **Example 2:** **Input:** s = "Hello " **Output:** 1 **Constraints:** * `0 <= s.length <= 300` * `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.: "`. * The only space character in `s` is `' '`.
null
String
Easy
null
1,877
hi so today we are going to solve lead code problem number 1876 minimize maximum pair sum in Array it is today's problem of the day so in this question they will give us a an array and you have to try all the possible way in which you will make pair of two elements and in which element you will get minimum of Maximum pair you have to return the that sum of the maximum pairs value let understand by one example suppose uh take this array as input so here we are having Four Element 3 5 2 3 so we make two pair one pair maybe one pair we can make three and five and another pair we can make two and three or in other way we can make pair of three and another pair of five and two so the maximum sum of in first way is 3 + 5 = 8 but the of in first way is 3 + 5 = 8 but the of in first way is 3 + 5 = 8 but the maximum sum in second way is 5 + 2 = to maximum sum in second way is 5 + 2 = to maximum sum in second way is 5 + 2 = to 5 + 2al to 7 so we have to return the 5 + 2al to 7 so we have to return the 5 + 2al to 7 so we have to return the sum of the minimum pairs of for each possible way you have to decide which way is giving the minimum of maximum sum and you have to return the maximum sum of the minimum way so for that we have to try all the possible way but if you'll try all the possible way the time complex time complexity will be factorial n so definitely we are not going to solve on that way so the easiest way will be sort all the element because we know one thing if one element is largest so if we make pair with another largest one then it will be give you maximum value but if flare is already maximum suppose here five is already greater so if you make pair with smallest one the sum their sum will be minimum and under for remaining way also we will do the same second largest with the second minimum and we will do same thing cursively so this will give us the minimum of the and we will uh we will take the what is the minimum value what is the maximum value in this way all the pairs and we will return that maximum value so the our procedure will be P we will sort the all the element in increasing order suppose uh we have sort all element in the increasing order and we'll make pair of largest one with the minimum one again second largest with second minimum third largest with third minimum and so on so uh we will first sort the all element after sorting we will make two pointer one pointer will point to the minimum and second pointer will point to the maximum one and we'll make we will make their sum and we will store their sum in one temporary variable after sorting again we'll try the second largest with second minimum and we'll make their sum and if their sum is greater than already sum value then maximum sum of this way will be the newest one so we will update again we will try the next largest with next minimum there are some and we'll again compare so on we will reach till until the left value is minimum than right value we will do the same thing so uh let's uh look on the code so we have done the same code we have sought the elements in increasing order and I have made one left variable and one right variable left variable will point the minimum one and right variable point to the maximum one and I have a make a Glo variable answer we will take we will make track of the maximum element and if the sum of the current pair is greater than the maximum one we'll update the maximum otherwise uh we'll make the same answer and we'll increase the left pointer and we'll decrease the right pointer after the this for Loop we will return the answer
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
141
hello everyone my name is alvaro and in this video i will be solving another problem from the blind lead code 75 problem list today i will be doing problem 141 which is called linked list cycle so let's read the problem statement a given head the head of a linked list determine if the linked list has a cycle in it there is a cycle and a linked list if there is some node in the list that can be reached again by continuously following the next pointer here it's just simply saying that they're giving us a pos parameter which is called position and that just tells you where the loop is so for example pos1 means that the node at position one is where the loop starts here position zero but it's not really passed on to the method so don't worry too much about that so return true if there's a cycle in the linked list otherwise return false so example one obviously has a loop as we can see example two the same thing and example 3 doesn't so if you want to get to start working on this problem by yourself now be the time to pause the video because i'm going to explain how to solve this all right so i guess let's try to think about the easiest approach first right um we could for example use a hash table or a hash set right and we could just traverse the notes of the graph right and whenever we encounter a node that has already been visited and as we visit each node we store them in let's say a hash set uh whenever that happens then we know that since we've encountered that node before that means that there is a cycle by definition right because we've encountered a node that we've visited already and that only happens in the link if the link list has a cycle in it and that could be an approach it definitely solves a problem but there is an approach that uses big o of one space because that approach that i just mentioned before uses big o of n space because in the worst case scenario every single node in the linked list is stored so let's try to think about a different way right how can we use big o of one space to do this so if you want to take the time to think about it uh pause the video because i'm gonna explain it now so the main idea here would be to use two pointers and we're going to use something called floyd's cycle floyd's algorithm which is an algorithm to detect a cycle in a linked list it is also known as the tortoise and hair algorithms you might have covered that in your algorithms class it's a fairly famous algorithm but don't worry if you don't know it this is why i made this video so the main idea behind this algorithm is the following we're going to use the slow or the tortoise pointer and then a fast or the hair pointer and the main idea is that we are going to start with a slow pointer in the first element of the list and we are going to use the we're going to start the fast pointer or the hair in the second element of the list if there is any the main idea is whenever the slow pointer is moved because we're going to move it every iteration of the cycle we're going to move it by one node and the hair or fast node is going to be moved by two nodes right so for example in the first iteration we would start well first we start with a slow at three and the faster two and the slow one after the first iteration will go from three to two while the fast one will go from two to four because one and two and how do you know this algorithm works well let's try to think of the two cases uh and whenever there's a cycle obviously if there is no cycle simply what we need to do is we know that the fast node is always going faster right so whenever the fast node is equal to a null pointer or another case which i'm going to discuss in a little bit when that happens then we've simply reached the end of the cycle and since we've reached the end of a sorry we've reached the end of the linked list and whenever we've reached the end of the linked list that means that there is no cycle so suppose that the list just looks like this like a three two zero and a negative four and we start with a slow and a fast this is no cycle right so we move this slow by one and then we'll move the flask by two now what we have to check for is whenever either the current fast pointer is equal to none that means that we have reached the end of the list or whenever the next element that goes after fast is equal to none because we're going to be moving the faster let's say if we are at some point or right whenever we update fast we're going to say something like fast is equal to fast dot next but suppose that fast.next is null but suppose that fast.next is null but suppose that fast.next is null then this will throw an error because none this ha does not have a next parameter in it so that's why we are checking whether fast is equal to none or fast dot next is equal to none in this case you know there will be no cycle because fast that next would equal to none now what happens right if there is a cycle well there are two different types of cycles you can have a cycle of odd length and you can have a cycle of even length so let's explore both cases so we start with an with a slow on the fast pointer and this would be just a cycle that goes from negative four to two so first we move the slow one by two and then we move the first one from two to negative four because we move it by two are they pointing to the same node no then we continue remove the slow one by one and then we go from the negative four to the two so that's one and then to the zero so that's two and at this point they point towards the same thing so there is a cycle so the case where there's an odd length we can see that it works but what if there's an even link cycle so suppose that again the negative 4 is posing as pointing towards the 2 and then we start again let's start with a slow here and the fast pointing towards the 2. so we move the 3 by 1 so towards the two and now the first one points towards the one same thing here now s points towards zero and one goes to negative four and then to two now we move this one by one and then we move this one by two and as we can see they both end up in the same thing so they detect the algorithm so yes it works both on even length cycles and odd link cycles so let's get to code it so we start first of all if one of the like the base case right will be if the head is none meaning that there is no linked list then obviously by definition right there is no cycle so let's start with that so if the head is none then we return false and now let's start initializing the variable so we can say slow is equal to head and fast is equal to head dot next and we're gonna keep looping this right the main idea is we're gonna do this until both pointers point to the same thing and whenever that happens we know it's true so we can simply set a while loop that says while slow does not equal fast whenever we exit that then we will return true and the only time that we will return false we will have to check within the while loop and when is that well we discussed it before in the video so that's if fast is equal to none or if fast dot next is equal to 9. and remember you should always check this first because if fast is not and we put this before this right then whenever fast is done this will throw some sort of error because if fast is none then none does not have a dot next parameter so it's always that you check it's always important that you check fast equals none before this so this is the case we return false and if that's not true then we just keep going and we just have to move the pointers so slow is equal to slow dot next and fast is equal to five stat next dot next and this should work obviously as usual in all my videos um you know runtimes are inconsistent but i tested it before it beats like 90 of submissions eventually just have to submit it a couple of times good enough there you go so yeah now let's discuss the runtime and the spacetime of the algorithm so the spacetime complexity of this algorithm is big o of one because we're simply using two pointers and it's definitely not proportional to the number of nodes and the runtime of this algorithm is big o of n where n is the length of the linked list um it is possible that we visit the nodes more than once however it will not be quadratic so just keep that in mind it's still big o of n but we may visit more than like you know we might visit like a node more than once especially if there's a cycle right but you will not be looping this like n times if that makes any sense so it's definitely still big o of n so yeah um that'll be it for this video i hope you enjoyed it uh make sure that you hit the like button which helps a lot the channel and see you in the next one bye-bye
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. 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. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **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
Easy
142,202
697
YouTube welcome back today we have this problem it's a degree of an array we have given non-empty array of non-negative given non-empty array of non-negative given non-empty array of non-negative integers the degree of this array is defined as the maximum frequency of the of one of its elements your task is to find the smallest possible length of the contiguous and this is important contiguous up array of norms that has the same degrees as Norms okay so for this one we're saying two because first we have to do two things we should found the degree and for this example that the degree has two because two and one are appeared to and after that we want to find the shortest suppery so we can just find we can one two three one we can find one two three or two three one for this one or maybe one two this one or two three or two 2-2 basically so the smallest one is two 2-2 basically so the smallest one is two 2-2 basically so the smallest one is two so we're turning two for the other example we have one two three one four two and the degree is three because we have two is three times and after that we want to find the shortest sub array so it will be six because it's just two we can just remove this one and just get the four right and the forelift and for light and just put the length of them and that's it so that just make um a quick um yeah delete content delete all the content and let's just okay so um let us and let's get this okay so we have this nums okay and what we want to do is that we want to put our solution into two sections well the first section is that we create a hash table that finds the um the each number and how many this how many times this number was appeared that will find it right and we find it's left to know how um how long the sub array will be so first we want to create an a table the uh the stores maybe we'll create two tables that Stores um the degrees and the frequency of each element and after that after we're creating the table we will create a count to get the smallest or the smallest array of the highest degree so for this one is a degree but this degree is bigger so we take this one this degree and if we find something smaller we just get it so the solution will be like that first of all let's define our variable and I guess that we have two things three we have lit lift because we want to get the left and right so we're gonna get lift this because we want to get the length of the Subaru so let's lift and we will make it um a map so it will be new map okay and I will say let's try it will equal the okay and I will say um let count because I want to count each and each one how many times it was uh appeared physically and I'll say for let I equals zero or less than nums the length I plus let X equals nums of oil and what we are going to do in this Loop we are going to uh to set uh the right and left so we are going to say if this number is not in lift uh store it in lift otherwise store it and write okay and set the count of this number so what we're going to do is that we want to store first of all let's say if it's not in left if and left dot has X I will say um left dot sit X and we give it the value of I okay and we'll start in the next one I will say right our story and write also right that's it um X and the value of I okay and I will say uh the count that's it and this is quite important we want to get the count so I just put X and I will do something like I will put one or whatever was in the account so I will say give me um count dot get X or oh sorry count get X or zero okay plus one so we make sure that we have each and each number and we have how many each number was appeared and the other thing that we have we put the left or right so basically we could when we have the left and right and we just to get minus both of them we will get our um our uh our summary length so I will see lit and uh res and it will equal Norms the length at the beginning I will make it equals lens I will return this line yes okay and this is the should be the length of the sub array so how we can modify this lens first of all I get that I want to get the degree okay so degree will equals um count no sorry math dot Max everything in count so I'm getting the um dot values I'm getting the biggest value in counts okay and after that we will start to Loop again so I say four let X let's just use offload of count dot keys because I want to look through the keys and I will say um if count dot get X equals degree that means this is the highest number was frequently uh appeared what we are going to do is that right now we have the wrist is nonstop length but we are want to make sure that we find the smallest sub array that this degree is appeared on so what we're going to do you remember that we have the right and left so what I'm going to do is the outside risk will equals raise um math dot Min between risk and write of x minus lift off X oh sorry that I get right the get X and left dot get X but we have should we should add plus one because we are talking about the indexes and that's it so first of all we have the right and we have the lift and we stored each side each left uh each element that was in left we store it once right maybe we could have it twice but we have left and right because we want to make sure we want to get the length of the small separate and we have the count to get the degree so first of all we make the first Loop and we say that if the element is not in lift storage and left and store it in right also with its index to give it give the value on the index and set the count of this element and if we find the count just add it to one it doesn't if you didn't find the counter I'll give it value just one and we will see the other thing that we have the next step is that we have the ours which will be the lens of the sub array and we have our degree the degree we'll get from the count we just get met.exe get from the count we just get met.exe get from the count we just get met.exe and we just to get the count the values and we get the bigger ones and after that we make another loop through the account keys and we say that if count Keys equals the degree I will say uh res equals the mean value because one we wanted to short this one between the old rest and the right and left plus one okay so for right uh right and left both of them like that I will get the length of the array because like let's say it's one and two so one uh plus two and minus two plus one it will equals um for this one it's uh it's zero and it's two so zero plus minus two it will two plus one it will equals three so the length of a three so just the index over the right with the index of the left ones the index of the right plus one it will equals um the length of the array and submit and Paula and let's let us see what the best solution was so the better solution was that we create a map only one map okay that's decent okay so we create our map and after that I have the Maxi frequency okay and in the one map I Loop two times the first time I would say if um const num equals of I okay and I'm seeing a frequency of num equals undefined if we don't find it so what we should do we should in the map the num will have the frequency of one it will have its index first index itself lost index otherwise I will say nums of oil in the numbers of frequency I'm increasing the frequency I'm saying frequency of num and I'm putting the Lost index and equals I and the max frequency it equals makes the frequency and frequency the okay so basically I'm getting the for each Loop are updating I'm making sure that I am getting the max frequency so I will get with the end with um this solution is pretty dope but I guess it's quite similar because it's two loops and we have corn snom and this is the same this is exactly the same this is only the different way and it just it has instead of having three tables it just have one table and each element has um has three um it has an object value and the object has three values oh that was decent okay so um that's it for today's video hope that my solution was quite good if you like my solution make sure to subscribe hit the notification Bell so you will never miss a video and see you in future problems
Degree of an Array
degree-of-an-array
Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`. **Example 1:** **Input:** nums = \[1,2,2,3,1\] **Output:** 2 **Explanation:** The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: \[1, 2, 2, 3, 1\], \[1, 2, 2, 3\], \[2, 2, 3, 1\], \[1, 2, 2\], \[2, 2, 3\], \[2, 2\] The shortest length is 2. So return 2. **Example 2:** **Input:** nums = \[1,2,2,3,1,4,2\] **Output:** 6 **Explanation:** The degree is 3 because the element 2 is repeated 3 times. So \[2,2,3,1,4,2\] is the shortest subarray, therefore returning 6. **Constraints:** * `nums.length` will be between 1 and 50,000. * `nums[i]` will be an integer between 0 and 49,999.
Say 5 is the only element that occurs the most number of times - for example, nums = [1, 5, 2, 3, 5, 4, 5, 6]. What is the answer?
Array,Hash Table
Easy
53
1,980
let's do elite code find unique binary string okay given the array of strings that does not appear in numbs okay finally string okay so you have zero one zero hidden one what if there is no answer so let's think also this answer and there's also this answer expected rows of nums to have size in between four and four oh okay each string has to be because there's only two elements that means each string also has to be two digits inside okay makes sense and i think because of this there's always an answer so we have n in between 1 and 16. i could try all possible combinations that'll give that's to the power of 16 which is six thousand five hundred uh sixty-five thousand five hundred sixty-five thousand five hundred sixty-five thousand five hundred thirty-six so that's fine thirty-six so that's fine thirty-six so that's fine that would work would trying all possible combinations be you know okay to do or is it really just 655 i think maybe there's more to it than that so zero all the way up to um to the power of 16 this is up to 16 digits if there's up to 16 digits four bits all of them turned on the value of that is going to be um so that's zero one two three four two power four minus one so that's fifteen so you have 16 digits then it's to the power of 16 minus one yeah so if you're from zero all the way up to six five three five actually it's better to just say you know two one bit shifted 16 bits to the 15 bits to the left 16 bits to the left minus one so that's so i want to go into all numbers within this range which isn't a lot and then put this stuff in a set and just check and return the first one that doesn't the first one you can't find so i'm pretty sure in c plus there's a way to convert a convert into binary string okay this is cool bit set that's kind of a problem two string substring 16 minus i'm stop size 16. that's how you can convert it to binary i use an ordered set strings and then just for auto s in nums dot insert s store all those strings in a set go through from zero one bishop to 16 to the left minus one if you can't find the number then return that okay um like haven't really analyze the time complexity properly because this is at most this will be in constant time to figure out the binary string or something because it's 16 right and this is almost 6 000 65 000 a few times 65 000 by 16 i say 32 for good measure we get uh 200 okay 2 million is still fine i think this might be a slow solution but i'll give it a go oh wow it's pretty quick cool um the memory usage isn't that great maybe they sorted it so what happens if you sort the nums and yeah i could sort the nums i don't need to use a set then maybe just go through and say i starts at zero so if nums at zero comes at i if s doesn't equal to that return s so this might have better space and time to be honest also why i is less than so let's actually do this i want to keep track of the i variable so i less than nums dot size here i just wanted to turn no let's do is to zero and i could say nums that's not equal to nums then this may be a problem so let's say if i is less i is greater than or equal to i is equal to numbers of size or this return s here just kind of thing uh yes that should work because if we get up to the end i wouldn't think this would be out of bounds but i have this condition so if i'm at the end that means i can find it this number is definitely not in the num so i'm going to return this string okay that's a lot of slaw but the memory is better i can't really have that support for what i don't think um we get to find out if there's a solution that has less time and space but this is best times best space
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
1,846
hello everyone welcome back to the channel so today we'll solve the daily challenge from late code so let's see the question first which is maximum element after decreasing and rearranging this is a medium level problem and you are given an array of positive integers array uh perform some operation possibly none on AR so that satisfies it satisfies these conditions what are the conditions okay the value of the first elements in Array must be one uh the absolute difference between any two adjacent element must be less than or equal to one okay and in other words ABS that mean absolute value of array of IUS AR of IUS one is less than equal to 1 for each I where 1 lesser than equal to I lesser than AR do L okay this is a zero index are okay abs of x equal to absolute value of x perfect now uh there are two types of operations that you can perform uh perform any number of times okay uh decrease the value of any element of array to the smaller positive integer rearrange the elements of AR to be the uh to be in any order okay so return the maximum possible value of an element in Array after performing the operation to satisfy the conditions okay so the question is very easy and we can we have the two operation decrease and rearrange the array and we need to make sure that the first element of the array must be one and the absolute difference between the two adjacent array must be less than equal to one okay and uh and we need to find the maximum possible value of the element uh after performing the array okay so let's see the example one uh as a input equal to 22 1 21 so you can see that this is not the first element is not one so make it one and then it will be two then it can be two and then it can be two as for the question and then it can be one doesn't matter so this is how the largest element will be two in this array so let's see the next example which is array so the array has 100 1 and th000 okay so 100 is not one uh so it will be one then uh this should be two because the maximum it can be two uh because you know what they have given that you have the condition that absolute value between the element of two adjacent element will be less than equal to one okay so then it can be two maximum then the third element can be three maximum because then only the absolute value Val absolute difference between them will be one okay so the maximum element as per I say that it will be three so that is why the outut is three and this is the last example at equal to 1 2 3 4 5 is already in one kind of shorted order so you can see that first element is one and the difference the absolute difference between everything every ad elements is one okay so that's why we don't need any changes so the maximum value is five here so the output is five okay so now let's solve the question so how can you solve the question that we can short the element yeah after shorting you can see that in this case we find out the one if there is not one in the array what can you do we can have some extra integer which we can replace every time and we can check what will be the maximum value so let's solve the question by writing the code so let's Sol the array first okay by using the short uh function AR do begin AR do end then what can we do so we can have we can use a array integer x equal to Z okay and every time we'll just increase the X okay and I = to0 let's have a for the X okay and I = to0 let's have a for the X okay and I = to0 let's have a for Loop for 0 to add size minus one okay it will go up to 0 to n minus one where n is the sorry okay yeah so what can you do right now that we can uh say also use that the first element must be one so for that case uh to check everything we can use that X every possible time it will be plus one because we need the maximum possible value uh it can be maximum one and we just add it at minimum I'll tell you uh why I have taken the main and the array of I okay so X will give the perfect answer because let's see the example two here in this case after shorting it will be 100 and th000 okay perfect then uh in the first itation where I equal to Z we got one so we don't have any kind of changes so minimum of x + 1 is = to 1 and add of Y minimum of x + 1 is = to 1 and add of Y minimum of x + 1 is = to 1 and add of Y is 1 so minimum is X will be one for the first time and when the second time it will appear it will happen uh then the array of Y will be 100 and 100 then it will be uh 1 + 1 it will be two so it will be uh 1 + 1 it will be two so it will be uh 1 + 1 it will be two so the X will be the new X will be updated by two okay and now x equal to two then in the last case there will be th000 and the when comparing with the th000 and here will be 2 + 1 3,000 three will be here will be 2 + 1 3,000 three will be here will be 2 + 1 3,000 three will be minimum so three will be added at the uh X and it will be the maximum of this whole array so we'll just return the X as the answer now we'll just run this code I hope there have not any kind of Errors yeah as you can see that this is a accepted code now let's run the code and before running the code let's analyze the code first okay you can see that we have used the shorted shorting algorithm which takes up to uh n login time in the case and we have taken a o of in for Loop so the time complexity for this case will be what o of n log n okay so what will be SP complexity we have not take any kind of Extra Spaces uh we just take X which is the constant every time and so that's why the space complexity will be o of n which is a constant space so yeah that is it okay this is the space complexity and the time complexity so now let's submit the code and I have submitted and let's see I hope there will not have any kind of erors yeah so that is the thing uh we have run this code and this is a uh good code and that is it thank you guys for watching this video I'll see you in the next time
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null
1,277
in today's problem we have to find the number of a square within a given matrix and what are squares square means squares of ones so even just one cell is itself a square in it and if you take 2 cross 2 it can be another square if we have 3 cross 3 that is another square so largest possible square size would be 3 cross 3 since the number of rows is 3 here so you have to return the number of such squares so i have just added a couple of examples here so for example this one in yellow is a square of size 1 cross 1 another this blue square is also a square with 2 cross 2. so let's see a concrete example of this and we had already seen one problem which was very similar to this and we will also be using uh exact same methodology that we used there so there the problem was find the largest square within this matrix of all ones so there we had to return just what is the largest possible square so that would have been the problem we would have returned 3 cross 3 or 9 but here we have to return the count of all the squares irrespective of what dimension they are so this would be k cross k that is k rows and k columns so let's see one example this is a given matrix it's a binary of 0 and 1. so first of all what are the squares of size 1 so these are the squares of size 1 what is the count here it's 10 then what are the squares of size 2 so we can take this part let me draw in this piece so once we have already seen size 1 cross 1 we have 10 now let's see 2 cross 2 so we have this one then we have this one and similarly this and this so we have 4 squares of 2 cross 2 then what is the next would be 3 cross 3 so this is just 1 square of 3 cross 3 no other square of 3 cross 3 can there be 4 cross 4 no because it's limited by the minimum of width or height so 3 cross 3 is 1. so what is the total 14 plus 115 so how we will solve this problem so let's see uh first of all uh whatever grid whatever cell is having one we will straight away add that count then how we will find the other shapes let's say we are here uh let's say we are looking at some cell somewhere in the middle let's look at generic case so we want to find how many squares are ending here so how many squares can end here one if it's zero then none of the squares will end here we are trying to find this cell so we want to find uh how many squares are ending here so if 2 cross 2 above it is 1 so if this is the scenario and this is 1 this is given if it's 0 we are not even calculating we will put it 0 here since no square can end here if it's 1 then we know that at least 1 square is ending here which is this square itself then we look at these three cells that is top left and top left so we take 1 plus y 1 due to this one so we know that there is at least one square ending here min of top left and top left so whichever is minimum let's say top left is 2 that means let's draw it again so we are here this is one this is two that means two squares are ending here and we will start from first row and we will solve everything for first row what will be the square ending here zero squares ending here one only this square here also one so first row we have solved let's say we are somewhere in the beginning and we will put the count here which denote how many squares are ending here so let's say here it's 2 here it's 3 and here it's 1 so here if it's 1 here it's 2 that means this block was originally one so let's forget this two this would be one in the original block its count is two and two squares are ending here that means what are those square 1 cross 1 and 2 cross 2 it's not possible that a 3 cross 3 square is ending somewhere so here it's 1 so 1 will be this and if this 3 cross 3 square ends here that means its count will be 3 there are 3 squares ending here because there is a 2 cross 2 also hidden here so if the count here is two that means these all four should be one so we have expanded this top left similarly we expand this three means in original matrix it was 1 here and here so it was like this and here it's 1 that means here it has to be 0 because if it was 1 we can see that 1 square is this other square would be this so whatever is the minimum of these 3 that will be added to it if it's one now let's come about how we will find these so what the space we need uh one simple thing is to keep a space of same size as the input array so this will be a kind of copy of this original array first row will be populated with this and when we are here we know that left is nothing top is zero so if left is nothing we will assume it zero and here it's one so it will be one top left is also zero top is also zero left is also zero so one plus min of zeros so it will be one now let's come here our top left is zero so minimum is zero so one plus zero is one now we come here top is one left is one top left is one so one plus min of these three which is one so two similarly here it will be again two minimum is one here it will be zero since it's zero here it will be 1 then here it will be mean of this is 1 so 2 mean of these 3 is 2 so it will be 3 and you can verify that 3 squares are ending here one is this itself one is this 2 cross 2 and 1 is this big 3 cross 3 now we will add all these so we have 3 2 5 1 6 4 10 12 plus 3 15. so do we need this entire space so we had also made optimization in the earlier problem that i said finding the largest square of ones so we only need this left top and top left so we are solving this problem row wise so first we have already solved this row then we come to the next row and when we are solving this value and so we proceed from bottom top to down and left to right so when we are let's say solving for this position here we have already solved for row above it and the cells before it but this cell and after this the rows are not solved so we can just keep track of one array which is same as number of columns so whenever we are solving here we will see what is the value of at this column so when we are solving column j we will see what is the value on this column so you can think of this as a solution of previous row before starting this row so first we are solving a row below it we need the top so we already have this so after calculating this we will replace this with this because this will no longer be required it will be required only here in the very next cell which will it will act as top left so we will have two more dummy variables top left only top left one extra variable and when we are calculating here we can use this left this is already there top is already there and after calculation we will replace this top and this top whatever it was earlier will act as top left for next value so we will just save this top in top left before updating this so let's write the code for this so first we will write it in c plus then with little modification we can write it for java and python as well so m is number of rows matrix dot size and we can add a boundary check as well if matrix is empty or not but here it's given that this is at least one similarly a number of columns is also at least one so i'm not adding that base check so uh when do we need to solve if matrix i j is one if matrix i j is uh zero then we know that no square can end there so straight away it will be zero so if matrix i j equal to 1 then we will solve something else counts j equal to 0 and top will be if i is 0 that is first row so for first row there is nothing on top of it so it will be 0 else it will be counts j so before updating this value we store it in a temporary variable left equal to if j is 0 that is for first column there is nothing to the left so left will be 0 else counts j minus 1. this is your to exist since we solve for column j only after solving previous column and then counts j equal to 1 plus min of top left and top left if you are having trouble in this solution first try to solve it with space m cross n space then try to optimize that you only need the previous row and not the rows uh above that so we are not storing that in order to save the space then result plus equal to counts j so if two uh squares are ending at this cell we will never solve for this cell again so we have to add that to the result which is the total number of squares and also we will update top left now so whatever was the earlier top now becomes top left for next cell but if it's the last cell then there is last column in a row so there is nothing to the right of it so for next it will come to the beginning so there the top left should be zero so if it's last cell in a given row then make the top left to zero reset it else whatever was the earlier top and that's it we will return the result and this works for this case let's try this second example and the answer matches for both the test cases so let's submit it and the solution is accepted here so we will do the same thing in java okay so min is not here we have to use math dot min and it does not accept the pull so we will use it twice so find the min of top and left and whatever is the result find the min with respect to top left so it works now so let's submit and the solution is accepted in java as well finally we will do it in python 3. so it works as expected in python so let's submit and the solution is accepted in python as well so if you are having trouble with understanding this space optimized solution you can look at the previous question where i had first solved it with the same space as the matrix size itself and then we had optimized that to just use uh kind of one row of this matrix the space is order n so what is the time complexity here time complexities uh how many number of elements are there in the matrix we look at each cell once and the space complexities order n time complexity order m n space complexity order n
Count Square Submatrices with All Ones
largest-multiple-of-three
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3. Total number of squares = 10 + 4 + 1 = **15**. **Example 2:** **Input:** matrix = \[ \[1,0,1\], \[1,1,0\], \[1,1,0\] \] **Output:** 7 **Explanation:** There are **6** squares of side 1. There is **1** square of side 2. Total number of squares = 6 + 1 = **7**. **Constraints:** * `1 <= arr.length <= 300` * `1 <= arr[0].length <= 300` * `0 <= arr[i][j] <= 1`
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Array,Dynamic Programming,Greedy
Hard
null
1,192
Hello hello guys welcome back to decades and this video will see the critical connection to network problem which established code number 12192 in this problem can be solved by using the general co adamkhor brijesh no latest video problem statement in this problem drops number from 0 connected And electronic media network connections between noida and witch represents a connection between services crush laga remove will make over unable to reach time to network in order to understand were basic while in these great lines that is there nothing but and connections in witch can actions can They remove enough to separate 10th from latest remove this connection from one to the whole withdraw from one to three and again from 2nd id subscribe moving increase the number remove corruption and increasing number of units and want to know connection to remove are you can C But You Can Reach From One To 4 This Is The Only Critical Connection For Election 2014 9 A Look At This Stage Four Five Hour Se Also Critical Connection Because This Will Be Creating To Different Components 10000 Remove Bechain The Great In Two Different Components And Collection Person's Collection Difficult Questions From One To 457226 Shyam Basically Already No Renewal College Direct Connection Only Can Remove Only One Day At A Time And Want To Remove Time When Body Must Be Put In Place At The Time You Can Only One And Definition Of This The problem can be reduced to present in the video of the Tarzan Decoration below you can check that video is against full explanation about this problem you can simply apply the same logic and the code and will work only thing you need to in order to solve. This Problem You For The Agency List And Ofton Forget You Need To Justify The Tarzan Sale Garam So If You Remember Tarzan Singh And Amit You Don't Please Like My Video Liquid Latest Simple Code In The Giver Connections And From This Point To You Will Find Jobs In Tamil Nadu And Will Not Be Exactly 1000 Videos Subscribe Times As Well Whenever You Discover New Discovery Channel Lotus And Ishwar Processing All The Different Modes Saw A Few Verses Of Wood And Freedom Comment Below And Tried To Help Impossible Like And Share More Videos And Subscribe Our channel in order to watch more of the program in videos 0
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
58
hello everyone in this video i'll be going over lee code number 58 length of last word the problem description is given a string s consisting of some words separated by spaces return the length of the last word in the string if the last word does not exist return zero a word is a maximal substring consisting of non-space substring consisting of non-space substring consisting of non-space characters only so for example if we had the input s equal to hello world we would output five because the last word in here which is w-o-r-l-d has length which is w-o-r-l-d has length which is w-o-r-l-d has length five for the solution to this problem there are a lot of different ways you can approach it one most obvious way would just to go through the entire string of characters locate the last word and count the amount of characters in it now this solution would be a little bit hard to program and wrap your head around therefore the fastest and most optimal solution to take 0 milliseconds of runtime would be to work backwards so the way you want to approach this is start from the end now as we're starting from the end let's look at the um rightmost character this is a blank or a space now here we don't really care about this character uh because it's not the first letter so what i mean is as we continue we notice that the second one is a blank the third one is a letter this is a letter d so we can create a counter that will store okay there's one letter here so the length of the last word currently is just one because this is the first word we have found going from the end so therefore is the last word going from the start now let's move on we notice that there is an l this is a second letter therefore the last letter now the last word now contains two letters let's move on there's an r now we know that the last word contains three letters moving on there is an o now we know that the last word contains four letters moving on there's a w now we know that the last word contains five letters once we move on once more we notice that there is an empty space once there's an empty space we notice that this word is complete therefore the length of the last word would be five in this example looking at this one more time let's approach the second example we notice that the first one is a space we don't really care about this second one is a space again we don't care now the third one is the beginning or the ending of the last word here we do care about so once we notice that there's a u we're gonna set a counter and now we're gonna keep on counting until the last word is finished we go over to the o we increment counter we go over to the y we increment counter so now we have three now we come across a space so now we know that this word is complete once we come across the space we can end the program and return the number three because that is the length of the last word so this is how we can solve this problem let's move on to coding it so now in order to stop start programming this we have to first program the loop that will go from backwards to forwards of the string let's write this out now we need to initialize a counter that will count the length of the last word inside the loop we need to figure out when we need to start counting so once we hit the first character that is a letter we need to start counting that as the word so let's write if s at position i is unequal to a space in that case we can start counting now we need to figure out when we need to stop and in that case we'll need a boolean so the what reason why is suppose we have hello world suppose you have a sequence like this now as soon as this program starts it's going to come across the first space now over here we notice that if it's not a space then we have to continue then we're going to come across the second space and then we're going to come across the first word and by that time we're going to finish the word we're going to have counter equal to 5. then we're going to come across a space so once we come across the space you have to write else if sf position i is a space we need to break however there's one problem with this code in the beginning the first character we see is a space therefore if we write something like this it would just break automatically here but then we run into the problem if we remove this line of code while we're going through we'll have no method of breaking out of the loop therefore let's initiate a boolean full found equal to false once we first start finding the work we'll set false equal to true sorry um found equal to true and then we'll write and found what this does is basically when we start off at the end where there are spaces we won't count these once we come across the first letter we will state that okay we have started finding our word once we end finding the word and we come across a space we'll write okay we have already found our word so now let's break and at that point we can just print out our answer as you can see the runtime is 0 milliseconds
Length of Last Word
length-of-last-word
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **Explanation:** The last word is "World " with length 5. **Example 2:** **Input:** s = " fly me to the moon " **Output:** 4 **Explanation:** The last word is "moon " with length 4. **Example 3:** **Input:** s = "luffy is still joyboy " **Output:** 6 **Explanation:** The last word is "joyboy " with length 6. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only English letters and spaces `' '`. * There will be at least one word in `s`.
null
String
Easy
null
455
hey everyone welcome back and let's write some more neat code today so today let's solve the problem assign cookies we're basically given two input arrays one is the greed factor of every child so every child has a certain greed Factor the higher the number the more greedy they are which means they require a larger cookie and we also have a second array which gives us the size of every cookie that we have so consider the first example down here we have three children this is how greedy each of them are and the rule is that each child can only be given a cookie that is greater than or equal like the size has to be greater than or equal to the greed factor of that child so we can give this child this cookie but we don't have a cookie big enough for this child or big enough for this child because the only other cookie we have is of size one this is two and this is three our goal here is to satisfy as many children as we can so basically each child has to be given a cookie where in other words as many children have to be given cookies as possible we don't need to give a child multiple cookies that would be wasteful we don't want to waste any cookies but we want to try to give each of them a cookie now we can't give these two children a cookie so we can only give this one a cookie in which case we end up returning one that's the max number of children that can be given cookies so the question is now how do we solve it how do we do this optimally well you can imagine that there is a Brute Force approach perhaps we go through every child in this array we check okay this is one then we have to try to find a one or something greater than a one in this array suppose this array actually had a two in this spot then maybe we go through this array and maybe we see the one first then we say okay we'll give this child a one then we go to this two and we find a two and we say okay we'll give this child a two that technically works even though this isn't efficient the time complexity would be o of n * M the time complexity would be o of n * M the time complexity would be o of n * M where n and M are the size of these two arrays but think about it this way what if we actually saw this two first and we say okay two is good enough for this child and then we'd only have a one left one can't be assigned to either of these two remaining children so depending on the order of these arrays this approach actually might not even work so obviously the order is relevant we would want to give every child the smallest possible cookie that we would have to so we can save the bigger cookies for the children that are more greedy in other words it becomes kind of obvious that sorting is going to be helpful to solve this problem and what we could do is sort this array s to ensure that we find the smallest cookie that satisfies each child first but that would not actually improve the time complexity it would make this problem possible to solve but if we end up sorting the first array as well then we kind of know that the values towards the beginning of this array are going to be what's going to be matched with the values towards the beginning of this array and actually we can take it one step further what we can say is we can eliminate the repeated work for example if we got to one here we would iterate over this array trying to look for a value big enough for this child then when we got to two we'd do the same thing we'd start at the beginning of this array looking for a cookie big enough for this child but if we maintain two pointers one pointer which of course is iterating over the children and a second pointer which is iterating over this array and we save the spot of this second pointer we can actually eliminate the repeated work we can get the time complexity down to Big O of n + m at least that's what it would O of n + m at least that's what it would O of n + m at least that's what it would take to iterate over these two but we know we do have to sort this guy and we have to sort this guy so the true time complexity is actually n log n plus M log n and let me show you how we would do that why it works just to make it more interesting I'm going to add a two and a three here so obviously these two arrays are already sorted suppose we start here we get to one okay then we want to start looking for a cookie we start at the beginning we see a one okay one is enough for this kid so one child is happy now that second pointer down here is now going to be incremented to the next spot because we already used this cookie but this is convenient for us because why would we want to look at this one anyway if we've already used the cookie and not only that but imagine if we actually had a cookies of size let's say a zero even though I don't think that's possible in this uh problem but just imagine that we did we had a couple zeros and then we had the 1 2 3 what we would have done instead is we would have started here we're looking for at least a cookie that's greater than or equal to one then we'd go here we'd say Okay zero nope not looking for that another zero nope and then here we'd find the one and not only is it enough for this kid but we know this is the smallest possible cookie that we have that makes this kid happy and then now we're going to the next value so here we're not going to have to look at these ever again because we know that the next child is going to be greater than or equal to this child anyway at least like their greed Factor so we don't ever want to look at these cookies we're starting here and that's actually good for us here to make this kid happy we need a cookie of two we see we have a two here great shift the pointer here and shift this pointer here now we're looking for a cookie of size three we have one so we made three kids happy the result would be three in this case suppose this cookie didn't actually exist maybe it was a two then we would take this pointer and end up shifting it out of bounds and now we have no cookies left so whether we have one child or 10 children remaining it doesn't matter we were only able to make this many happy so we would return that in other words the way I'm going to code this up we actually don't even need to keep track of how many kids we made happy because as you can see we're doing this in a greedy way we're trying to make the kids with the smaller greed Factor happy first so if our ey pointer ends here that means we were able to make this kid happy if the ey pointer ends over here that means we were able to make these two kids happy if we can shift the ey pointer all the way out of the array that means we were able to make all of these kids happy and the ey pointer here would be at index 3 so we'd be able to return three so now let's code this up what I'm going to do is first just sort the two input arrays G sort and uh s sort and then I'm going to have our two pointers I is going to be the pointer in Array G and J is going to be the pointer in Array s they're both going to initially start at the beginning and we're going to keep going while our ey pointer is in bounds so in bounds of G and remember what we're actually going to return is I itself because that will tell us how many kids we made happy now we want to know is the cookie at index J greater than or equal to the greed of the child at index I in other words if this is not the case so I'm going to take the opposite of this I'm going to say the greed factor is greater than the size of the cookie that means we need to take our J pointer and shift it to the right while this is true we need to increment J because we're looking for greater cookies we know this array is sorted so if we keep incrementing this we will find greater cookies but it's possible that our pointer ends up going out of bounds so before we even make this comparison let's just check J is less than the length of s and this is true then we will keep looking for a bigger cookie now even after this Loop is finished it could be possible that we went out of bounds so let's check if J is less than length of s that means we found a cookie so what do we do when we find a cookie well all we need to do is increment I because we made that child happy so let's move to the next child but also we are using the cookie at index J so we should probably increment index J as well we can do that on one line if you want but it's not like a big deal now if this is not the case meaning that Jay went out of bounds we did not find a cookie big enough for the child at index I then we can kind of just take a shortcut and break out of this Loop if you want to make this code a tiny bit more concise you can I guess take this out of the loop and just say if this ends up equaling that then we break out otherwise we do the increments you see down there but I mean shortening this code really isn't that big of a deal so I guess I wouldn't waste your time on it let's run this to make sure that it works as you can see on the left yes it does it's pretty efficient even though the runtime doesn't indicate that if you found this helpful please like And subscribe if you're preparing for coding interviews check out n code. thanks for watching and I'll see you soon
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
1,361
Hello guys I am Lalit Agarwal welcome to you all on your own coding channel code fix made by you made for you so let's start now today's lead code problem aaj ki lead code ki problem kya bol rahi hai achha before going towards the problem na one minute Dish for those who have understood this problem well and who want to try it on their own, look at the question, there are some tricky parts here. If you have understood them, then after that these questions will be very easy. It is important for you to understand what is the first and important part, that is, a bicycle should never be built here, if a bicycle is built then it will not be a valid tree. We are discussing the points and what not. There can be such points after which your valid binary tree will be disqualified, he said, okay, so first of all, what is your binary valid point, that a cycle should never be formed, he said, okay, never repeat any node of yours. Why should it be because here we have read one more thing that we need only one such tree and only two trees are needed if it is possible and we don't want that too. He said, okay, then what else do we have to check somewhere else? Even if you are not able to do any repetition, it is okay, it is very good, you have understood this also. The third and important thing is that you have to understand that you have to see that you should become binary in the same number of notes as the person has spoken. So there should be less nodes and not more notes. Think a little about these three points and then try to do this question. Yes, this is a little tricky. This question in itself should not be interpreted as yes or no. Yes, from us, take these three points, if you brush up a little on these three points, then this question may arise. Said, Okay brother, there is no problem, let's see once. Well, those who did not understand the question, they should take it. There is no need, first of all let us easily understand what this question is trying to say, after that we will build its approach and then finally we will move towards its implementation. Look, what was this question trying to say? Question I asked myself. First of all, one A is given, what is the number of nodes that we have, it should be four only, so this is one, this is two, this is three and this is four, okay, we have four notes, said, yes, in this. There is no doubt anywhere, you have four notes, okay, this one is its left child and one is its right child, its left child and right child denote, what are these nodes with zero index doing, which is their own node, say okay. This is the zero index. Said, yes brother, so whatever is the zero node, it has zero index. Above the zero index, the left child one has one and the right child one has two, okay, there is no problem, okay here, which is its index. Isn't it yes, this is the zeroth index, and zeroth is its value, what will remain of it, will it remain zero, so like this is one, so what has become of this one has become a value in itself, it has also become a node and first. Whoever is telling this on the index, it has been denounced, said, OK, so what is the meaning of -1 here on the left so what is the meaning of -1 here on the left so what is the meaning of -1 here on the left side, it does not have any child present, similarly what is the meaning of -1 on the right side also. That neither is there meaning of -1 on the right side also. That neither is there meaning of -1 on the right side also. That neither is there anything present in the left side of the cell nor is there anything present in the right side of the cell. He said this after understanding it. After that what did he say? What is the second index? Left cell is three. He said. Okay, so add three to the left. He said, what is there on the right? There is nothing on the right. He said, okay, leave the right one. Then this is the fourth index. It is not the fourth index. Which index will it be? He said, okay, zero. Yes, this is the third index, what is the minus and on the left side of the third index, it said, it is okay, it means nothing and what is the meaning of -1 on the right also? There and what is the meaning of -1 on the right also? There and what is the meaning of -1 on the right also? There is nothing on the right side, I understood this thing and said, Yes brother, I understood it, when I made it, then I came to know that yes brother, I am able to make only one and only one tree, which is this Apart from this, no other tree is possible, it means that it has been qualified on all the conditions. Said yes brother, it has been qualified on all the conditions, it is a valid mine tree, so what did you return True? There should not be any doubt, this thing should be so clear, he said, yes brother, this thing is clear, there is no doubt anywhere in this, let's see the second example once, look, come here, I saw the second example when When I formulated the second example, it became something like this. Now tell me, is this a valid binary tree? I said no, this is not a valid binary tree. The reason being behind is that the left child of Saro was also present and the right child was also present. Present was very correct, there was no problem anywhere, then the one and the two are fine, both of them together are pointing to the same node. How is this possible, does this happen in any tree? If not then what have you returned in the last place? Have you made a false return here? Understand this point very well. He said, OK, one more one. We are looking at the example here. What happened in this is that the zero node is Pointing to one, he said it was very good, there was no problem, but at the same point of time, the one which is one started pointing to zero, does this ever happen? Bane said in the tree, no, this does not happen either. What return have you made? Falls have you understood? I said yes brother, I have understood, so basically see, which of your points have to be kept in mind, first of all we will keep our points in mind, then we go on marking ours and suggest that This zero is pointing to zero one, said it is ok, this one is pointing to three, suggest it, said ok and the three which is pointing back to zero, can this be possible in a battery? He said, 'It is be possible in a battery? He said, 'It is be possible in a battery? He said, 'It is not possible brother, this is possible. I had seen an example here and from there I understood that such a situation can happen that people start trying to get each other to point. He said, 'Okay, so you can get the point after roaming around so much.' said, 'Okay, so you can get the point after roaming around so much.' said, 'Okay, so you can get the point after roaming around so much.' It came from zero to one, send it back to zero from one, there is only one thing, he said, okay, so if this reverse pointing comes anywhere, then what does it mean, a cycle is being created in it, so you have to see for yourself whether it is a cycle or not. It is not being made, have you understood? He said, Yes Bhaiya, I have understood. There should not be any doubt in this. The cycle should not be made. He said, okay, what is the second and important thing? The second and most important thing of yours would be this. Suppose that this is the example of our cycle. Our cycle could have been made from here as was being made in that example. He said, 'Okay, as it came to two' made in that example. He said, 'Okay, as it came to two' made in that example. He said, 'Okay, as it came to two' and pointed to it, he said, 'Okay, so and pointed to it, he said, 'Okay, so and pointed to it, he said, 'Okay, so this is also one'. It has become a cycle, said Hanj bhaya this is also one'. It has become a cycle, said Hanj bhaya this is also one'. It has become a cycle, said Hanj bhaya but, this is what happened to one to cry and from crying to one, this is what happened to parent child relationship. What is the meaning of parent child relationship? What has happened to the three, to its parents, this has also become a cycle. Kind but. This also became a parent child relation, meaning what happened that like this zero was the child of zero, one said ok and if one was the child of two, then the child of two can never be zero. Do you understand this? Said yes. Yes brother, child of two can never be zero. According to Bain Tree, this thing is clear. Said yes brother, this thing is clear, so what is the parent child relationship here, it is important to maintain yourself, that means to check yourself here. Is it that its parent or its child is not an ancestor somewhere? Its child is not an ancestor somewhere. Said it's okay, so you have to check your ancestors too. One thing, I have checked this. Said, okay, second, third and last. The thing that you will have to check is that suppose you are building a valid bi tree but here n was also given in it. What did n mean that there should be the same number of nodes? You have to check the number of nodes also. Have you understood this? I said, brother, you have understood, you have to check all three points. As soon as you check these three points, your question will be solved. Okay, look at each point once. Let's first discuss it directly with the help of code. Come here. First of all Apna Kya Hai. We will discuss the complete discussion about Apna Kya. First of all we will come after traversing the entire NEFT note. After that same formula Apna Kya. We will do it, we will put it on the right, he said, Okay, so let's go to the left first, he said, Okay, so look here we have created two vectors, one is the name of pair, meaning the name of parent, in this, we will be checking that Who all were his parents? He said, 'Okay, and he said, 'Okay, and he said, 'Okay, and he created one named Vij. In this, he will see whether he has already visited this note. It is a simple thing.' He said, 'Yes brother'. It's a is a simple thing.' He said, 'Yes brother'. It's a is a simple thing.' He said, 'Yes brother'. It's a simple thing, there is no problem, he said, OK, now you have run a loop of four. He said, OK, now what is this loop of four doing, you have already said once that your first complete is the left child. We will iterate on it, we will apply all three formulas there and then later we will apply the same formula on our right side also, he said, ok, it is very good here, as soon as you come here, see, first of all, did you check whether your left child is there? What is the value of the left child here? Is that value equal to -1? If that value equal to -1? If that value equal to -1? If -1 is its value, then what does it mean -1 is its value, then what does it mean -1 is its value, then what does it mean that there is no child present on its left? In such a situation, it is a strange thing, what to do? I have to continue, I do n't have to think about it, brother, yes, there is no child present at all, then he said leave, right after that you have to check whether you can accept this child. The child who was there said it was three. Okay, so three. Have you already reached three? What does this mean? Try to understand it carefully. What did you say here that zero is okay? From zero to one, it also went to two. He said, okay, from here there is also a three, from here, there is a four, he said, okay, so what did you do, and here, consider three, here, consider five, first okay, now did you understand this thing carefully, you said this from zero. I have come to one, from one I have come to three, so what did you do? I kept marking all of them as visitors and said, yes brother, three too, I have already visited. He said, okay, then when you come here, your three will come back here. So what does this mean, this return fall, what has become of this condition, why has it gone wrong, why has this condition gone wrong here, because if one is also pointing to three and two is also pointing to three, then what has become of this? What has happened, are you able to understand that what has become of this, has become a bicycle? Yes brother, I have understood very well that what has happened here is that this node was also pointing to this and this The note was also pointing to the same thing, there should not be any confusion anywhere in this thing is clear to everyone, he said, Yes brother, this thing is clear to everyone, there is no confusion anywhere in this, but it is very good, you have checked this. Now I have understood why I had created widget, then I have created an integer variable named temporary, now what is this integer variable doing, it is saying, now where were you in the beginning, on the row index. He said, "Okay, we have on the row index. He said, "Okay, we have on the row index. He said, "Okay, we have got the left child of the index number one. Okay, now what did he say here that who is his parent, tell me, the parent of zero, till now he did not know anything. He said, yes brother, so what is here?" The said, yes brother, so what is here?" The said, yes brother, so what is here?" The initial value that we had considered is -1. He said, it is okay, it means that till now -1. He said, it is okay, it means that till now -1. He said, it is okay, it means that till now its parent has not been decided. He said, it is okay and of course, this is its root node, it will have a parent someday. He also did not say, ok leave it, then what did he do after that, he said, he ran the while loop that until this temporary variable becomes equal to -1, temporary variable becomes equal to -1, temporary variable becomes equal to -1, then initially it is equal to -1. He then initially it is equal to -1. He then initially it is equal to -1. He said, yes. I am just equal to -1, said, yes. I am just equal to -1, said, yes. I am just equal to -1, leave it aside, I will understand its work for now, give me an example from now on, when you will treat it, there will be a value for which any trade will have to be made, then I will automatically come to know, by the way, here Please suggest what is happening here, only this much work is being done that the one who is zero is fine, Ro's and parent's stories are going on, said, Okay, so who is the parent of one, who has been marked, said, the parent of one, this is a strange thing. Row marked, he said, okay, now when you have come to 2, at that point of time, he said, okay, when you were calculating for 2, what happened at this point of time, when you were calculating for 2? So you will have to check the parent of two. Said yes brother, you will have to check the parent of two. Why did you have to do this? Suppose two is pointing to three. D said whom is two pointing to? Said to three, two is pointing to three. And what else should we know that this three is its parent. Suppose, please suggest that something happens that this two, yes, starts pointing to the one and the one is its parent. The one starts pointing to the one and the one is its parent. Balaj Bhaiya, are you able to understand this condition, he is pointing to one and one is his parent, this is not possible brother, so one can be his parent, it may not be directly, it is okay, maybe he is pointing to zero. Yes ok so if it is pointing to zero then who is its parent one and to whom is it pointing to zero? Is this possible? So, that's why I have kept one of my while loops going on here. What is that while loop doing that until it reaches the entire top row, till it reaches -1, whose parent will be -1 reaches -1, whose parent will be -1 reaches -1, whose parent will be -1 only and only of the root? Said yes brother, till we reach our route, we will keep checking all our parents to see if anyone has left child at any point, if any parent has left child at any point of time. If it is equal, then we will tell you at the same point of time, brother, get it returned, it is false, it is not worthy of becoming a valid water, it is a simple thing, I said, brother, and at every point of time, we are updating our triple whose Inside we are updating that brother, now tell his parents, then tell his parents and then you have understood the condition, Bolaji, you have understood the condition, there is no doubt anywhere, after that, what did your parents do? Which one has been stored in the left child of its parent? Meaning, whose parent is the left child which has just been created? Who is the parent of the one that has become I? What is it? Now it is running zero. Said, OK, then I marked it in my visit also. Gave that yes brother, I have already visited it, I have visited it again, it means that somewhere the condition has failed, I understood it and said, Yes, I have understood, so I have maintained the cycle and just now this Answer has also been maintained, now this number was left, what was the number? What was the number here denoting that our number of nodes should be equal? ​​So what did we do here? We created be equal? ​​So what did we do here? We created be equal? ​​So what did we do here? We created a variable named counter. Initially, counter. We created a variable named counter. Initially, above I had made an equation in which Apna had given the value n -1 which means how many total number value n -1 which means how many total number value n -1 which means how many total number of nuts will Apna get, n -1 of nuts will Apna get, n -1 of nuts will Apna get, n -1 is saying the same as if it is saying four then how many threes will Apna get because what is one? The root node is the root node, if we are not counting it, then we do n't want how many m's after that, we said three apni should be left, only three apni are left in the last, we said ok, look, you can understand it directly here, how can you understand it? Come here, look at the left child, look carefully, this is one node, said, yes brother, this node is one, said, yes brother, it has become two, said, yes brother, one more node has become three, yes, is it only three? Apni's node came out, he said, yes brother, and what did Apna also say, how many nodes should come in the counter, only three should come, 4 - 1, I had made it three, then Apna's nodes should come in the counter, only three should come, 4 - 1, I had made it three, then Apna's nodes should come in the counter, only three should come, 4 - 1, I had made it three, then Apna's counter will always run only three times, and after running last, Apna said that The left one should run and the right one should run. In the right one also, I have set the counter minus. After both of them run, if my counter is not equal to zero, then make it return false, otherwise make it return true. Rest of the conditions at every point of time were already checked above. Only one more condition had to be checked which was checked last. Well, why did this happen because what will happen here is like an off-course, which what will happen here is like an off-course, which what will happen here is like an off-course, which is zero. The root node is done, remove the root node. After that, how many nodes will you be traversing? I said on three nodes, so what is this condition that you have done? Have you checked at every point of time being there is any doubt anywhere in it. It should not happen, he said, yes brother, it is clear, you have done the whole trade for the left child, you have understood about the left child, he said, yes brother, I have understood about the left child, there is no doubt anywhere in the left child. Now look, we are using the same tactic in the right child. Exactly the same loop of four has come. He said, yes, the loop of four has come. First of all, we checked whether there is a minus and then leave it, don't even think about it. You said more, okay, then did you check whether you have already visited this node, now you have not zeroed your vegetables in it, count your other vegetables also, there should not be any doubt in this because Be it on the left or on the right, there should not be any node again, then he said, yes, it is clear, then you have not zeroed the parent anywhere because its parent will also be checking itself to see if any node comes near it. Whose parents are the same, then we will check his parents also. He said, 'Okay.' Then here, the one said, 'Okay.' Then here, the one said, 'Okay.' Then here, the one with the same parents, he ran the whole vile loop. He said, 'Yes brother, there said, 'Yes brother, there said, 'Yes brother, there is no doubt anywhere'. If all these conditions become true, then is no doubt anywhere'. If all these conditions become true, then is no doubt anywhere'. If all these conditions become true, then his Later, your parents will store it and will also give it to the visitor bank. If you have done both these things, then what will you say, simple thing, turn the counter to minus and at the end when this entire right goes to the child. After this, what should we check if our counter is anything other than zero, if there is more value in our counter, whether it is a negative value, or whatever, if our counter is anything other than zero, what does it mean? If your number of notes were not used then you had to return false and if exactly this number of notes were used then how would you make your last return true because you had already checked all the other conditions above by submitting your Let's take a look. Okay, tell me its space complexity and time. So, it has been submitted very easily. Look, okay. Yes, now see, first of all let's talk about its space complexity. I said, okay, so come here, apan ne pay off n here. Used pe and used n here so it becomes 2. He said, Yes, Bhatu has no value. Apna will say n because whenever you are taking space complex or time complex t, Apna always ignores the finite. He said Okay, so what happened off n? It's a matter of space completion. Okay, yes, even inside this fur, we are not using any more space, so let's talk about our space completion. In the time complaint complex, here we have a loop of four. Apna is going on Yes, brother, a loop of four is going on, Apna is going on n times in this loop of four, so off n is here, then this is the condition, leave it, this is the loop of the will, yes. So now how much of it can go in the loop of the weil, at max of n bat, okay yes brother, of n bat can go, leave it here too, he said, okay and here too, how much of it can go in the loop of four. Same thing happened in the loop of four, the same condition of apni vile is coming once again. He said, ok, it is a simple thing, so how much will be of Apna will be of 2n, okay because this is the loop of vile, how much will it run at max parents. In n Batu, it is at max, okay, so what can you call it? You can also call it off n * n bat what can you call it? You can also call it off n * n bat what can you call it? You can also call it off n * n bat or you can also call it simply of A. Okay, I hope you have understood A. Thank you. fur watching
Validate Binary Tree Nodes
tiling-a-rectangle-with-the-fewest-squares
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. **Example 1:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\] **Output:** true **Example 2:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\] **Output:** false **Example 3:** **Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\] **Output:** false **Constraints:** * `n == leftChild.length == rightChild.length` * `1 <= n <= 104` * `-1 <= leftChild[i], rightChild[i] <= n - 1`
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Dynamic Programming,Backtracking
Hard
null
1,015
Hello Everyone Welcome to 0.5 Inch Time Without Dress subscribe this Video like and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page if and subscribe this channel for Unlimited Red Color Module subscribe Video subscribe Liquid Not Fit Into The 10 Most Important Meeting Solutions Subscribe Number Setting On Much Time You Don't Find An Divisible By Sudhir What The Question On Play List Box As You Possible Test Cases In The Middle Or subscribe Video Free Live Web 2111 Subscribe To 20 To Three Four 750 Let's Start With Live Will Give Winners Subscribe 111 Model Subscribe To That All So Let's Talk About Click To Subscribe To Wing Ne Virvar Ko Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Channel Please subscribe and subscribe the Channel Question walon par What do you tube light weight and 128 heavenly 1115 What do you do to the number to do subscribe my channel subscribe to the Page if you liked The Video then subscribe to How to Connect with Equal to Entertain Plus One With Every Place In Next This Rebellion Just Avoid Plus Wave Please subscribe and subscirbe Before Sleeping User To Splatter Class 7 That Going Forward With Great Regret Entertain Model Existence Person's Always Listen To One Can Never Be Alone In All States In The Midst Plus One Class Model Subscribe Now to Receive New Updates Reviews and News The Here After Button Click and How to Use Tempered Glass in Terms of 2004 Mode on More Video Subscribe - The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Off Do 154 Years Mukesh Loop Dawood Not Possible Number And Subscribe To That Time Complexity Based Approach Is Border Off Around Complexity Of This Approach Her Daughter Of One Will Not Give Any Experience During Midnight At To Like Share Subscribe Button Is
Smallest Integer Divisible by K
smallest-integer-divisible-by-k
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`. Return _the **length** of_ `n`. If there is no such `n`, return -1. **Note:** `n` may not fit in a 64-bit signed integer. **Example 1:** **Input:** k = 1 **Output:** 1 **Explanation:** The smallest answer is n = 1, which has length 1. **Example 2:** **Input:** k = 2 **Output:** -1 **Explanation:** There is no such positive integer n divisible by 2. **Example 3:** **Input:** k = 3 **Output:** 3 **Explanation:** The smallest answer is n = 111, which has length 3. **Constraints:** * `1 <= k <= 105`
null
null
Medium
null
39
hey guys welcome back to another video and today we're going to be solving the leaka question combination sum alright so recently i think last month i solved the question combination sum two so do that check that out after this question all right so given an area of distinct integers called candidates and a target integer called target return a list of all unique combinations of candidates where the chosen numbers sum to target you may return the combinations in any order the same number may be chosen from candidates an unlimited number of times two combinations are unique if the frequency of at least one of the chosen numbers is different all right so now that we have this let's just go through the example real quick so we have this example uh where our candidates are the numbers two three six and seven and our target is seven so over here we have two answers so one of them is two and three and when you add them up you get four plus three giving us seven and over here we have the number seven which all of them when added up give us a value same to the target which in this case is seven and one more thing we want to notice is that the same number can be chosen how many other times as needed all right so this over here is going to be a classic uh backtracking question it's going to be pretty similar to combination sum two so what i'm gonna do is i'm to directly go into the code of this and kind of explain how each step looks like all right so over here we're going to start off by having our results list so self.results is going to equal to an so self.results is going to equal to an so self.results is going to equal to an empty list so this over here is going to be outputted and it's going to hold all of the possible combinations which sum up to the specific target so this is what we're going to end up returning so let's do that return self.results okay so now that we return self.results okay so now that we return self.results okay so now that we have this uh we want to define a few more things so we're gonna also have store our candidates value so we can refer it uh refer to it when we call our backtracking function so self.candidates so self.candidates so self.candidates and that's just gonna be equal to our candidates all right and finally that should be it so over here we're going to call our backtracking function and i'll show you how this works so we'll call backtrack and what exactly are we going to give it over here so over here we're going to have a path now this path is going to be a list of numbers which is going to add up to whatever the target value is so over here instead of writing path we're just going to start off with an empty list of numbers okay so an empty list right there and over here we're also going to be giving it our target value and this target value is going to start off being the same target value as over here and what we're going to do at each iteration when we add numbers to our path over here we're gonna decrease that same number from our target so what i mean by that is let's just go back to the first example and over here our target has a value of seven and um let's go over here so in the beginning we chose the number two so now after choosing the number two our target is going to change the number five since we have already accounted for the number two here and the rest of the numbers don't need to add up to seven instead they have to add up to the number five and once this target ends up reaching the number zero that means that we've got our answer so that is also why we're going to keep track of our target over here and i think that should be it for our backtracking function so now that we have this let's actually define what this function is going to do so we're going to have this function called backtrack it's going to take itself and we're also going to give it a path so let's just call that path and over here we're also going to have our target let's just call that target as well okay actually going back we actually give it one more thing and the other variable a parameter that we want to give it is going to be called index now this index over here is going to tell us at what index of our candidates list are we currently on all right so that index in the beginning we're going to start off with the very first value which over here has a value of 0. so we're going to start off at the zeroth index and let's also add this to our function let's call it index all right perfect okay so now let's go to our backtracking part of this and what we're going to do is we're going to iterate through all of the numbers so let's just do that so for x and range and what numbers exactly are we going to go through so we're going to start off through with the number index and we're going to go all the way up to the length of self dot candidates all right so now what exactly is happening here so in our first position let's just say we're currently in our first position we're going to try out each and every possible number inside of our candidates all right so now what's going to happen is so currently let's say we go to the zeroth index and what we're going to do is we're going to add that number to our path in the beginning so let's just add that to our path so path and what is the number that we're going to add so we're going to go to self dot candidates and over here we're going to go to the x index and this is what we're going to be adding to our path this is going to be our new path so we have an updated path and we're also going to have to update our target over here so now our target was initially let's say seven and then we came across the number two so our target decreased so our target is going to decrease by exactly this number over here so we're gonna go to the same number in self.candidates self.candidates self.candidates but what exactly are we doing over here so what we're doing over here is we're going to be calling the backtracking function on itself so self.backtrack let's call this so self.backtrack let's call this so self.backtrack let's call this function and let's give it the exact same parameters so first we want to give it the path and this is the updated path that we have so let's paste that over here and the next thing that we have is the target now this target is also updated as we consider the current number that we're on now finally the question is what index do you want to give it so basically what happened is we found the first number right now and how do we find further numbers so in this case our index is going to actually be the same x value that we're currently on and the reason that we're giving the exact same x value is because like it says over here the same number may be chosen from candidates an unlimited amount of times in other words let's say we chose whatever is at the zeroth index and in the second iteration we can choose that number again which is why our index over here is going to be the same as this x value over here so that's exactly why we're calling the self.backtrack function self.backtrack function self.backtrack function uh with that index in place since that number can be accounted for several times but now as it is it's going to go on forever and ever there's no stopping for this function so we want to define some sort of stopping point so how exactly can we do this so in order to stop it in some certain point what we're going to do is we're going to have two if conditions now when do we know that we've actually reached the ending so we know we've reached the ending when our target is equal to zero so when our target is equal to zero what that's telling us is that we've already reached an ending and we're done we don't need to do anything else so in order to stop this we're just going to return whatever we have but before that also means that we have a path which is a valid path which adds up to our target value so to our self.results we're going to so to our self.results we're going to so to our self.results we're going to append this path that we have so self.results are depend and we're so self.results are depend and we're so self.results are depend and we're going to append the path now that's one of our if conditions and the second condition we have is what if we went overboard what if the numbers that we added up is a lot higher than the target so in that case our target would actually end up becoming negative so if our target is less than zero then in that case that we know that we've gone above the limit or whatever the target is we've crossed that boundary and in that case we can just directly stop it since we're not going to end up finding any answer at that specific value all right so hopefully this did make sense so this over here is going to go through each and every single number trying out all of the possibilities and if it goes overbound we're going to end up returning it and if we do find a proper path then in that case we're just going to append that path to our results and at the ending over here we're returning that result over here so let's submit this and let's see what happens and as you can see our submission did get accepted so finally thanks a lot for watching guys do check out the other videos which are really similar to this uh question over here the permutation question and also the combinations two questions alright so hopefully this video did help and thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
1,605
all right let's talk about the fine valid metric given row and column sum so you are given two array row sum and column sum of non-negative integer column sum of non-negative integer column sum of non-negative integer right uh you can go through this and i'm gonna just quickly just talk about the question so this is actually pure math and i mean it will definitely relate to october i would say this question is not hard but due to the math problem you have to think about probably in more than 30 minutes i guess so in this example raw sound right this is for zero this is rule one and this is called zero and then column one right now then i know like you have two by two matrix right so i'm gonna just assign i'm gonna assign a b c d right then for the math problem i know a plus b equal to three and then c plus d is equal to eight right this is a uh definition for rule song right but how about the other one and the other one is four and seven right so i know a plus c is equal to four b plus d is actually equal to seven so how do we know like when do we actually need to subtract a number to find out a or b or c or d right so here's a problem uh let me change another follow this one right so if i subtract a number in the row one right in a row one i would definitely get a fit either column zero or column one right so uh at some point i need to subtract right so um when that's a proper number uh look at this uh row song index zero and ton index 0 which one's the smallest so i find the smallest one and then i can assign a number directly right so three and four so i will pick three right i'll pick three let me erase a so i will pick three now i know uh i use this number in this cells so i'm going to subtract so i subtract the row sum so it's going to be zero and for column size it's going to be a 1 7 right okay now let's move on the next column um so if i compare the next column right i'm still in row 1 and this is column one i mean uh yes well uh rule zero column one sorry about that so my current value for rows uh for row value is actually zero and seven which one is smallest it's definitely zero right so i'll assign so i assign zero to these cells right and then i subtract zero in index zero and then for the column i have seven minus seven still seven right so i move on the next following rule right it's going to be c right and let me erase this sales first okay so for set up for row one column zero eight and one right eight and one because for the maximum is actually four right so i can only assign one right here right so if i assign one i need to subtract the one right here which is zero and this one is seven right and i will move on a d is actually what this is actually seven right because originally this is four seven column one is seven right and then i know row one is eight so one plus x equal to eight zero plus y is equal to seven so what does x and y it's definitely seven right so you just sign seven right here but this is pure math i mean let's be honest so i'm going to sign on equal to raw sum and be able to call them some balance and forgot the dots right here then i would actually create a 2d arrangement for dp right where i don't care we'll divert the entire method no i uh no i need to assign right i need to assign so uh my dp at i and j will be equal to math mean so i need to find out the mean all right so it's going to be a real song in i and colon song hk so just have to make sure you know i and j should be put on right i represent the i represent a larger represent the column so if i use this number then i will say row sum and i would we'll subtract by the number that i picked right and the column sum at j will be subtract by the number all right and this is pretty much it right so i will just return it so this is about a major problem all right i made a mistake let me submit all right here we go so let's talk about time in space this is going to be what this is going to be a space out of m times n this is going to be a time of n times n so they are the same and this is a solution and this is not hard again this is a pure map if you don't know then you just do the math and then you will just code up basically you can code this in one minute be honest and i will see you next time bye
Find Valid Matrix Given Row and Column Sums
minimum-number-of-days-to-make-m-bouquets
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of **non-negative** integers of size `rowSum.length x colSum.length` that satisfies the `rowSum` and `colSum` requirements. Return _a 2D array representing **any** matrix that fulfills the requirements_. It's guaranteed that **at least one** matrix that fulfills the requirements exists. **Example 1:** **Input:** rowSum = \[3,8\], colSum = \[4,7\] **Output:** \[\[3,0\], \[1,7\]\] **Explanation:** 0th row: 3 + 0 = 3 == rowSum\[0\] 1st row: 1 + 7 = 8 == rowSum\[1\] 0th column: 3 + 1 = 4 == colSum\[0\] 1st column: 0 + 7 = 7 == colSum\[1\] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: \[\[1,2\], \[3,5\]\] **Example 2:** **Input:** rowSum = \[5,7,10\], colSum = \[8,6,8\] **Output:** \[\[0,5,0\], \[6,1,0\], \[2,0,8\]\] **Constraints:** * `1 <= rowSum.length, colSum.length <= 500` * `0 <= rowSum[i], colSum[i] <= 108` * `sum(rowSum) == sum(colSum)`
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
Array,Binary Search
Medium
2134,2257
328
hi guys welcome to the tech grant today we will solve a problem on linked list do like and share the video subscribe to the channel to get further update and the problem here is called odd even linked list and what we need to do is we need to place all the odd nodes of the linked list together and even node of the english together and even nodes should fall after the odd nodes so if this is the linked list that has been given we need to place all the odd nodes which is one three and five it will be together and the even nodes will follow the odd nodes and all the even nodes will be together when they say even and odd it does not mean the value of the node but the placement of the node means this is the first node this is the third node and so on so this example clarifies that so the odd nodes here are 2 3 6 and 7 which are all placed together and then we have the even nodes which are one five four so even nodes are placed after the odd node and we need to do it in place so we don't need to use any uh additional space for this and time complexity will of course the order of n where n is this number of nodes here so what we need to do here is pretty simple like how we traverse the linked list that is what we will do and we will create two pointers one for the even list and one for the odd list so just let me quickly go through the solution and i will explain to you here itself so if head is equal to null then we return head whatever we got which is null otherwise we will create our linked list so we'll have two pointers here one will be for odd which will point to head another will be an even pointer which will point to head dot next and we also need to ahead for the even pointer because we need to add the even point even linked list after the order linked list so when we have connected all the dots for odd and for even we need to connect or to even so we will have a pointer for that so we will say even head pointer and this pointer will be currently at the even whatever we have here so it means that it will be at the first head or the first node of first even node basically and then we need to traverse the linked list so even will we need to check on even because even will come after the odd node so let us see if this is equals to null so when till it is not equal to null and will have even dot next not equal to null it means basically the next odd node is also available for me till the even and odd notes are available i will keep on doing this so once we have this then what i need to do is we need to make odd dot next so if i have this linked list with me so quickly let me copy this here so if i have this linked list this is the odd node this is the even node so i need to connect this to this node so i will say odd dot next is equals to even dot next so that way this odd node will be connected to this node one will be connected to three and i can say odd is equals to or dot next i can move the odd pointer ahead same thing will be done for even now so even dot next will be equal to now my odd has moved here so the next of this will be the next stop my current even so or even dot next pointer it should point to this four so it will be odd dot next okay and we'll move the even pointer now to four will move it one step ahead so even equal to even dot next it will go to the next pointer so now my odd will odd pointer will be here even pointer will be here so again i can just go one step ahead here because till now even dot next is not equal to null so it works for us we can go one step ahead and odd will be equal to five and even now will be equal to null so will come out of the loop in that particular case once we are out of the loop this odd pointer or the odd yeah basically the odd pointer of the linked list will give me all the list which are basically on the odd location so this odd will contain something like this it will have all these and the even will have all the even pointers so it will be something like this now i need to connect this five to two so that is why i had this head pointer here so when i come out of this i will say that or dot next is equals to my even pointer so just point uh point to the even head here and i will return my head so that should do it for this problem let's execute and yeah it works fine i will submit it and we'll get over with this problem so yeah that's it for the even and odd of the linked list it says it's medium height is pretty medium because this is the part where you need to think a little how you will manage and uh trust me most of the problem of linked list can be solved using two pointer either say it even odd or the slow and the fast pointer that we use for race condition kind of thing so yeah think on the terms of two pointers when a problem of linked list comes to you so that's it for the video see you in the next one take care bye
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
58
hello everyone welcome back here is when I'm saying and with another exciting live coding session today we got an interesting problem on our plate finding the length of last word in a string so and we are diving deep into go language for this one so here's our challenge for today given a string consisting of words separated by spaces we need to find the length of the last word so sounds simple right but trust me there are some interesting intricates to unravel so let's begin by setting our function signature so we will name it length of the word and which take in app string and return an integer so now if we think about it we don't need to go through the entire string from the start instead starting from the end and moving backward can save us a lot of iteration so we will initialize two variable length to zero and found word to false and length will track the length of the last word while frontward will indicate if we encounter a non-space character so all right a non-space character so all right a non-space character so all right diving into the middle of the solution the loop so let's implement it so length will be zero and found word will be false and for I then minus 1 greater than zero decrement and if S Note empty found word will be true and length plus and else if found toward break and return length Okay so this is our implementation we can just run it to verify it's working so hopefully it will work yep uh all good so uh and the loop so I'm going to iterate through uh from the end of the string so that's why is minus and as we reverse the moment we find a non-space character we set we find a non-space character we set we find a non-space character we set front words to true and start counting and if we encounter a space after finding a word we just break out so let's give this a real so examples so for example if we have hello words the last word is word with length five so now let's submit it four and syntax cases as well to double check it's working so yeah all good and as you can see our implementation is quite fast runtime one millisecond beating 76 all good four those who are curious about how this can be implemented in other languages I have added Link in the description below so there you will find implementation in Python C plus rust and much more and before we'll wrap up let's uh yeah break down uh the logic so as you can see it's quite uh intuitive approach so uh that's it for today and uh if you found this video helpful don't forget to hit the like button share and subscribe for more coding adventure and remember recording is not just about getting the right answer it's all about understanding the journey to that answer and yeah keep practicing happy coding and until next time
Length of Last Word
length-of-last-word
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **Explanation:** The last word is "World " with length 5. **Example 2:** **Input:** s = " fly me to the moon " **Output:** 4 **Explanation:** The last word is "moon " with length 4. **Example 3:** **Input:** s = "luffy is still joyboy " **Output:** 6 **Explanation:** The last word is "joyboy " with length 6. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only English letters and spaces `' '`. * There will be at least one word in `s`.
null
String
Easy
null
58
in this video we'll be going over a length of last word so we're given a string s consists of some words separated by spaces return the length of the last word in the string if the last word does not exist will return zero a word is the maximum substring consisting of non-space substring consisting of non-space substring consisting of non-space characters only so in our first example we're giving hello world the last word inside the hello world is this world which consists of five characters so return five so let's first go to a thought process we'll be checking the strings checking the characters from right to left we should note that there may be trailing spaces inside the input string we will want to skip all of the trailing spaces before we start counting the characters inside the last word let's go do a pseudo code so we're going to create two variables i our current location and psi s initially as the length -1 which initially as the length -1 which initially as the length -1 which basically is the last index we'll be iterating through from right to left and length is the length of the last word now we're going to skip over the trailing spaces first so while i is greater than or equal to zero which basically means not outbound yet and the current character at i is equal to space and with decrement i will skip it now i want to count the number of characters in the last word it's greater than or equal to zero not outbound yet and the current character is not equal to space now with decrements i and the increment are aligned they will return the length of the last word let's go through the time and space complexity so our time complexities go to o of n where n is the length of the input string this is for the worst case scenario where the whole input string is only one word now our space complexity is going to be equal to of one now let's get into the code so create our current eye to keep track of our current index inside the input string initially at the last index and the length of our last word and we skip all the trailing spaces this end if it's empty space we'll skip it now i want to count the length of our last word the current character is not a space then we'll increment length and then decrement i then return the length of the last word let me know if you have any questions in the comments section below
Length of Last Word
length-of-last-word
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **Explanation:** The last word is "World " with length 5. **Example 2:** **Input:** s = " fly me to the moon " **Output:** 4 **Explanation:** The last word is "moon " with length 4. **Example 3:** **Input:** s = "luffy is still joyboy " **Output:** 6 **Explanation:** The last word is "joyboy " with length 6. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only English letters and spaces `' '`. * There will be at least one word in `s`.
null
String
Easy
null
414
given a non empty array of integers between the third maximum number this away if it does not exist we turn the maximum number the time complexity must be an O then okay huh okay I mean this seems pretty straightforward I mean it we've just if you only need to return the max number you just pretty much keep three where it was right I've been looking at a brief glance at the kind of to the examples maybe they're the reason why it's kind of a weird like there's a couple of if statements or maybe people just skip through it and then realize curse for example on example three it's actually not in the original problem statement is that you actually wanted third distinctly maximum number which maybe it's not what people intuitive or is that what people's intuition because in this case you have two three one I would have actually liked without if I haven't married I would have to be turned to as well but because we wondered maximum distinct them but you actually 101 so okay cool I mean I think this is pretty straight for him and we go given your name stuff like max second max something like that way let's just set them to some set of by you non-empty of integers hmm so I by you non-empty of integers hmm so I by you non-empty of integers hmm so I guess because the input doesn't really tell you what the bounds are it could actually be negative we're just kind of really annoying in a sense that you know in theory you I let's just say what we won is that as an education to consider so like you might trip you up of you to someone like I said max as you can 0 and that maybe someone that would have considered doing just because it's a good center while you put it in this case we actually can so and I guess the case I'll handle this here just to either have a boolean value for each one or just keep track of how many maxes are taken I guess that's just nobody easy way to do it they're just - can you zoom if we go further just - can you zoom if we go further just - can you zoom if we go further away I mean I think this is just you ready you know it's just an if-statement ready you know it's just an if-statement ready you know it's just an if-statement type thing we turn max kind of maybe not this is just my thingy but there may be we have statements here so it's just one of those things that you have to make sure you get things right because there's a lot of potential for kind of typos and educationist eggs and so forth okay so if let's do the base case is 10 we just in this case can we generalize this a little bit yeah we could probably generalize this a little bit like you have and in a way of three elements someone like that but I think yeah I mean I think you have to figure out what tolerance you want to have for like in my mind just this is gonna be any like for if statements and like ten lines of code like in that case maybe it's okay for me not to like well I'm thinking now it's not a way to like make sure I minimize the number of potential errors or not given Airways just like human errors like typos and so forth or like copy and paste hours for having three things I think like we're just separating our different cases and maybe they'll probably okay ex-cons you maybe they'll probably okay ex-cons you maybe they'll probably okay ex-cons you know the one that we but do I kind of also try doing a little queen as well but I think what I'm gonna do now is that least for now okay so then in this case we come pay max to num toy okay to be honest now that I'm typing it I don't know if I recommend this so actually okay fine let me actually it just feels a little wonky and also like now that I'm typing it out it feels like they're definitely way more potential for mistakes so let's just standardize it a little bit and maybe we could actually now we can generalize a little bit too less time and and then now you have to do kind of like um like bubble it up - lazy - so you swap that in this case and if you sends me carry backwards there so actually it should bubble things up to the fine so like yeah actually yeah okay actually we could given generalize a slightly more of a having four-way do not know how to having four-way do not know how to having four-way do not know how to intend a ssin in the code yet or Auto and ten so we that we won't do that after we and then now what happens if to you don't just had a different case okay so this would get the really simple case wide I think we could test it but I know that there's the return statement isn't quite right but it's also wrong in a couple of other places that's why I'm pausing for now so yeah so this is this would be right except for this example I mean obviously we have to also change this to Mac story and also there's just like weird thing like if max care is less tenth we I think you we turn and also I'm off by one just should be too okay babe but now I have to consider this example to worry but let's see if it compiles first well yeah the exam would react we have to keep track of distinct numbers so and it you know in this case it just might not I mean actually I know that this is not distinct as we don't do anything and away backs or make sure we get to look at some cases right so that we can you know steady on from a good base okay so that's good uh okay cool I think actually it should be that bad I think if I think we could just add in short loop such that I'm just saying this like any maximum number of elements in our way but seems like is okay ten if ten we continue Thank You next okay I guess we should kind of test this to make sure that it actually fails in the way that we expect first let's see if this gets this right okay so I guess this is actually why we see what happens after without this just to cut him I don't know sometimes you do get okay so this actually gets the wrong answer X back today okay because I would say there are definitely times in my career were like there a couple of things that you just can't confirm lucky on and that they work together to give you the right answer but not in a way that is actually correct especially with these kind of filling so okay now let's test the other let's go back and test the other one just to make sure that I'm still okay well it should be I mean okay but this is easier so this should be pretty okay cool I know now I guess I'm gonna submit oh no well give - guess I'm gonna submit oh no well give - guess I'm gonna submit oh no well give - wrong answer for this X I'll put this one when expected is - I mean they're one when expected is - I mean they're one when expected is - I mean they're not wrong but I might have I might I mean I probably I so one thing I forgot to test is like a lot longer than number of element of a way it's very probable that I have a type of submit well I got off by one somewhere to be honest good so okay and since I'm feeling a little lazy we could just print out them to max values each step of the way I know that would give me some gibberish the beginning I don't you push a zero but oh well and I'm using Coates index oh okay so today's gibberish in the beginning you gives me 1 0 to 1 which looks good so far 5 to 1 and upwards 1 but it forgets to do a weapon there do we mm let me put this here Prentiss just to him know what yeah so the other wanted scare but if the last it has to fight it and then oh because max is true so we never checked last one whoops someone like time maybe yeah whoops yeah as usual make sure you double-check them as usual make sure you double-check them as usual make sure you double-check them you're up I wasn't there was but I guess before I go into my fear I should make sure that's right for us okay so yeah definitely I got a little cocky and confident and I submitted before testing like an obvious case of having more than three numbers so to be honest like this is probably pretty bad like if you test anything it should come up but I and it turned out to be just a normal air off by one which sometimes happens when you try to code really quick but definitely make sure you test
Third Maximum Number
third-maximum-number
Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_. **Example 1:** **Input:** nums = \[3,2,1\] **Output:** 1 **Explanation:** The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. **Example 2:** **Input:** nums = \[1,2\] **Output:** 2 **Explanation:** The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. **Example 3:** **Input:** nums = \[2,2,3,1\] **Output:** 1 **Explanation:** The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Can you find an `O(n)` solution?
null
Array,Sorting
Easy
215
261
problem 261 graph validated TR so we are getting a graph structure we are going to check if this graph can become a tree but it should be validated tree let me explain this problem yeah uh we should know about what should be a graph so for example this nod connected to this nod there's another two no they are also connected this is a graph yeah and this is a validate graph but it is not a validated tree because if it is a tree all the KN should be connected like this one yeah but as you can see this areas yeah those two no connected the above two no also connected yeah but the whole part is not connected so this is some cases yeah there's also other cases for example we have three KN and they are connected with each other so is this a valid data three it is a graph yes but it is not a validated TR so this is another case yeah so if there is a structure like this so this is a validated tree yeah so according to three different cases how should we solve the problem I think we can use uni to solve it easily and we just need to cheack the connected edges for example we're going to check this two edges they are connect if they are not connected we're going to connect to them if those two edges if they are not connected we going to connect to them and then we're going to take those two ases if they are already connected so we're going to return a force yeah otherwise we're going to return true yeah so this is a uh this is for the situation if the graph is not like this we have to check this one yeah if the graph is not like this we're going to check in the second case yeah and then the third case but how can we Che the first case yeah we just need to check how many kns and how many edges so for this graph there are four knots and two edges definitely it is wrong yeah so what we need to do we need to have like four not with three edges yeah if there are four nod and three edges we're going to check the second case and the third case but if there are four no with two edges definitely we're going to return a force yeah now let's get started coding as I said I'm going to use uni so we should uh yeah try to write a basic uni file structure so the unile can be really complicated but for us I think uh in the interview we need to write at least a very basic structure of UniFi Yeah so basically we're going to write a initialization I'm going to write a pass first we're going to write some uh API like uh F and unor yeah definitely we're going to need the F and un uh I will use a pass at the moment and then I think I need a unor yeah so s do N1 and N2 unor of the two knots yeah and for me I also need uh is connected check I need to check if those two kns are connected so basically this is my API for the uh uni we need to yeah basically we need to write it for ourself we don't need to copy it every time yeah so this is the unioni yeah so if I have the unioni what I going to do as I said before I use the unit file I need a t validation T So if this are not equal to the length of and plus one yeah normally if this une equal to the N plus one I'm going to attack the second case and third case as I explained earlier but if it is not equal so I going to return a force immediately so this is just like yeah just like this case so for example those two n connected those two KN connected so the above two kns connected and Below two KN connected above two kns connected so how many n four how many add is two so if it is like this if they're not equal 2 + 1 not equal to four I can equal 2 + 1 not equal to four I can equal 2 + 1 not equal to four I can return fals immediately because definitely this is not a validated graph a validated tree I needed to check the validated Tre yeah now I will go to the Second Step the second step and third step I going to use the uni so the UF should be equal to yeah UF I will give a value n this is the number of not now I will check all the address so for u Way in address yeah so if um is connected U so if z uh connected so I can return a force immediately so this means why I'm checking those two nod u and v if they're already connected I can return Force if they not connected I will un them together I will connect them together so I can use UF do unor with u and V yeah finally if I didn't return a true and return a false I can return a true safely for the final result yeah now I just need to finish writing the uni so for this problem I just need to write a very basic unii I don't need to use a pass compression I don't need to use a reing I just need to write a very basic unii structure so I can use array as the unified because their number of the no is just 2,000 the no is just 2,000 the no is just 2,000 yeah so it going to be uh I will use a list r with for the initialization of the parent array now I can write F and is connected I think it's connected is easier to write we just need to return um self. f N1 equal to self. F and2 yeah and unor is also really easy to write let's just write the unor we going prepare P1 and P2 so be equal to s. F N1 and s. F N2 then uh we're going to put them together so I will prepare the parent of P1 should be equal to P2 yeah so the parent of P1 should equal to P2 or you can make it P2 equal to P1 it's the same for the algorithm yeah so p1's parent is P2 now we finished the unor yeah let's finish the difficult part it is a f and basically there will be more line yeah basically if this n not equal to s. parent if not equal to its parent what are we going to do yeah we're going to update the self. parent array it will be updated to and self do parent array inside it be S do parent uh with n yeah so I will not explain what is why it works for the union file you can check my other videos I have detailed explanation of why we're going to do it like this basically the union file is to connect the component in a graph if they are connected we're going to use un file to connect them together and after connecting all the connected component we can Che the easier because we can just use uh similar to o1 time for my time complex the union file is log in it is not1 because I didn't use racking and pass compress yeah but basically if we are going to use the template basically we're going to use the optimized uni fi yeah but this also works if you want to write for yourself yeah you can write it like this self dot yeah and after that n equal to uh and s. yeah after that the s. parent and yeah n should equal to this s. parent n equal to it's parent and finally we just need to return this not yeah so this is the file if we didn't yeah if its parent is not itself it means we need to steal to find its parent if it is equal to itself it means there's no connected component if it is not equal we're going to search it yeah we're going to f it parent until we f it and then we Define this n equal to yeah it's a it's parent we just needed to return this n actually this n is its parent yeah uh now let me run the code to check if it works uh it's connected not defied oh is connected here should be UF do is connected yeah now as you can see it works yeah hopefully I didn't make a mistake now let me submit it to check if it can pass all the testing cases as you can see it pass all the testing cases and the time complexity is unlock in because we used the union file I didn't optimize the UN f it is a log in so it is 2,000 time log so it is 2,000 time log so it is 2,000 time log 2000 uh yeah so for the address it is a 2,000 and for this Union fi on track it 2,000 and for this Union fi on track it 2,000 and for this Union fi on track it is a Logan so it is UN login time thank you for watching see you next time
Graph Valid Tree
graph-valid-tree
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph. Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_. **Example 1:** **Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\] **Output:** true **Example 2:** **Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\] **Output:** false **Constraints:** * `1 <= n <= 2000` * `0 <= edges.length <= 5000` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no self-loops or repeated edges.
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
207,323,871
33
Hello everyone, in today's question, what we are waiting for is date is of interest and it is always having distinct characters and if we are getting date particular target value I am going to write index of date particular value so if we can see. D code air in D code you implement you search D thing I am using D binary search operation you C are going to split this beat this index are from D middle and will check which middle has D target value and will you turn D index for Date If You Can See Are Getting D Beads Off 100% And D Run Time Getting D Beads Off 100% And D Run Time Getting D Beads Off 100% And D Run Time Of Zero MS So Do Subscribe To For Placement If You Like This Video
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array `nums` sorted in ascending order (with **distinct** values). Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 0 **Output:** 4 **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 3 **Output:** -1 **Example 3:** **Input:** nums = \[1\], target = 0 **Output:** -1 **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. * `-104 <= target <= 104`
null
Array,Binary Search
Medium
81,153,2273
35
hello and welcome to another Elite code solution video this is problem number 35 search insert position for this problem we're given a sorted array of distinct integers and a Target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with o of log of N Run time complexity for example one we're given an input array of 1 3 5 6 and a target of five our output would be two because that's the index where our Target is example two our num's array is 1356 our Target is two our output would be one and for example three our num's array is 1356 and our Target is seven so our output would be four let's go through an example for this example our nums array is 1 2 3 4 6 7 8 and our Target is six and for this problem we're going to be using binary search to search for our Target or the position where our Target would be inserted and binary search is a search algorithm that takes the array divides it in half finds the midpoint and then searches the left or right side of the array so the first thing we're going to do is find our left Point our right point and our midpoint our left point will be equal to zero our right point will be equal to the length of our numbs array minus one and our midpoint will be equal to our left point plus our right Point minus our left Point ID two so now that we have our three points we're going to see if the value at our midpoint is equal to our Target which it is not so we'll then determine if our value at our midpoint is less than our Target which it is so in that case we're going to adjust our left pointer and our left pointer will now be equal to our midpoint + one and now be equal to our midpoint + one and now be equal to our midpoint + one and now that our left Point has changed we want to update our midpoint the value at midpoint is 7 which is not equal to our Target and it is greater than our Target so we will adjust our right pointer to be equal to our mid minus one and now that our right Point has changed we'll update our mid pointer again the value at our midpoint is equal to our Target so we will return our mid which is four let's R into the code first thing we're going to do is Define our left and right points our left point will be equal to zero and our right point will be the length of our numbs array minus one now we want to Loop while our left pointer is less than or equal to our right pointer and now we will calculate our midpoint which will be equal to our left plus our right minus our left / 2 and plus our right minus our left / 2 and plus our right minus our left / 2 and the division will be rounded down now that we have our midpoint we'll check to see if it's equal to our Target less than our Target or greater than our Target if it's equal to our Target we'll return mid if it's less than our Target we'll adjust our left pointer to now be equal to our midpoint plus one and if it's greater than our Target we'll adjust our right pointer to be equal to our midpoint minus one and in the case where we Loop through our whole array and we do not find our Target value we'll just return our left pointer which will be pointing at the location in our array where the target would be inserted and that's it for the code so let's run this all test case pass so let's submit our solution was accepted so that's it for this problem if you like this video and want to see more content like it make sure to check out my channel thanks for watching
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,870
hi everyone today we are going to solve another lead code problem that is minimum speed to arrive on time and in this one we are given a distance array and the maximum hours in which we can reach to the office and we have to return the minimum positive integer speed that all the trains must travel at for you to reach to the office on time and if we cannot reach to the office within the given time we can return -1 time we can return -1 time we can return -1 so let's try to understand this with these examples so say in this first example we are given the distance as one three two and the maximum hours which we have to reach to the office is 6 right so we know the formula of speed is equals to Distance by time right now we have to find the minimum speed required to reach to the office within this given time so since we have to return the minimum speed we can start with if we move at a speed of one kilometer per hour if now we can see if we move at a speed of one kilometer per hour the first distance we can cover is equals to the first distance we can cover in how much time the first distance we can cover in the time would be Distance by speed so the time would be one distance and speed is one so which is one right then the second one we can cover in three by two three by one sorry three by one that is three similarly the last one two by one which is two so the sum comes out to be one plus three plus two that is six so that is again the maximum time we have so we if we move at a speed of one kilometer per hour we can reach to the office within the given time right so we can return one here and there is one more condition here in this example we are given if the first train takes 1.5 hours then if the first train takes 1.5 hours then if the first train takes 1.5 hours then we have to wait for an additional 2.5 we have to wait for an additional 2.5 we have to wait for an additional 2.5 hours because we can only return integer hour until it is not the last ride okay so let's take let's see this example the second one in which the distance is one three two and the maximum hours which we have is 2.7 have is 2.7 have is 2.7 now say since we have to find the minimum speed say we again start with the time would be Distance by speed again the distance we'll start with speed as 1 okay if we take if we move it one distance with one kilometer per hour of speed the time would be one hour right now the second is three kilometers per hour if we move at a distance of one kilometer per hour so the time will be three hours since we have a maximum time of 2.7 hours and we have a maximum time of 2.7 hours and we have a maximum time of 2.7 hours and we see as of now the sum is greater than 2.7 that is 1 plus 3 so it will 2.7 that is 1 plus 3 so it will 2.7 that is 1 plus 3 so it will definitely if we take a speed of one kilometer per hour it will definitely take more than 2.7 hours now if we take more than 2.7 hours now if we take more than 2.7 hours now if we decide to move at a speed of 2 kilometers per hour so now if the first distance that is one kilometer if we move at a speed of 2 kilometers per hour the time would be 0.5 hours but per hour the time would be 0.5 hours but per hour the time would be 0.5 hours but it is mentioned that we have to take an integer hour so it will be one hour right then the second distance that is three if you move at a speed of 2 it will be 1.5 but move at a speed of 2 it will be 1.5 but move at a speed of 2 it will be 1.5 but again we have to take the integer hour so it will be 2. so again we can see 1 plus 2 is already greater than 2.7 see 1 plus 2 is already greater than 2.7 see 1 plus 2 is already greater than 2.7 so we have to move at a greater speed again so now say if we move at a speed of 3 kilometers per hour 1 by 3 will again take one hour right since we have to take the integer number then and the second one would be three by three which will be 1 so as of now 1 plus 1 is 2 so we are good as of now if we move by 2 by 3 which is 0.667 right 0.667 right 0.667 right so if you take a sum of this it will be 1 plus 0.667 so that comes out to 1 plus 0.667 so that comes out to 1 plus 0.667 so that comes out to be 2.667 Which is less than 2.7 hours so we 2.667 Which is less than 2.7 hours so we 2.667 Which is less than 2.7 hours so we can move at a speed of 3 kilometers per hour so we should keep that in mind that for the last ride we can take anything we can take a double value but for all the previous slides we have to take the next integer and if we cannot make if we cannot reach to the office within a given time then we can we should return -1 okay so how would we and we return -1 okay so how would we and we return -1 okay so how would we and we won important thing which is mentioned in this description which we should notice that is the tests are generated such that the answer will not exceed 10 to the power 7 okay now say this is the approach if we take we'll start with the speed 1 and we'll keep on increasing the speed until we find the speed in which we can reach the office within that given time right but it will take one from 1 to 10 to the power 7 which is not an efficient approach but we can think of using a binary search here so say we'll start with we can instead of like taking one speed at a time what we can do we can we will start with our speed which is 1 and the maximum speed which we have is 10 to the power 7 right what we can do we will find a middle point and we will check if we will move with this middle speed if this the time we get is greater than the given time if it is greater than the given time we should move left similarly if the time we calculate with the middle speed is less than the given time then we should increase the speed so we'll move right so we will use this approach let's score this one out you will be able to understand better so like I said we'll start with one and the end point will be 10 to the power 7 1 2 3 4 5 6 7 right and the minimum speed will initialize will be -1 in case we cannot reach to will be -1 in case we cannot reach to will be -1 in case we cannot reach to the office within the given time so now we'll run a while loop basic binary search operation while start is less than equals to end and we will calculate the mid so we can name it as mid speed for better readability so start plus and minus start Pi 2 so we will we have calculated our mid now what we have we can do with this middle speed if we can calculate the time okay so we can have like enter the time taken which we can create an helper function to calculate time and in that helper function we have to find if we have to pass the mid speed the speed which we have to move and our distance away so don't worry about this calculate method as of now imagine this calculate method will return that actual time taken if we move at that certain speed what we have to do we just have to check if the time taken is less than equals to the given hour if this time is within a less than this hour then what we have to do we'll set our minimum speed at that time first minimum speed would be that mid speed and will move to the left side then which means end is equal to Min mid speed sorry minimum a it is minus speed minus 1. similarly if the middle if the time taken is greater than the given hour we'll move our start pointer to Mid speed Plus 1. right and at the end we can return our minimum speed now we'll write this helper method that is calculate time which is pretty easy so this method will return a double because our given hour is in double so public double or calculate time function calculate time with mid it will take mid speed as an integer or we can name it as speed and the distance array which we are given if you can just type that correct okay so now we have to calculate the time right so we'll initialize a time with zero or it would be 0.0 and will iterate over or it would be 0.0 and will iterate over or it would be 0.0 and will iterate over this distance array entire is equal to zero I is less than distance dot length I plus we'll calculate the time so say for the first distance it is 1 and we will move with any of the speed say 2 so it will be will double the distance of I by we'll change it to double by speed right and like I mentioned before if it is not the last hour in that if it is not the last hour we have to take the next integer otherwise we can take the value so that we can simply Handle by taking if we will add everything to this time so that we can easily handle if I is equals to last element that is the distance dot length minus 1 if this is the case then it will be whatever time we have it in double sorry it doesn't double a otherwise we have to take the Seal of whatever we get in t that is so if we get 1.5 it will convert it into two but get 1.5 it will convert it into two but get 1.5 it will convert it into two but if it is the last limit then whatever we have like zero point say here 0.667 it have like zero point say here 0.667 it have like zero point say here 0.667 it will take just 0.667 after it will take just 0.667 after it will take just 0.667 after it writing over this is this for Loop we will have our sum of like say 1 plus 0.667 which will be at time so we plus 0.667 which will be at time so we plus 0.667 which will be at time so we will return our time from here so once we are done with this we will have our time taken and then we will simply check if our time taken is less than hour then we'll move left otherwise we'll move right let's try to give it a run okay so I think I missed one and taken mid speed possibly lose conversion so mid speed we have as minus one okay and that is mid speed is our integer value and we are passing in speed that is calculate time because we'll use conversion from P0 in time calculate what is the problem hint distance that's fine mid speed is fine I don't see any issue here so let's try to check that if mid speed is equals to this that's fine but speed is an integer value and the time taken we will calculate oh sorry the time taken should be in double right why is that let's try to give it a run it's working fine let's try to submit and it is working as except expected thank you
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
116
all right let's talk about populating next right pointers in each node so you're given a perfect binary tree so uh you have a struct node so you have valve left right and an x and then base basically you just have to point your current null uh to the next one in the current level and if you're on the last note right just point it a no so using this idea and then using the preferences method you will probably solve this question pretty simple so i'm going to check if the rule is actually able to know if that is true then you just return now it doesn't matter right and for i mean for example two i have to return all right and then uh i would have to create a queue to store every single node in this current level so q no q equal to newton's english and i also need a dominoes so i can when i return i can actually return the route right away so i'm using the domini to traverse so two dollars so while q is not empty and also um i need to know my current size the third size is actually the current level the number of nodes in the current level secure the size and uh at the end i also need the three so uh i would say good to know first and then pre is actually keep remember the first i mean the previous one and then you will just point at the kernel right so i will traverse the size of the uh i mean current level of the tree so less than size and then i plus so i would say no and then this would be no equal to q so the current poll tri note i mean the note will be the one you have to check if this is equal to zero then there's no there's nothing to point to the next one right so i would just assign pre equal to no and then if that is not if that's not it's not the first one i would say three dot next is equal to the current net or current node and then pre will have to reassign to the node so every single time you just switch your free to your current or current note when you assign the next right and at the end uh i will have to assign print on next equal to no so i will actually set the current uh current next to the node but i also need to check for the children so if you know the left is not known and i would just say cue that over no doubt and also if you know that right now no i would just assign to the offer no doubt right and this would be the solution so let me just run it and see if i have any missing or not all right i didn't miss anything so here we go so let's talk about the timing space complexity for the time you traverse every single one of it right this will cost you all the fun and in space i would say it's all the fun because you have to put into your queue and then pop and then push i mean officer and then that will cost all the fun for sure for every single level you have to push i mean offering to your queue for sure so time and space are all open and then i'll see you next time bye
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[1,#,2,3,#,4,5,6,7,#\] **Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 212 - 1]`. * `-1000 <= Node.val <= 1000` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
117,199
94
hey everybody in this video we are going to be solving a problem on lead code which is binary tree in order traversal so it's a really simple problem tagged as easy and it has a very straightforward solution now other than this problem if you all want to check out some solutions to other problems on lead code based on binary trees or linked lists you can check out my playlist on the channel lead code solutions over there you'll be finding many problems based on these topics so without wasting any more time let's begin with binary tree in order traversal so let's go through the description and then we'll see how we'll be solving it so over here we've been given the root of a binary tree and we need to return the inner traversal of its nodes values so there's not much to explain over here other than the in order traversal for those of you who are not aware of it so let me just create a nice big tree and that should work so if you look at this tree and we want to do the inorder traversal so in order traversals basically work like first preference is for the left child then comes the root and then comes the right child so if you look at this tree we first go left now we've reached 2 so because 2 has a left child we go left now 4 doesn't have a right child so we store 4 or we print 4 if you want to look at it that way we print 4 and then because 4 doesn't have a right child we don't have anywhere else to go we go back to 2 then we print it so left child done current done now we go towards the right child 5 now five doesn't have a left child or a right child so we go back to two we have already printed two so we go back to one now the left subtree of one has been printed then next we need to print one we print it out then we go right now three reach three and three we see has a left child so we go ahead to six now because six doesn't have a left or right child it's a leaf node so we print it we go back to 3 we print 3 we go to 7 and we print 7 so this is the in order traversal left root right and we need to return this in order traversal in an array so this is the function that we've been given but i'll be creating another function to traverse the tree recursively and it will give us the output in a global variable which i am declaring let's just call it in star arr so we'll be re-allocating this array as so we'll be re-allocating this array as so we'll be re-allocating this array as we traverse the tree further so we reallocate means if arr has currently it has the memory of four integers if we find another node in the tree then we reallocate it to hold five integers instead of four so at every node we reallocate arr because we are unaware about how many nodes there are in the tree so that's why we need to reallocate it again and again so now i'll be declaring defining the function which we're using which will be traversing the tree let's call it in order and the parameters it'll take let's call it struct tree node star node and now we just put the base case if not root return and one more thing which we need to do is a global variable size which indicates the size of this array now what we do as i said left root right so first we need to go left so what i do over here i say in order root of left now we after going left what we need to do we will write that now one important thing that you need to do because now when we have called this the next thing we need to do is we need to store our current node now before storing it we need to reallocate this array so what i'm going to do is arr is equal to in star this is just a typecast re alloc arr size of int into plus size now i'll just explain what this is going to do so over here our current size of arr is size this variable now what we do is we say arr it is a pointer so we take this pointer make it point to a chunk of memory which is more than what it was pointing to before so let's say err was holding four integers before so now what i did i reallocated it and i said set plus size which makes size five instead of four so it the memory got reallocated to five and all the values which were currently pressed which were previously present in arr got copied back into the new space so those four integers still remain intact and we just got the new uh an extended space of the fifth integer so now because our size is equal to the size of the array so we do a arr size minus one is equal to root of well and all we need to do after that is call the right child so node of right and similarly i wrote it wrong over here it should be node and over here two it should be node so node of we called node of left we called node of right and in between we put the inserted the value of our current node in the array so this little piece of code should fill up this array with all the values all the nodes present in the tree so all we need to do now is just do some initializations because we'll be getting multiple test cases so the code would run only once but we'll get multiple test cases in that same run so every time we get a new test case we need to re-initialize our test case we need to re-initialize our test case we need to re-initialize our global variables so size is equal to zero arr is equal to null so you can note that i am not freeing the array as i mallocked it i don't need to free because it's written over here that the caller will be calling it so we set size equal to 0 are equal to null and now i can just call my traversal function in order and then return arr so this should work about right let's check it by running the example test cases it gave me a runtime error it says oh my god i again missed i wrote note instead of root i wrote root instead of node so i'll just run it again and it gave us the wrong answer and i'll just see why is it so all our outputs returned null so we said arr is equal to null in star re analog size of int plus size um so just give me a minute i'll debug that and get back all right there wasn't any problem in this code but all we needed to do more was we need to give the return size to the caller because the caller doesn't know the size of the array so that's why it was giving us null so we say star return size is equal to the size of the array and now it should work about right all right it runs fine for the sample test cases let's go ahead and submit it and it works fine for all test cases so there you have it guys that's the solution for binary tree in order traversal and as i said it was a quite a simple problem just we missed our giving back the return size to the caller that's why we were getting the error initially but all in all it was not that difficult so i hope you liked the video and if you found it helpful do make sure to like and subscribe
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
338
hey guys it's all five one here and today we're going to be solving counting bits in this problem we're given an integer n and they want us to return an array answers of length n plus one such that for each element the number of ones in the binary representation should be stored in that index so what does that mean exactly well let's take the number three in binary this would be 1. so for answers at 3 we would have to store a value of 2 because there's two ones there so the full answers array would look something like this where if we take this array for example because it's not going to change these all will have the same amount of ones no matter what the N is so our array for this example would be 0 1 and 2 and we will return this whole array here at the end okay so let's start by going over the Brute Force solution so here I've initialized the example for n equals three and here I have the array going from 0 all the way to three and in each one of these indexes we're going to put how many one bits there are for that number so for example for zero we know there are zero bits so I'm just going to initialize it to that for now and let's say we're at one now well if we're at one we have to count how many one bits there are and one in binary is still just one but we would have to have a nested for Loop to be able to count how many ones there are here and that would take end time so let's just do that we have one bit for one what about for two well two now has two bits one and zero and we have to run a for Loop through the all of the bits to find out there's only one there so we're going to store that and then for three same thing we're gonna have two bits but we will need a for Loop to iterate through all the bits and then we would be able to store two because we would find that there's two one bits there but the problem is that the time to run his algorithm would be o of n log n the reason it's n log n is the n comes from iterating through this whole array which is of size n and the log n comes from iterating through the binary bits and as you can see we don't actually have as many bits as there are let's say three for example we don't have three bits here we only have log n plus one so if you had 16 let's say 16 in binary would be one zero and log base 2 of 16 is equal to four but you can see we have five bits here so that's why it's plus one but all of this simplifies to just log in anyways so that's why this is our runtime and there's actually a more efficient solution that runs in just o of n time so the only way to actually get an O of n time is by using dynamic programming and what does that mean well let's say we have this zero here and we have a 1 here well to calculate two we should use one of these two indexes to calculate two instead of going through two as a binary bit and Counting the ones individually so I'm just going to fill these out and then once I'm done with that we can go over it and see if we notice some kind of relationship between the numbers so the first thing I notice when solving this problem is the placement of these ones are all going to be in powers of two so for example this one is in 2 to the power of zero this one is in 2 to the power of one two to the power of two and two to the power of three so basically if we have a power of two then that means we're only going to have one bit and if you think about it let's say we have the number 32 well that would still only have one bit as you can see here so we have there's one at the end and then zero and zero I believe and no matter how big the number gets there's still always going to be a one bit if it's a power of two okay well that's useful I guess but how can we use this to find the numbers that are not powers of two like these for example well let's take three we know that three is made up of the two bit and the one bit in binary so this would represent the two and represent the one and this makes up three okay so maybe we can say that let's say this array is called DP of three could be equal to DP of two plus DP of one but what does this really tell us about the rest of the numbers well let's see if it holds for five so DP of five what would that be well we know that 5 in binary is going to be equal to one zero and one this is the four bit two bit and one bit so we can say that DP of 4 plus DP of one makes up five so what we're noticing here is that we're using the most significant bit and then just adding one to it okay but we can also see that it doesn't hold true for seven so for example let's say DP of seven we will make that equal to the most significant bit which is currently four plus DP of one and as you can see that does not equal 3 because DP of 4 is 1 and DP of one is one and that would give us two so what's the actual relationship here well instead of DP of one we can say that this is instead DP of 7 which is our current iteration minus the most significant bit which is four and that will give us a DP of three and then this would equal 3 because DP of 4 is 1 and DP of three is two so one plus two would give us the three here at seven and this also holds true for the previous examples so for five we have DP of four plus DP of five minus four which would be DP of one and same thing for three so our pseudocode is going to be something like iterate through all of the array and for each number in the array we want to find the biggest power of two so we can just say find most significant bit and I'll show you how to do that in the code and then after that you just want to do DP of I is equal to one because we know this is just going to be one at all times since it's the most significant bit so we don't have to worry if it's 2 4 8 16 or anything else because they're always going to be one so that's why it's one here and then we can do plus DP of I minus the most significant bit and then at the end we can just return our DP array since that's what it wants it doesn't want it at a particular index and that's our whole algorithm our time for this is going to be olvin since we're only iterating through the array ones and the space is going to be o of n as well because we have to store this array here so now let's get into the code so to start I'm going to initialize the answers array and it's going to be all zeros for a length of n plus one the reason is n plus 1 is because we want to have room for our base case at zero and then from here I'm going to initialize a variable and I'm going to call it largest bit and we're going to use this to keep track of our most significant bit like we said in the code and I'm going to set that equal to 1 to start and now we go through every single end so for I in range of 1 to n Plus 1. the reason we start at 1 is because we already know that at 0 is going to be zero so we don't need to calculate that and then from here we want to calculate our more significant bit so how do we do that let's say our largest bit is one right now so I'm going to write that down here largest bit is equal to one but let's say our I is equal to two so that means we're at the second iteration and our most significant bit should be the twos place so what we want to do is check if largest bit times 2 is equal to the I so the current iteration then we want to update our largest bit to be equal to I and the reason we do this is because our I at this point let's say at I equals 2 that would be our new most significant bit and that's why we updated like this from here we just want to do what we did in the pseudocode again so answers at I is equal to 1 Plus answers at I minus largest bit and then that should fill in an array and at the end we just return our answers array and that should work so as you can see this code is pretty efficient and now I'll go through the code manually so to start the example we're going to be doing is n equals 5 and in our code we initialize our answers array to be all zeros for a size of n plus one so as you can see our answers array is a size n plus one and I only put this is a zero for now because we're going to update the rest so I don't want to make it too messy and then our largest bit is going to be initialized to one which I've already done here so these are checked off and now we can go into our for Loop so for I in range of 1 all the way to n plus 1 then we want to check if our largest bit times two is equal to I and like I said before the reason we want to do that is because this is how we find our most significant bit so let's see largest bit is currently one times two well that equals two and I is 1 currently so this is false so all we want to do is update our answers array at I which is one two one plus I minus largest bit and this would be zero so our answer is I would be equal to one and now we go to the next iteration so now we're at I equals two and let's see largest bit is still one but our I is now two so we want to update our largest bit to be equal to I which is two okay so now we do answers at I equal 1 Plus answers at I minus largest bit and I equals two and our largest bit is also two so this would be answer to zero which is zero plus one so at our two spot here we want to have a one and now we're at I equals three so largest bit is still going to be two times two that is equal to four so this condition is false and then answers at three is equal to one Plus answers at three minus two which is one so we would have one plus whatever is in the one index so one and that would be two and now we're at I equals four so let's see largest bit is two so two times two is equal to four so now we're going to update our largest bit to be four and then we update our answers at I which is 4 to be equal to 1 Plus answers that four minus four so this would be zero which is also a zero value so we would just store A1 at index four so now for our last iteration we're at I equals five so we're going to have largest bit times two so four times two that's eight so that's not equal to five so we can just ignore that now we update answers at five to be equal to one Plus answers at I minus largest bit I is 5 our largest bit is four and this would be equal to one and answers that one is one so we would update five to be equal to two and that's correct this video helped me anyway please leave a like And subscribe thanks for watching and I'll see you in the next video
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
796
oh cool we're given two strings a and B a chiffon string a consists on ticking string a moving the leftmost character the rightmost character okay that seems okay man this is so basically okay so basically just return whether it can be a ship of P or B can be a ship a can be a ship of P or B can be a ship of a which I think if you said it's still the same either way did a couple ways you can do this like by I mean I think there's a straightforward way for especially for yeezy so I don't really expect anything like god sure about it I would just I would disseminate it right I think if so if this is a more complicated problem maybe if this was a medium or hard and there's a frame we're like hey given in a way given a string a and like given in a way of these things but would you do then maybe you into some pre calculation put in a hash table or something like that so that you could get like a no constant time lookup but it seems like this is one off and there's finished wait for it this shift account is and C you know they're the same and since both a and B it has most the length at most 100 I'm just gonna do the really lazy string concatenation thing there's some like if we were playing over performance or worried about performance and stuff like that we may do something like you know using a string buffer or having character ways and kind of do comparison that way a little bit but that's all the fancy stuff that I've thing for this problem we don't really need cuz I mean it is easy and I guess that said half the submissions fail so maybe I should be careful just in case cool okay I don't know we should assume that they have the same length but I'm just gonna check that oh god I'm in Python so something so you've noticed I sometimes I jump from C and Python I actually blend them generally prefer C to be honest but Python special materials of strings and memory allocations for the purpose of just getting a poem done as quickly as possible relatively I just do whenever in Python sometimes and string manipulation it's just way easier in Python okay cool okay so update Samed and so mmm how do I want to do this I guess we'll just do an off start oh I guess there's no expansion 5 hunting I'll just write a helper function no oh yeah okay fine yeah I'll take some time to name it's slightly better it's not even that good by how I went for us I mean don't know how much I need to get into this since I feel like this is pretty standard I mean you just always not used to the Python 3 syntax bit and I'll get better at it that's the point of practicing quo I think there's some stuff like and again with evading taxes I'm always curious if I'm off by one so I'm just really sometimes bad at it so I just realize I'm using the keyword let us wonder comb into this roughly way except for me being off by one here just course no real quick oh okay I mean and the point of having this print here is so dad like even if it's wide a lot of times when I look at code like I want to make sure that it's not right for them you know sometimes you just get lucky and things that correct especially when it when your palm has like only to enforce like half the title and not half the time but like if everything is random and flip the coin half the time you get it right and you get endorsed off like fake confidence about it but now you can see that like cddb a and then one you know and then just all four I think actually but and what I point out is true is that like with this there is not by one way I need to actually add is two plus one because this standard out should have five strings four five offsets including zero so yeah so let's run this code again hmm Oh actually it's actua so I was actually may be wrong and dad like justice early terminates so maybe just gets the last one right well I guess the way we could test this is having one that's for us so let's double check that as well just to be a little bit careful okay so I don't need the first point always just off by one who eat me last time and then we so he's chucked at a rock god shifted five times and then we could ship it hopefully Oh No well Oh four empty string huh okay so I guess that is the case I didn't check I it's one of those things okay fine yeah sad face Larry this is what happens I think it's Oh in genuine program contests and stuff like that they actually don't tell you the thing you got wrong in which is kind of and you have to figure out you have to look at the code I actually prefer it that way because it makes you really like touchy assumptions and just think about what you did whoa and also next time you're yeah next time hopefully you know you learn from your mistakes like this one I really should have caught this one but uh oh today oh sorry maybe yeah so I'm reading the comments now yeah maybe in the code contest they tell you but I think in I mean they tell you that it's warm but they don't tell you the - they warm but they don't tell you the - they warm but they don't tell you the - they tell you that the problem or the solution is wrong but they don't necessarily tell you like their input that is wrong but yeah I mean I think the different format so I don't know what I prefer but I think for me the reason why I do these problems is to you know practice you know game things right and first time so I've just preferred to you know like really figure out like what is it that make me wrong the first time and for this case I forgot about this length is equal to zero case and I just didn't make that assumption and you know
Rotate String
reaching-points
Given two strings `s` and `goal`, return `true` _if and only if_ `s` _can become_ `goal` _after some number of **shifts** on_ `s`. A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. * For example, if `s = "abcde "`, then it will be `"bcdea "` after one shift. **Example 1:** **Input:** s = "abcde", goal = "cdeab" **Output:** true **Example 2:** **Input:** s = "abcde", goal = "abced" **Output:** false **Constraints:** * `1 <= s.length, goal.length <= 100` * `s` and `goal` consist of lowercase English letters.
null
Math
Hard
null
1,688
hello everyone so in this video we'll solve liquid problem number 1688 that is count of matches in tournament so in the problem statement we are given an integer and that is the number of teams in the tournament and we have to find the total matches that will be played in the tournament So based upon the number of teams we are given two condition uh to decide number of matches that will uh that will get placed in that round also number of teams which are moving forward in the next round so if the number of teams are even the number of matches played will be n by 2 and also the number of teams moving forward will be and by two for the odd number of teams cases a total number of mass is played will be n minus 1 by 2 and the number of teams moving ahead for the next round will be n minus one by two plus one so let's check example one in example one number of teams is equal to 7 and uh number of matches played in the first round will be as the number of teams are odd then the massive played will be based upon the second condition so number of masses will be 7 minus 1 by 2. that is three a number of teens moving forward teams forward is equal to 7 minus 1 by 2 Plus 1. so this will be 4. so uh this is for the first round for the second round we'll have matches is equal to as number of teams are even now so the first condition will apply so number of masses will be n by 2 is equal to 2 and number of teens moving forward will be n by 2 based upon the first condition so this will be four by two so number of teeth moving forward will be two again the number of teams are even so first condition will apply so message straight will be 2 by 2 is equal to 1 and number of teens moving forward will be one only and that will be declared as the winner so total mass split is 3 plus 2 plus 1. so it is equal to 6. so let's code this in C plus so quickly I will explain what I did in the code so first I declared the message is equal to zero and number of teams is equal to n i declared it because I don't want to change the value of input variable M then I am checking uh while the team's not equal to 1 that till the time if there is no winner we will check if number of teams are even or odd and if the number of teams are even then uh number of masses played will be teams by 2 based upon the first condition and a number of teams moving forward will be teams by two and if the number of teams are odd then a message played will be teams minus one by two it comes from the second condition and number of teams moving forward will be teams minus one by two so uh let's run this code yes so this is accepted also one thing I would like to highlight over here is if the number of teams are odd say n is equal to 7 so in case n is equal to 7 the number of matches played will be teams minus 1 that is 7 minus 1 5 2 so it will come to three so if we divide any odd number by 2 then we get a question and remainder as one so uh what we can do is we can directly do it as n by 2 this will also give us 3 because we are only concerned about the portion part we the remainder will come one always if we divide any odd number by 2. so we can write teams minus 1 by 2 as teams by 2. so let's do this also we can remove this teens minus 1 by 2 States by 2 because we are only concerned with the quotient part so now we can see that matches this line of code is redundant for if as well as else condition so we will remove it from here and we will bring it out of the condition now let's run this code again yeah so this is accepted now let's run for all the test cases yes so this is acceptable for all the test cases thank you for watching the video and if you find this video helpful please like share and subscribe
Count of Matches in Tournament
the-most-recent-orders-for-each-product
You are given an integer `n`, the number of teams in a tournament that has strange rules: * If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round. * If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round. Return _the number of matches played in the tournament until a winner is decided._ **Example 1:** **Input:** n = 7 **Output:** 6 **Explanation:** Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6. **Example 2:** **Input:** n = 14 **Output:** 13 **Explanation:** Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13. **Constraints:** * `1 <= n <= 200`
null
Database
Medium
1671,1735
35
hey guys persistent programmer here and today we're gonna do another Lika question search insert position so for this problem we're given a sorted array and the target value and we need to return the index of the target if the target is fog and if not we need to return the index of where that target would be so this is a really interesting question because when you first see ok we're given a sorted array and the target value the first thing you need to think about when you're searching for something in a sorted array and you're given a target value is binary search right so that's the first thought that should come to your mind when you're reading this question but the problem here is that not all of the values like not all of the targets exist in the input so for example over here this is a case where the target does exist so we can see that 5 is here and 5 is at position 2 so you would normally do a binary search and be able to find this but if we look here we're given a target of 2 and then 2 should exist in position 1 over here and we need to return that position right so now how do we do this using binary search but not having the target in the list all the time right so that's the main question here ok so let's think about this and I was definitely kind of struggling to get here but what we need to think about is ok how are my left and right values of the array going to help me return this index right let's do a deep dive of this list here and if you haven't done a binary search before let me know in the comments down below I can do a video just on binary search but for this video I'm expecting that you already know how binary search works so we'll just do a normal binary search so we will have our left pointer here and our right pointer here and we'll find the mid so the mid will come out to be 3 because we're taking the floor function so that will take the lower value and when it's at three we'll compare three to two and two is less than three right so we can say we can move our right index to mid minus one right so our index is going to be over here now and when we compare now this one to two is greater than one so what will happen is the left index is going to move one forward right so if we return that left index we will get our answer so our left index is going to go from zero to one when it compares this one to the two and sees that the two is greater right so that's the idea between returning the left index because it will give us the value that we're looking for and where the insertion needs to happen and here we are given an element seven which is greater than the last element in the list so what's gonna happen in this case is the left index will start off at zero where it always does and it's gonna compare with the mid and keep checking with the target which is seven and the left index is going to keep adjusting towards this six right because every number here is going to be less than seven so when it is at this position it will check ok well 6 is less than 7 so it's going to move the left index over one more right and that's how that's why when we return the left index it's still gonna give us the right answer which is four here so 0 1 2 3 4 so it should be after the 6 and then let's look at this other example 4 where we have a case where the index needs that needs to be returned as actually before the first element so in this case the left index is going to remain at the zero right because we will keep adjusting the right index over and then keep checking with our target here which is zero so it's gonna be caused less than our mid comparisons and the right index will keep moving over and our left index will just remain at zero which will be our output so I hope you understood these four cases and why we need to return the left index after the binary search okay awesome so if this is all good let's go ahead and write the code okay so the first thing I'm going to do is define my left index which is going to be 0 and then my right index is going to be the length of the list minus 1 and the reason we're doing minus 1 is because we're starting at 0 so after that what we're gonna do is write our while loop so we'll say while left is less than equal to right and now we're in this loop and now what we need to do is find our midpoint so the mid index is going to be equal to the floor of the Left plus right and we will do over 2 so 4 left plus left right over 2 and after we have our mid we're going to check if the number is equal to the mid right so if the number exists in the list we'll just go ahead and return that index so we can say that if Nam's mid equals the target then we can go ahead and return that mid index okay and then if we need to check the other cases so we'll say also if target is less than Nam's made so if the target is less than our mid then what we need to do is move our right side so if the target let's say let's take the 0 right so if this is less than that three then we need we know that it's not going to be in this part of the list so we're going to move our right pointer which was initially sitting here over so we'll move it to so we'll say write equals mid minus one right and the reason we're not just setting it to mid is because we already checked that it's the target is less than this value right so that's why we're doing the minus 1 here and else that means the target is greater than the mid so we'll move our left index over so we'll say left equals made plus 1 and the reason we're doing plus 1 is because again we check them in and we need we know now that it's going to be over in this part of the list if this number was like 7 right if the target was 7 in this case okay so after this what we're gonna do is go ahead and return the left okay so the time complexity for this will be log n because at each point we're cutting the list in half and only checking in that half so that's the time complexity and we have not used any additional space to solve this problem so the space complexity is just gonna be off 1 all right so this looks good let's go ahead and make sure there's no typos or errors so wrong code submit okay awesome accepted thanks guys if you liked this video please go ahead and subscribe to the channel give this video a like and if you have a different solution please post it in the comments below it could be in any other language it's just gonna help other people look at the solutions and understand and solve this problem themselves thanks guys happy coding
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
816
hey my name is khushbu and welcome to algorithms made easy in this video we are going to see the question ambiguous coordinates we had some two dimensional coordinates like 1 comma 3 or 2 comma 0.5 like 1 comma 3 or 2 comma 0.5 like 1 comma 3 or 2 comma 0.5 and then we removed all the commas and decimal points and spaces and end up with a string s return a list of strings representing all possibilities for what our original coordinates could have been our original representation never had extraneous zeros or extra zeros so we never started with numbers like 0 or 0.0 or 0.0 or 0.0 or 0.00 1.0 or 0.00 1.0 or 0.00 1.0 or these numbers or any other number that can be represented with less digits also a decimal point within a number never occurs without at least one digit occurring before it so we never started with numbers like point one the final answer list can be returned in any order and also note that all the coordinates in the final answer have exactly one space between them occurring after the comma so this is how we need to give the output these are the cases which are not going to happen so these are the exit conditions in the second paragraph and so here's the question in the example one we are given a string with 123 in the bracket and so if you see we can have the number as 1 comma 23 or we can have 12 comma 3 or we can have a number with a dot which is 1.2 comma 3 a number with a dot which is 1.2 comma 3 a number with a dot which is 1.2 comma 3 or 1 comma 2.3 in this so these are the possible 2.3 in this so these are the possible 2.3 in this so these are the possible coordinates that we could get from the number 123 and here's the second example and similarly we are given some more examples in the constraint we are given the length which would be between 4 and 12 and the string is going to be enclosed within the brackets like this so that's the note that is attached with this question now let's see what are the steps that we need to perform and how we can get the solution for this question so we'll be going through a modular approach for this particular problem rather than writing a shorter code we will write a modular code for this so let's take this example over here which is 0 1 2 3 which is initially given to us as enclosed in the bracket and so the number that we have is 0 1 2 3 when we remove the brackets now this number is a coordinate so need to be a two part thing that is x and y so it can be broken down into three states that is you can have a comma after zero or after one or after two so these would be the broken down coordinates and now as said in the question we can also have a dot so for all these coordinates that we could have got from here we need to also c for the dot so let's take these coordinates and now we'll try to bifurcate it further so over here in the first one we have two numbers 0 and 123 and we need to apply the dot as we had done with the comma so 0 remains 0 because we don't have more numbers that can accommodate the dot but for 123 we can break it down so it becomes either 1.23 that is a dot so it becomes either 1.23 that is a dot so it becomes either 1.23 that is a dot after 1 or a dot after 2 that is 12.3 or a dot after 2 that is 12.3 or a dot after 2 that is 12.3 similarly we can do it with the second example wherein we have two numbers 0 1 and 23 and we can have a dot in between these numbers like this as we have mentioned that we cannot have a dot in the front or at the end because there should always be a number on both sides of the dot doing the same with the third one which is 0 1 2 and 3 and breaking it down so we get these numbers out of the example that is given to us now over here we have everything that we need the next step that we need to do is eliminate the numbers which are not going to be valid for example the number like 0 1 so in the question it was mentioned that there won't be extraneous 0 that is extra zeros over here we can see we have an extra 0 with this 1 so this won't be possible and similarly 0 1 2 and 0 1.2 is also not similarly 0 1 2 and 0 1.2 is also not similarly 0 1 2 and 0 1.2 is also not going to be possible so let's remove these numbers and now we are remaining with x and y coordinates that could be there is our task done no now we need to find all the combinations that is a combination of this x with all the y's and if we would have had another x then we would have also had the combination of that one with all the y's so it is going to be like this that is we would be combining 0 with all the combinations of y or the number similarly for the second and third coordinate system and so this is going to be our final answer that is we now have all the possible coordinates that could have been there in the original coordinates so over here we saw three things that is first is breaking down as per the comma then breaking down as per the dot and then eliminating the invalid choices after that is done we are going to form all the coordinates combinations with the ones we have got the rest is simple now how do you validate your numbers for validations we can say that we have three basic rules if the number does not have a dot the number should either be a zero itself or else should not contain any leading zero that is it should not start with zero if it isn't a zero secondly if you have dot then you have a two part thing that is for the number before the dot that is for the first half the number should either be zero or should not have any leading zeros that is same as the case wherein we were not having any dots for the number that occurs after the dot that is the second half should not have any trailing zeros that is 1.20 is not is 1.20 is not is 1.20 is not valid it should just have been 1.2 so valid it should just have been 1.2 so valid it should just have been 1.2 so these are the conditions for checking the validity for the numbers now that we know everything that we need for this question let's go ahead and code it out the first and the foremost thing that we need is a list of results and secondly what we need is to reduce our string by removing the brackets that we have so i need to take the substring of the original string that is given for performing the operations on it and that would be starting from the first index till the second last index after this we will take a for loop and we are going to break the string into a coordinate system so we are breaking the string in x comma y form and so our first comma is going to be in the place that is first index so it goes over here and so we'll start from index equal to 1 and now we'll call our helper method variant will pass both the coordinates or both the strings so that would be substring of 0 to i and the substring that is starting from i till the end so this helper function would internally call all the methods that would be needed to produce the result and that result is going to be stored in the list so finally we can just return the result so that's all about the main function now let's write the helper function so in here we need a list of all the numbers with a dot representation for x and 4y so that would be a list of string and i'm going to take a function that would add the dots in the string x and in the string y after i have got everything that i need to iterate and generate the combinations that could be formed by using these both lists so i'll take a for loop and i'll check if that particular string is valid then i need to form its combinations with the y string and that too if the y string is valid so if the combination could be formed i'll just add it in my result and in the result we need to add the string with a bracket and a comma so let's take a bracket plus my string plus a comma after which there needs to be a space plus the y coordinate and finally terminated by a bracket so we need the string in the form of this that is 1 comma space 2 3 so that's the format that we are going to follow now we have our helper method now we need to write the method for appending the dot and to check whether our number is valid or not so let's write those methods let's first write the put dot method so this is going to be similar to breaking the strings but only here we need to append those strings with a dot so let's take a for loop and we'll be adding it in the results so let's take a result variable over here and over here we are going to add the two substrings appended with a dot in between and those substrings would be the substrings from 0 to 1 and 1 to length or that is 0 to i and i till length so let's write and that's all for this finally just return the list and one thing that we missed over here is adding the whole string as it is that is if we are having a string 123 we'll be adding that string to in our result so we'll do result.add the string so we'll do result.add the string so we'll do result.add the string s and then we'll be breaking that string by adding dots now comes the final function that is valid so let's write that it would be a boolean function and it would have all the three conditions that we saw so firstly we will check whether the string has a dot or not if it has a dot we'll be performing some functions else we'll be performing some other things so the first rule that we saw was for no dots and for that the number should either be 0 or the number should not start with a 0. so that is what we are going to write that is if my string is equals to 0 i can say that we can return true because that's a valid number otherwise we can just return that string does not start with 0. so we need to return that whether the string starts with 0 or not because if it doesn't starts from 0 it is true otherwise it is false and if it contains a dot then we need to break it into two parts and that two parts would be broken down with a regex that says that split on the dot so we will have part 0 and part 1. for part 0 the same condition needs to be there and for part 1 that is the second half we need to just check that it does not ends with 0. so we need to say that if the 0th part is equal to 0 is not the case and it starts with 0 in that case return false otherwise the first part has passed now we need to check the second part and the second part should not end with 0 should not be ending with 0 and that's the condition so over here we are returning in every case return and return so now we have everything in place we have broken down the strings we have applied the dots we have made the combinations input dot we have added all the dot separated numbers and over here we have checked whether the string is valid or not so now let's go ahead and run this code and it's running fine for all the examples let's submit this and it got submitted so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep coding bye you
Ambiguous Coordinates
design-hashset
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Array,Hash Table,Linked List,Design,Hash Function
Easy
817,1337
1,665
hi everyone welcome back to the channel today let's solve a hard question from the code weekly contest the minimum initial energy to finish task the question statement so we are given an array a task where each element in the array is an array of two elements actual and minimum and actual is the actual amount of energy we have to spend to finish this task and minimum is the minimum amount of energy we require to begin this task so if the current task is an array of 10 12 and the current energy we have is 11. we are not able to start this task because 11 is smaller than minimum 12. however if our current energy is 13 then we are able to complete this task and we will have 13 minus 10 which is 3 left and we can finish the task in on any order and we have to return the minimum initial amount of energy we will need to finish all the tasks for example one the minimum initial energy we need is eight and we will finish the task starting from the third task and then the second and the first and at the end we will have one energy left and for example two the minimum initial energy is 32 and we will finish the task in the array order which is one two three four five and at the end is also one energy left in a data constraint the length of an array can go up to 10 to the power of five so we have to figure out a solution with time complexity between big o of n to b over n squared okay and a key intuition to solve this question is to find the pattern so let's think it through so for every task which i denote as cost and minimum we need minimum to start this task but only cause to finish it so that means that after this task we will leave a minimum minus cost for the next and following task so for the next task 2 if we don't have enough energy to start this task then we need to add minimum two minus saved in order to start this task and the goal is to minimize initial energy so we can maximize a safe at the beginning which will leave extra energy for a later task to use and that will lead to the greedy algorithm and what greedy means is that for the task array we can reverse sort the array by minimum minus cost to have a task with higher safe energy at the front so we can have more safe energy at the beginning which will leave extra energy for later tasks to use now let's look at the code okay the code is pretty short and clean first reverse sort the task array by the difference between actual and minimum and rest is the output and current is how much energy we have at every index in the array so through the task array if minimum is bigger than current which means that we don't have enough energy then we will add the difference between minimum and current into rest and then set current to minimum and at the end we will subtract actual from current and finally is to return rest now let's see the code in action okay and here we'll be looking at example one and remember every task in the task array is an actual minimum so first thing is to reverse sort the task array by the difference between actual amendment so 4 8 will be pushed to the front and at the beginning current and rest are both 0 so minimum is bigger than current so current at rest will become eight and to finish the first task we'll need a cause of four so we'll subtract four from current so current will become four and the next task the minimum required energy is four and currently we have four energy so it's enough to start this task and the actual cost is two so current will become four minus 2 which is 2 and rest won't be updated and the final task the minimum energy is 2 and we still have enough energy and the actual cost is one so current will become one so at the end rest is eight so this will conclude the algorithm finally let's review so the key intuition to solve this problem is to find a pattern and that will lead to the greedy algorithm and how greedy works is to reverse sort the array by minimum minus cost to have more energy save energy at the beginning that can be used for later tasks and the time complexity is a lot linear because we have to perform sorting at the beginning and space complexity is constant and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
Minimum Initial Energy to Finish Tasks
diameter-of-n-ary-tree
You are given an array `tasks` where `tasks[i] = [actuali, minimumi]`: * `actuali` is the actual amount of energy you **spend to finish** the `ith` task. * `minimumi` is the minimum amount of energy you **require to begin** the `ith` task. For example, if the task is `[10, 12]` and your current energy is `11`, you cannot start this task. However, if your current energy is `13`, you can complete this task, and your energy will be `3` after finishing it. You can finish the tasks in **any order** you like. Return _the **minimum** initial amount of energy you will need_ _to finish all the tasks_. **Example 1:** **Input:** tasks = \[\[1,2\],\[2,4\],\[4,8\]\] **Output:** 8 **Explanation:** Starting with 8 energy, we finish the tasks in the following order: - 3rd task. Now energy = 8 - 4 = 4. - 2nd task. Now energy = 4 - 2 = 2. - 1st task. Now energy = 2 - 1 = 1. Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task. **Example 2:** **Input:** tasks = \[\[1,3\],\[2,4\],\[10,11\],\[10,12\],\[8,9\]\] **Output:** 32 **Explanation:** Starting with 32 energy, we finish the tasks in the following order: - 1st task. Now energy = 32 - 1 = 31. - 2nd task. Now energy = 31 - 2 = 29. - 3rd task. Now energy = 29 - 10 = 19. - 4th task. Now energy = 19 - 10 = 9. - 5th task. Now energy = 9 - 8 = 1. **Example 3:** **Input:** tasks = \[\[1,7\],\[2,8\],\[3,9\],\[4,10\],\[5,11\],\[6,12\]\] **Output:** 27 **Explanation:** Starting with 27 energy, we finish the tasks in the following order: - 5th task. Now energy = 27 - 5 = 22. - 2nd task. Now energy = 22 - 2 = 20. - 3rd task. Now energy = 20 - 3 = 17. - 1st task. Now energy = 17 - 1 = 16. - 4th task. Now energy = 16 - 4 = 12. - 6th task. Now energy = 12 - 6 = 6. **Constraints:** * `1 <= tasks.length <= 105` * `1 <= actual​i <= minimumi <= 104`
For the node i, calculate the height of each of its children and keep the first and second maximum heights (max1_i , max2_i). Check all nodes and return max( 2 + max1_i + max2_i ).
Tree,Depth-First Search
Medium
543
784
cool 784 in either case permutation given a string as we can transport every letter individually to be lowercase or uppercase to create another string we turn a list of all possible strings we could create okay cool letters okay I mean you could do this with I'm just I don't actually know what the expectations for users anyway but yeah for number 12 you know the first thing that do it like for n is equal to 12 the first thing you could think about is just like well there's going to be at most 2 to the 12 strings so that's okay to do cool force and that's it right just I mean I think that's what so we're just going to prove for us I think they're actually I mean I think you could definitely do something like and probably to be more optimal you would do something like branch-and-bound type things with it branch-and-bound type things with it branch-and-bound type things with it because so that you don't have to recurse on numbers but I'm lazy so I'm just gonna create a set end to it the lazy way oh and by that I mean I'm just gonna do or two to the twelve permutation no matter what even if we have numbers and then just used to set to sort it out which is step is slow a bit but in theory it is faster to type so that's really optimizing for a little bit some which I don't like matter interview but I'll talk about that after I actually get it done verse and Here I am using bitmask into I made fun of people using big mass just earlier so and I do need actually most of these prevents because of the order of operation with bitwise operators to lower I always forget how to just look at Python them real quick it's like to lower just lower okay hmm oh whoops cement J KS I'm just kidding Oh whoops so I was just working my iPad so I could see people's comments and quicker yeah cool I mean that slow time is not surprising because I don't know I definitely did this the probably the most in the efficient way possible but though it still has the same time complexity but not space well a key space complexly is well a little bit well it's the same complexity but constant decided they know them so I'm not surprised but I was happy that it once because I'll be a little sad actually I mean time limits out well yeah but um yeah I think this goes back a little bit to what I'm so yeah during an interview I applied on recommend this I would probably actually recommend doing a Accenture like a def for search or just recursion and only branch out with you have a number I mean I have a character but here I was just being a little bit lazier maybe like a little bit in the spirit of competitive programming since I've been sure playing around with that a little bit more where this is away type you know six seven eight like nine lines of code so like you know I'm not gonna make that many mistakes to I you know I just said that but then you know you were paying attention I actually had the wrong index here but thankfully that got caught out very quickly yeah but it's just that you know brinda or so some of that is I've written this code probably like thousands of times so I'm more confident about it and that allows me to gonna get it done very quickly and I started I mean I don't know how long I've been talking about his farm but I finished just within like four or five minutes which is probably kind of good but yeah I mean I think the bitmask is just a little bit like in Python is that it's really not pythonic I think in general because I think I mean that's it I mean it's not pythonic in general so it's not a yeah usually I should know keeping his pythonic I would have converted to C++ or something but yeah converted to C++ or something but yeah converted to C++ or something but yeah but idea here is that you know there's two to the N possibilities so then for each one you can look at you know each number is say yeah oops you have something like binary number and then for each index we look at do it the other way for each index we look at it and if it's a one on that if there's a one in that category in that bit we set it to look it's you use the lower case and with that you we used up the case and that's kind of the basic idea behind this tight code you slice you actually see there's no variations of this a lot when you do coding but uh yeah I mean it should be very easy with graphics which I don't lecture that's actually pretty tight too so I'll put up on the screen so maybe I should have to think about this but uh that's very tight well yeah cool I mean I but in terms of complexity is just 2 to the N I mean there's some constant optimization that we talked about it and that I'm blacks made for example and space is also 2 to the N which is technically output sensitive depending how you want to define it and output sensitive is a cool term so I like saying it but it's technically off to the end which is you know as fast as you can make it and even though I have a first constant because I put things in a set and then I put you convert it to a list but yeah me over this is definite part is this I think this is actually a good this actually is a good practice problem if you're a little girl begin and I think actually because then you could practice this you know doing multiple ways one maybe not displayed but definitely implemented with a Q and implemented with you know recursion you know with a stack and so forth and definitely and it's just good practice and this is a very basic prompt so that you could practice those things so I definitely recommend this problem for those reasons I don't think it's like I've yeah and for that reason it's a good problem to practice I don't know if you would get this explicitly but I definitely and your prices are not recursion type problems and DEF research type problems anyway so and this is all I wouldn't say prereq but like this is a subset in difficulty of those problems so I would recommend it yeah
Letter Case Permutation
insert-into-a-binary-search-tree
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. Return _a list of all possible strings we could create_. Return the output in **any order**. **Example 1:** **Input:** s = "a1b2 " **Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\] **Example 2:** **Input:** s = "3z4 " **Output:** \[ "3z4 ", "3Z4 "\] **Constraints:** * `1 <= s.length <= 12` * `s` consists of lowercase English letters, uppercase English letters, and digits.
null
Tree,Binary Search Tree,Binary Tree
Medium
783
81
Jai hind is problem fifty tere bandhe Raees clip from middle sorted in this app you can contain decrease is more exactly values ​​like this you can contain decrease is more exactly values ​​like this and strong sorted my tablets flatlens duplicate so wick liquid input deficit in this alert to a sweet can go appeal this to improve tiffin The recruitment scam is completely different from the one where the problem switches to airplane mode because subscribe and complicated problems can be sorted in soft and let's see who completed this that where they have something like this is possible that and in that Bihar from her own words which Have Been Explained Purely Meningitis Values In Late 20 Days 310 Also Have Four Five To Six Degree Lee So Let's Beer Searching For 5 Ki Sui Thum Toe Middle Acidity Share And Strengthen One Special Case Discuss My Dismissal's Sanitary K This latter increases the time complexity of solution in this case not defeated by increasing exam we can do it in law graduate time but for some places I just can't do anything for example it's a dictionary of middle share special loot values thrill middle east good values The Video then subscribe to subscribe our se loud login time research subscribe button intermediate subscribe that they remedy se match referee se match right and they can't do anything rate than in preventing left nd right let's take another case Thursday ki cm name par mili share distance id the family eats a A Pitch Values ​​700 Middle family eats a A Pitch Values ​​700 Middle family eats a A Pitch Values ​​700 Middle East A Criminal Pipe Target Datsun Whose Slapped Irons Middle East To West Is 30 Did Not SMS Left And Right Such Complaints With Left Services Vinod Now This Party Charlotte On A Noble Check Withdrawal Target Line Others And Not Very Easy Compare With Flute And Current Value Supervisors And Vinod Departed Soul Can Get Rid Of It Should Be Noted Here That Time From This Point Is Not At All The British Booty Was Not Least One Minute But Left For More Than Solid Skin Pimples And To Alert All Now Dushman Media Player Electronics Udhar Party Not Needed To Compare Udayveer And Subscribe Switch On Battery Saver Mode Select Sit And Reject Meeting In The Morning Reducing This Problem By Half Will Only Minor Differences From Normal First Version Of This Problem Related Problems Without It's Not A Distinct As Way Can not do anything left side a bird on log in subscribe channel subscribe hai but to on a great believer of log in a the police arrived from this confirmed will write in si plus jhanjhal pratham hua hai kar Sewed from two denote left and right in defiance watching happened that suis alarms mid semester get near term with the best case a view from the match the illusionary continue research shows that will do subject just numbers l who is equal to names that mid key and Ko namaskar hu is equal to namaskar mid sudhir veeravratam hua hai ek din they can't do anything which part to search soft will do we need to plus and - - a ki tense is equal to namaskar chal hai so this day is equal to medium left Party sorted to listen here will pick dead lift and reserve bank depending on weather target like share and not that this phone number is on sale, hence on this day the quantity target and the words that media is in this mode on target is hua hai ki day target looting Loop 2018 Hai What Will You Are Equal To Meet - One Because It's More Hai What Will You Are Equal To Meet - One Because It's More E-mail Voice Mail Equal To Meet Plus One Too Even Today In This Case With Nodal Point In Difficult For Art And Against Case In Left Craft And Other Cases Right From Disputed Disturbance middle age ki Bigg Boss image now we monotonic increasing line summit at some places because husband bread pit subscribe to the middle also here in this part and from this point depending on the bed here life will be sorted and right thought will start at both parents can Not be confident were yesterday morning healthcare system right party started login check Thursday is a sanam smith dr so this day target is that and MP3 phone number 60 that is more than equal to target in which leco le2 mid a plus one e-mail pe e-mail pe e-mail pe Are Equal To Me And Minus One Exactly SIM Logic On Modi's Head That And Finally Bigg Boss Return Forms A The Freedom In Counter The Situation For The Invaluable Upton Rathore Vikram Nicol And Lewis Mode On Will Not Find I Secure The Person Sector -2 Disclosures Hair Open Close OK To Kar Do That And Went Wrong So Let's See What's Wrong A Slap The Person Sector -2 Disclosures Hair Open Close OK To Kar Do That And Went Wrong So Let's See What's Wrong A Slap Of Or Fuel And Size Minus One That Mid Point Tomorrow Morning Nam Summit Shouldn't Mukti Mistakes That Media Jobs And Journals Media Jobs In Tears For This Will not be any compensation issue that this solution not meat which mistake and villains a noise pollution act were electricity will be able to get software right the pickup distribution som water side veerwati se zameen u ki nou will do something in japan fight them some improved only Switch and different in which subject Singh that when solution slap loudly and exit 10 to 12 which first will do it in python tree hua do the independence solution objective C
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33
1,095
hello guys and welcome back to lead Logics today we are going to solve the question find in Mountain Area it is a lead Cod hard and the number for this is 1095 so we have to find an element in the mountain array and we have to return the minimum index of the element so what is a mountain array so in this question we are given that a mountain array is such an array that its L is definitely greater than three and there is a index or element for which every element on the left hand side of the element is smaller than the element and every element on the right hand side of the I element is small smaller so there is a peak in between it is the uh it can it is the Maxima of the entire array Global maximum and we are also given that the mountain array which we are given it canot be accessed directly we have to use the get and the length function which are defined and we cannot make more than 100 calls because if we make more than 100 calls we will be given wrong judgment so seeing uh after seeing this we definitely know that the left hand side and the right hand side of or the element are sorted the left hand side is sorted in the ascending order and the right hand side is sorted in the descending order so since we have to search in a given space and the space is sorted so definitely binary search will be applied here so let's come to the approach let's take an example so we are given in Mountain array 1 5 10 20 15 5 and 3 so you can see 20 is the peak all on the left hand side are smaller right hand side are great also smaller and left hand side is sorted in ascending order right hand side is sorted in descending order so in this we have to find a Target now suppose if we are given the target as 20 that is the peak itself so there can be only one peak in this case so we will directly return the peak index because if it is the peak there cannot be any other element with the same value as the P because the condition given in the question are smaller than and not equal to smaller than equal to that's why and coming to the second case if the target is not a peak then also there are two cases like for example if we give the uh Target as 10 so in this case the target is present only on the one side that is on the left hand side if we keep 20 as the peak element so it is on the left hand side of the are left hand side of the peak but and you have to return the index of the 10 but if you take five in this case then for five you have two indexes that is one and five so according to the question we have to return the minimum so what we have to do is that first of all we need to find the peak element in the mountain area then what you will do then you will call binary search on the left hand side and the right hand side so let's come to the coding section so the first step uh will be to find the peak element so we can write an function to find a peak element so private and P index so this speed uh takes the mountain are we Define the in left = to left = to left = to Z and in right = Z and in right = Z and in right = to do Leng minus one now we'll find the peak using the binary search because we know the conditions first we'll calculate the mid left yes right and minus left y now if there is such a case that mid is greater than the mid + one then we can greater than the mid + one then we can greater than the mid + one then we can say that mid may be at Peak mid maybe our Peak we are not sure but mid maybe our Peak we'll put so we'll shift the right hand pointer to the mid we are not shifting it to Mid minus one because mid can also be our Peak else if mid is smaller than mid + one then smaller is smaller than mid + one then smaller is smaller than mid + one then we can definitely say that mid will never be r p because it is either smaller or equal to and according to the conditions it is always smaller it is always greater than the left hand side and the right hand side so we can definitely say left will be mid + 1 because in this case mid will mid + 1 because in this case mid will mid + 1 because in this case mid will not be a peak and afterward we simply turn the left so this will be our uh finding the peak or function so now we since we have the P what we need to do is that we need to write a binary search for the left hand side and the right hand side so for simplifying we can write a simp simple binary single binary search with a condition of ascending so that we don't have to write it repetitively so let us write uh binary search for this for the left hand side and right hand side so it will take the mountain array as the argument along with it will take a Target and the left and the right now first of all we need to check if there is a the we are on the left hand side of the peak or we are on the right hand side of the we can check this using uh oan value and we can check the left and right value if left is smaller then we are definitely we want to say we are in the left section if the right is smaller then we can say we are in the right hand side of the PE so Moun array do get left if it is smaller than M ARR get on the right now we can simply apply our binary search mod calculate the mid we'll also need uh to store the med element for uh comparisons so we take the mid element now if the target equal to the mid element we are uh taking the mid element because we want to minimize the number of get calls and if we'll call every time get in comparisons then we may exceed the 100 go so that's why we are taking one and checking the mid element so if the target is mid element what I told you simply return the mid otherwise we'll check if we are on the left hand side or if we are on the right hand side so this is what the left hand side if we are on the left hand side and the target is greater than the mid element so Target is greater then shift the left pointer if Target is smaller shift the right pointer then if you are in the right hand side and if Target is greater than mid element shift the right pointer else shift the left pointer simply return minus one if uh mid is not found so this was our binary search uh function now we need to write this driver function so what we are doing first of all you need to find a peak so Peak equal to Peak index and pass the mountain ARR simple then we need to find the binary search first of all we'll check in the left section because if an element is find on the left hand side it will always be smaller than the element found on the right hand side so first of all we will call the binary search Mountain array left uh Target left equal to Z and right equal p if is find in this if our index is not found is found then simply return index else return binary search on the left hand side right hand side Mountain AR Target P comma I think we can give it B+ one comma I think we can give it B+ one comma I think we can give it B+ one because we have already passed B there and uh here we'll give Mountain lus one so let us check if it run fine so we have so you can see the answer is accepted for the sample test case now run let's run for all the test cases yeah it passes with a good run time and a good space so this was our approach so if we talk about the time complexity is and login because uh we are performing binary search three times and the space complexity is of one because we are not using any space only the binary search is called two times and the peak index is all one time so this was my solution please do like the video please share it to your friends and please subscribe to my channel guys I need your support and I will post daily Solutions like this every day if you want to take a screenshot of the code please go ahead this is the mountain array and the peak index function and this is the binary search thank you for watching the video have a nice day guys
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
64
what is up YouTube today we are gonna be going over minimum path some it's a meme problem leaked code Amazon had last this question before I started a slack channel where I posted problems I posted the link below and lastly check out my channel and subscribe if you haven't already I post videos every weekday I'll see you guys soon alright so the ocean reads given a m by n grid filled with non-negative numbers n grid filled with non-negative numbers n grid filled with non-negative numbers fun path from top left to bottom right which minimizes the sum of all numbers along its path we can only move either down to right at any point in time so we can only go right and down and we want to find the maximum to this number so that returns seven because we go 131 and then down so this one's good for drawn out and the whiteboard first thing you want to realize is the first row in the first column they only have one possible min sum because we can only move down and can only move to the right so we're gonna put the first step is we're gonna want to calculate that so we're just going to move along so 1 plus 3 is 4 3 plus 4 is 8 plus 8 is 16 1 put three years for three plus five is eight 8 plus 2 is 10 I did that wrong 4 plus 5 is 9 2 plus 9 is 11 so the pseudocode for this is going to be int I equals 1 so we do 1 because we're we don't need to figure out the sum for this one it's just itself so we start here and here we're starting here for the 4 here for the first row and since we're moving along the columns in the first row it's the number of columns so that's where we're going to set our endpoint so I less than columns don't get tripped up it could you could think it would be rows but that's not the case and we're gonna solve this in a top-down and we're gonna solve this in a top-down and we're gonna solve this in a top-down fashion you can do bottom-up but I just fashion you can do bottom-up but I just fashion you can do bottom-up but I just want to do top-down because that's what want to do top-down because that's what want to do top-down because that's what it's asking for anyways but you can do it either way and so we have grid so we want to do the first row so it's 0 because that's the first row and then we're doing I plus equals and then we're just gonna add the previous so for some of this one we don't want to add this one so we just subtract I minus 1 so good 0 I minus 1 and same thing for column so we're gonna have J equals 1 J sorry for my Salafi handwriting trying to write this fast J plus and the same thing just swapped so we're gonna have J here because that is the rows we're moving down the rows this time so we're changing it that's why we put J there and this is the first column J less and yeah oh no I already did the 4th Jesus so plus equals grid so we just subtract one from J minus 1 0 so that's the kind of like the first step next step is we want to solve these ones so we're going to use for this one we're going to use the math dot min function and we're going to find the min of this one in this one and then we're just gonna go over long the rows and then down the columns so it's gonna be two for loops making it o of N squared run time so we're just checking for each one we're gonna check for so for this one we're gonna check this the min of these two so let's just go along real quick two plus four they're the same so 6 then we have 2 plus 8 or 2 plus 6 well 2006 is smaller so we have 8 and I'm just gonna go through these real quick 7 + 6 13 well if it's a 9 + 9 18 3 + 7 + 6 13 well if it's a 9 + 9 18 3 + 7 + 6 13 well if it's a 9 + 9 18 3 + 11 14 2 + 9 11 3 + 11 14 so in this case 11 14 2 + 9 11 3 + 11 14 so in this case 11 14 2 + 9 11 3 + 11 14 so in this case we had returned 14 so let's draw the pseudocode for it and we're also going to start off at 1 we're gonna want to start here so we're gonna put both that one this is the one for one in one position so I lesson rows and the J equals 1 J less than columns J plus close and we're just going to have grade I J plus equals math dot min I ran out of space but it's the one above it in the one to the left of it so let's just do that we're just going to subtract one from the variables so first thing let's grab the rows cool and the columns and let's do the first row so or Jesus Vince oh my god Google was one so remember it's columns no columns so we have grid the first row so we're doing good 0 I plus equals grid 0 and then we're just some that's not 0 i minus 1 and then the first column and same thing just swapped already pseudocode of this is j0 just a first column and then we just need to do the rest double for loop and just ij+ equals or no it's remember we have ij+ equals or no it's remember we have ij+ equals or no it's remember we have to do the math dot min function so grad Phi minus 1j or grid I J minus 1 and then we just want to return grid rows minus 1 and columns minus 1 because in this case the it would be three rows we can't we don't actually have a xxx index that's why we subtract when done here so let's just submit that and it's one space complexity because we didn't have to create anything new so this one works hopefully it works on the Smit as well yeah there you go so it's pretty fast great memory usage we didn't create a new array thanks for watching if you guys like this video hit that like button I'll see in the next video
Minimum Path Sum
minimum-path-sum
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\] **Output:** 7 **Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum. **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\]\] **Output:** 12 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `0 <= grid[i][j] <= 100`
null
Array,Dynamic Programming,Matrix
Medium
62,174,741,2067,2192
1,689
hello everyone welcome to quartus camp we are at 26th day of mail it code challenge and the problem we are going to cover today is partitioning into minimum number of deci binary numbers so the input given here is a string which represent a decimal number and we have to return the minimum number of positive deci binary numbers needed so that they sum up to n so here they have given few hints that actually reveal as the answer itself so the first hint says think about if the input was only one digit then you need to add up as many ones as the value of this digit if the input has multiple digits then you can solve each digit independently and merge the answers and thus the answer is equal to the max digit so simply this is actually the answer for this problem so let's understand this with an example so before getting into this example let us see the first hint given in the problem it says what if there is only one digit and how would you solve it so the binary numbers has only zeros and ones so if you want to form any number then you have to use only these two values for example if there is only one digit consider three is the digit and you want to form three by using the binary numbers and what are the minimum number of binary numbers needed so it is a one digit number so in that case you need only one digit so if you add up three ones you will form three and this is the minimum possible solution for this problem now jump into the example given so here there is 32 so if you want to form three you need three ones so let us fill three ones or three binary numbers and the rest is two so you can form two by filling once in any of the two binary numbers and fill 0 in the rest of the numbers so let's move on to three digit number let's say 135 is the three digit number so what is the highest number here 5 is the highest number so you definitely need at least five numbers with once to form five so consider we have five numbers with all ones that add up to five so the lesser numbers here are three and one so let's form three by filling once at three binary numbers and rest of the numbers are going to be zero so that they sum up to three same way we are going to fill one to form one in any of the binary number we have formed and rest of the numbers are going to have zeros so if you add all these numbers that is gonna form you 135 which is nothing but five numbers because five is the highest number and we need five ones to form that number so simply the answer is what is the highest digit value in the given string so that is what the hint three say so if you look at hint 3 it directly set the answer is equal to the max digit so we are going to do that only so let us declare a result variable which is going to have 0 and let us iterate the given string and we are going to update our result with the maximum digit in the string so yes finally return the result let's run and try this yes let's submit yes the solution is accepted and runs in four milliseconds so thanks for watching the video hope you like this video if you like hit like subscribe and let me know in comments thank you
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
1,793
hey everybody this is larry this is me going over with q4 weekly contest 232 maximum score of a good array um i think they just get lazy i mean this is it took a long time for me to actually just read this problem um because i don't know what is it go to way can you say anything else can you use any other adjective anyway i'm just kidding anyway it doesn't matter that much um but yeah hit the like button hit the subscribe button join me on discord uh let me know what you think about this problem and other problems um yeah so this one the idea is that it's just greedy to be honest um so basically you have this idea you know you have disarray oh i do we got this live so if i didn't edit that out then well you know um but yeah but let's say you have this array you know you can actually um yeah you can actually change it to in a way that is you know basically what is a good array right a good array is if it contains the index k and so then starting from that index let's say seven we just go um monotonic you know we take the min starting from there right so that means seven four to the right and then uh one three oops three seven to the left right because starting from the seven it gets smaller because it only cares about what the minimum number is right and once you kind of have this array once you're able to rephrase this then it's just greedy because basically you start seven okay what's the next time i'm going to expand well it never makes sense to go to three one year before you know for length two you always have you know just go for the greedy one uh for length three you go seven four and for length four you go seven you know you add the three and so forth so this is very greedy you basically um have a two-pointer you basically um have a two-pointer you basically um have a two-pointer system to calculate you know the to greedily add with one at a time and then calculate the score for that and then that way you always get the optimal score for a for each length and then for each length you just you know take the max out of all those so i'll go over my code real quick um and i'll make this smaller so you can kind of see it in one screen roughly maybe but yeah but basically yeah i just said i have a best array that just looks at the minimum going from the index k and yeah this is just going left this is going right to set the minimum uh this is hopefully this makes sense and then this is actually i don't i feel like this is a little bit easier than i would imagine um but yeah you know while this is true i go to the left i go to the right um you know i greedily you know if we have the left endpoint we move to right up if we're at the right end point then we move the left up otherwise we take the bigger we take the number that's bigger and then we add it to the thing um and that's pretty much this is to move the point the two pointers um so you start from the middle at one length one and then slowly you make length two length three you know moving left or right whichever pointer um and then at the very end or i put it in the beginning but yeah once we count all the numbers then we break and we return the answer i had a miss i had a typo uh where i forgot to consider the entire way so that was just a silly mistake but yeah but basically this current is the current min and the min is just basically either the left the min of the left or the mean of the right because you know that min is at one of those end points that's why i have the current and then this is just to get the um the area if you want to call it the maximum score which is um this is the rift times this is the minimum which is what we're getting uh and this is the answer you take the max and then you just return the answer at the very end um yeah so this algorithm is going to be linear time because we look at each number and index or each number in the array constant number of times one's going left one's going right uh well not given the same number just each number gets scanned once in this loop and then here it gets you know if you look at each for this loop only uh this while loop only happens of n times because um because uh you know it starts with length one and then start and then length two and then length three and then so forth all the way to length n after n iterations so yeah so this is of n time of n space given that i have to um i have the min and i don't think to be honest you even need this uh looking back you could kind of keep a running track um you could do something that's like a running count keeping track of things along the way um i think the way that i did it um was more intuitive to me while i was thinking about it um because i and also um because i wasn't able to i think when i was solving it during live during the contest i didn't want to prove it exactly so i kind of i and i figured that if i had a solution it would need this anyway so that if this was wrong i still have this to kind of work around with um you know to build off i would also say if you watch you could watch me solve this live next and i actually have you know you could watch maybe near the end of that live video to see how i debug um because i got a long await like an n is equal to 500 elements and i don't ever i didn't know how to debug it so you could see how my dot process and how i debugged that um because you know every minute counts even though it was a little rough but yeah um that's all i have for this farm you can watch me sub it live next okay we've already finished well okay what's okay men uh where does k come from this is just a silly definition of good but okay there's like a mono repo thing mono q thing or whatever how did i combine it here you so you know this whoops hmm um uh come on thought that would be right to be honest oh they're equal what would i do to equal because of the euclid shouldn't matter why did i get this one hmm the damn it's probably one of technology about this hmm so what that was a mistake dot one four six what's by the last number i have all five one or the last number that is weird oh that is dumb i am a dummy okay that five minutes uh yeah thanks for watching uh let me know what you think about this problem set uh it seems like it's been it's slightly easier than usual but uh yeah hit the like button to subscribe on drama and discord and you know you take care of yourself and yeah to good health to good mental health i'll see you next week bye
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
82
hey hello there so the second link list question I'm looking at the day as the 82 removeduplicates front soldier listed - so it's potentially a full upper 283 - so it's potentially a full upper 283 - so it's potentially a full upper 283 remove duplicates for answering a list for that question we have a sorted linked list so the news value inside this little aside in the ascending order so it's keep going up we want to delete all the duplicates such that each element can only have one occurrence inside this linked list so one two will become one two so that's a at least to keep one of the nose with the duplicated volume inside this new update is a linked list so for this full upper question it's the same linked list that's in the solar order you know while you are going up but the difference is that whenever we find a note that can a value that's have multiple notes with the same value but we want to remove all of them entirely so as the example we have this linked list of 1 2 3 4 5 we want to remove the two notes which value 3 and also removed the two notes of a 34 so the linked list will become 1 2 5 so to solve this problem we're gonna solve this first thing there it iterative fashion and then talk about the it returns a problem recursive one so obviously we want to do this processing this to tackle this problem we want to do a linear scan of the linked list so we're looking at the nodes one at a time and the logic is that if we see that the node has the same value with the next node value that means that we from this node and all we are entering the duplicated subsequence and we want to get out of that sub sequence as part as far as possible so here so it just did that so this case here we have traverse of all notes the pointer that the traversal notes value is different with the next note value that means we can advance without any problem so as a result we will be looking like this and then we find that the note that we are looking at the reversal notes has a value 3 and our next note in the sequence also have a value of 3 that means we enter the we're entering the duplicated subsequence and we want to get out of as soon as possible ASAP so we want to achieve something like this so to move the traversal now to be first and no that's not of the same duplicated value and after that we want to do the short which just have the previous nodes instead of pointing to the depleted a starting point of the duplicated section we want to have it points to the first node that's outside that duplicated a section so that can potentially be pointing to a node that Plus no duplicated value that's not duplicated body so that's this short here so after the short we pretty much exist exit this you know subsection subsequence with the duplicate value no value sweet here so that's pretty much the approach just gonna advance the traversal ooh this link list also keep track of the prior nodes and when we actually entering the duplicated a subsequence that's indicate indicative by that normal nodes value has the same value as the next node value that's indicating that we're entering this you know repeating section we want to get out of that as soon as possible and after we exciting that we want to have this rewiring to short the section here so that's the premise of the logic and so the we need a prior state for this prior node which can potentially just be in null pointer so if we choose to do so we might likely to encounter the case there the very first node that we're looking at can potentially just be the duplicate starting node for duplicated section so after we do this escaping we will be pointing at the node to here since that the previous is actually still a null pointer we couldn't do this rewiring so instead we actually just kind of feel how the handle pointing to this note to here because that can potentially be a candle for the deduplicated linked list so just going to be a little bit branching there once we escaped the duplicative section we could either do the fentanyl reassignment riri or we can do this previous note link short so there are two options there for the iterative approach so overall it's going to be a linear path but from the head node towards the tail to do whatever in that it needs to do the deduplication for the space we got a couple pointers so that's a constant in space so that's the summary about this iterative approach so I'm just gonna put this up finish quickly I won't also be able to look at those notes there so we got a previous pointer which is no pointer in the beginning and we have a traversal now that's starting with the head node in our entry point to the linked list what we want to do is to keep traversing a camera is totally blocking me so the termination criteria is that if I still have an ex note that I need to at least take a look whether I have a duplication with it or not and it also indicates that I'm at the tail or not if I just have no notes left that means I safely which the end if I have the next I want to do at least do a duplication check there so that's the termination I can just put the return head here so just going to follow the logic here if my value is not the same as my next that means I can safely advance so that's only condition that I do have a next right I don't need to check that the while condition is as guarantee that I do have a safe next note so I don't want to advance past the previous pointer and also the traversal last winter otherwise we pretty much officially entering the territory of duplication we want to get out as soon as possible while we can still run to the next and my Nexus of the same body as myself that means I'm still not out of the water yet if that's the case I definitely want to move further so after this while loop will be the very last node in this section subsequence of repetition so I would need a one final job to get out of there so after that I will ask the Prine prior know to reattach to me instead of the starting point of the repetition geez so that's the code oh sorry we need to look at whether this previous pointer is actually no not otherwise all the stuff we do instead is to reassign head to pointing at this new node here a new potential starting point of this deduplicated a linked list so that's I think it's the code for this iterative approach let's see if it works all right I'm just gonna quickly check we have a null pointer to be the previous node the traversal no we're starting with the head node we want to go as far as possible towards the end and if we are not in the if we're definitely not the starting point of repetition subsequence we won't keep moving forward otherwise we entering the subsequence that's a repetition duplicates we want to move out of that after we move out of that if my previous node is actually a valid node I want to have it pointing to me otherwise I will just tell the head no hey I might be the new head node for this deduplicated linked list so it looks reasonable so let's try something with it okay it's working then after this I'm gonna try to talk about the recursive one is there's no benefits in terms of the time at space it's going to be the same linear time complexity but the cost act is going to be linear because it has to go all the way back and then fact tracking in so it's not space-efficient but for so it's not space-efficient but for so it's not space-efficient but for whatever reason that you might be asking to do so you've got to do what you asked it to do I guess so that's just thinking about what if I myself it's actually a noting here what I need to do so obviously one thing the thing I need to do is to check my next my value is not the same was my next so the thing that I want to do is do I want to ask my next to initial the Sam deduplication process for the subsequence that starting from him or her and after him or her has already done that he will give me the handout for the duplicated sub C sub sequence you know link list and once I get that pointer I can point him myself to that so I want to do this otherwise if my notes value is the same as mine next the notes value that means I'm pretty much the in the midst of this subsection of repetition what I'm going to do is to get out of that as soon as possible and once I'm out of the section of a repetition I want to return the function call on myself because I you know I'm an officially a new node and a node with a new volume non-rapid now node with a new volume non-rapid now node with a new volume non-rapid now repeated duplicate value potentially be so I can return f of myself now so that the guy that cost me to do the same can potentially link himself him or herself to the new starting point for the deduplicated link list so that's the recursive relationship the base case is that if I am just a node by myself I want to return myself because I have nothing that don't string in the line that I can be duplicated off so if node has no next yeah so that's pretty much the reasoning I just use this graph a little bit to illustrate this case so a volume a node and I check my next actually have the same value as me so I want to move myself out of there and the starting the deduplication from here and return the head node of the deduplicate version so in this case you will be repeating the second section again until I move myself to five so after that I will actually say to node 2 here is the head node of the subsequent row link links that has no duplication please connect yourself with this here and then download will actually return himself to node 1 and node 1 we will return it in the as the final output so that's the recursive relationship recursive approach to solve this problem again the space is not efficient as the iterative approach and I for somebody like me who is not used to thinking the recursive relationship it's easy to get it wrong so it's just not going to code this up the first line is going to be the base case if not actually not base case but yeah it's base case if I'm not a valley known no pointer this is actually a safeguard here it's not our base case otherwise we need to check our relationship with next movie in the sequence so that's based on if we do have a next so we're just gonna cut the second branch here if my value is the same as my the news that's coming after me then I want to move out of there as soon as possible it's similar to this while loop here so Wow I still can move and my value is the same as my next value I want to go as far as possible so after that I just have my you know I could do one more job final job and then I am on a body was the first non-repetition body so I can try to call non-repetition body so I can try to call non-repetition body so I can try to call this deduplication on myself otherwise it means that my value is not the same as my next value I would just ask my next to initiate this deduplication for the nodes for the subsequent row link to list starting with my next and after that's done he will return me a new head node for the you know subsequent deduplicated linked list and I will be able to safely connect myself to that so the thing I'm going to do is still have my next pointer points to the deduplicated version from my next and on so that's pretty much the recursive code let's see if it works cool yeah so you will linear time still one pass but the cost stack can be linear time as well so the universal case it's just every note is pretty much distinct so we will just keep calling this deduplicated on the next no on the next until we turn find the tell note you will return yourself and that node will return himself to all the way back and after that we can return the head so it's a little bit of being efficient compared to the iterative approach if you ask me alright so this is the to approach iterative and the recursive approach to question 82 so yeah that's it for today
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Output:** \[2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List,Two Pointers
Medium
83,1982
1,750
hello guys welcome back to my YouTube channel today I going to solve day five problem of this month on lead Cod if you guys haven't subscribed my YouTube channel yet then please go ahead and subscribe it now without any delay let's get started with today's problem so today uh we are going to solve problem number 1750 that is the minimum length of a string after deleting similar ends Okay so in this problem we are given with the string s which is consisting only of characters a b and c and we have to apply following rules on our string okay so we have to pick a nonn empty prefix from the string s where all the characters in the prefix are equal pick a non empty suffix from the string s where all the characters in the suffix are equal then the prefix and suffix shouldn't intersect at any index the characters from the prefix and suffix must be same and delete both the prefix and suffix okay and in the end we have to return the minimum length of s after performing the above operation any number of times possibly zero times okay so here in the example one a string s given to us c a okay so first character that is our prefix and the last character from the end that is our suffix so both these characters are matching here or not so both the characters are not matching right so we can't remove anything from our string in that case we have to just return the length of our string okay after applying all the operations so in this case the output is two because you can't remove any characters okay so the string stays as it is right and here in this example two this is a input string uh given to us so first uh check the prefix of our string so this is a prefix C character and in the suffix there is also C character so both prefix and suffix are matching so we are going to remove both the characters from the beginning and the end and then our resulting string is looking like this okay after that in this string again prefix and suffix are matching so we have removed both a from the starting and a from the end in that case our new string is going to be like this b a b okay again our prefix and suffix are matching again we are going to remove our prefix and suffix then our new string is AA again our prefix and suffix are matching then we again we are going to remove our all the characters now the resulting string is empty so that is why we are returning zero here in this example we can delete both the A's okay both the A and this a why because we have to delete similar ends right the question name is clear minimum length of string after deleting similar ends okay so a is a similar end and this a is also a similar end right so in this example our prefix is a and suffix is a both are similar ands then uh after that our resulting string is like this again we take the prefix as b and the suffix as B okay so uh these two prefix and suffix are showing the similar ends for a string so after removing them our resulting string is like this CCA okay so the output is three so I hope that you guys are clear okay so now uh let's understand this uh how I'm going to solve this problem so first I'm going to take my start is going to be nothing but the beginning of my string right int start is going to be beginning of my string and end is going to be my S do length minus one so write like this s do length min-1 so this is my end okay now after min-1 so this is my end okay now after min-1 so this is my end okay now after that I have to run one while loop while my start is less than my end okay while my start is less than end and these two operations s do G at start is equal to S do care at end Okay so if these two things are matching so here uh let me take this example okay so this is a input string okay let's take this for better understanding okay so this is a string given to us let me copy it here okay this is a string given to us my start is uh at this Index right now okay this is my start and my end is at this Index right now okay so here right now I am checking if my start is less than end yes start is at zero right now and end is at this position so what is the total length of this string okay so can I write uh index let's do the indexing on this so this is at 0 1 2 3 4 5 6 7 and 8 so length of my string is nine and the character uh this is at index 8 okay s dot length minus one so while my start is less than equal to end and my S do character at start is equal to S do character at 8 so both are matching right a if both are matching so now inside this while loop let me take uh the current character okay what is the current character so C current character is s of right s do care at start so this is my current character right now right this a is my current character now I have to check how many a are there in the beginning and how many A's are there from the end okay this is what I'm going to check so I am going to here write one more while loop okay so here I am going to move my start pointer to the right until it reaches a different character or end pointer okay so here I'm going to move this cursor start cursor until I reach at some different VOR or I reach till end okay until then I'm going to move my start cursor so I going to write like this while my start is less than equal to end okay I'm going right now I'm going to move my start pointer okay while my start is less than equal to end and operation s do care at start is equal to my current care okay if that is the case then I'm going to move my start cursor start Plus+ okay this way I going to move my Plus+ okay this way I going to move my Plus+ okay this way I going to move my start cursor until I reach end or move to a different character okay so now for this particular example my start reaches here okay so this is my start position and what is my end position so end position is here only because there is only one single one right now but if there is one there is any example in which there are total two A's right in the end so for that I also have to write for end same statement same while statement so in the end I'm going to move my end pointer to the left until it reaches a different character or start pointer so I am moving my end pointer to the left start poed to the right and point to the left okay so again uh same way while start is less than equal to end and S do care at Care at end is equal to current care okay if this is the case then I have to move my end pointer to the left that simply means end minus right this is done now okay so now uh this is my s reaches to one and is at this index 8 right now okay so here uh for a right now we are checking so in this is a complete y Loop okay this is can complete cancel is okay so this is a complete while loop okay so in this complete while loop I'm going to check again and again okay so now my start reaches here and reaches here now a new character comes so now my new start becomes here okay so this initial Loop is completed here okay for the initial Loop I'm going to uh show it with right color okay this is initial Loops okay first uh outer loop is going to start from here right outer loop is going to start from here okay so now once uh this initial Loops are completed okay after that again I'm going to check for the while start is less than equal to end and yeah so I'm going to check for this B right now so this is a new outer loop so now I'm going to check for this one okay so now uh after that this be this is my new this is inner loop okay inner loop I'm executing Inner Loop B is here and then I reach is here from end because both are the similar string now this BB and this B is a similar Str okay this is done after that my uh outer loop is showing this C is reach reaches at this C and my uh outer loops and reaches at this position okay CCA now uh both are not matching now both are not matching my start and CCT so definitely my Loop is going to end here okay so my Loop is going to end here right so now here after this I'm going to check if my start pointer is crossed end pointer okay if my start pointer crossed the end pointer then there is no cor left so I have to return zero okay if my start is greater than and then in that case I have to return zero okay and otherwise I have to return what otherwise I have to return nothing but what is my end okay this is my string what is my end is five okay what is my start three and + one what is the output of three and + one what is the output of three and + one what is the output of this one is nothing but three right 5 - this one is nothing but three right 5 - this one is nothing but three right 5 - 3 + 1 this is what I'm going to write 3 + 1 this is what I'm going to write 3 + 1 this is what I'm going to write here and minus start + 1 so now I'm here and minus start + 1 so now I'm here and minus start + 1 so now I'm going to get the output as three okay so uh I hope that you guys are clear why I'm writing this okay so here uh let's say uh there is a string known as a okay so initially in the outer loop this condition is satisfied okay after that I'm going to run this is one character I'm going to pick so my character is a okay after that I'm going to move my start while my start is less than equal to end yes so my okay so here in this particular example okay in this particular example my start is starting from here is starting from one second my start is starting from here and end is here okay in the outer loop now I'm going to move my start so my start pointer R is here okay this is my new start how many starts okay this y Loop okay so now my new start becomes at this position okay this is new start now after that I am executing end but one time it will work now this is start less than equal to end so this condition is satisfied first time this condition is satisfied now uh in this my new start reaches here okay first I check how many Starts Now for end I'm going to check so first time I start is going to be equal to end and this is matching so my end reaches here in this case at this position okay at this position my end decremented and s++ okay this is end decremented and s++ okay this is end decremented and s++ okay this is what happening what's happening here so for that particular case I'm going to return zero okay in that case there is no element in our string okay so I have written everything now let's try to run the code and see so all the test cases has been accepted now let's submit the code so our solution is accepted right and I hope that you guys are able to understand today's problem if you guys still have any questions then please feel free to ask in comment section till then keep coding and keep practicing meet you in the next video thank you bye-bye
Minimum Length of String After Deleting Similar Ends
check-if-two-expression-trees-are-equivalent
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Tree,Depth-First Search,Binary Tree
Medium
1736
1,094
What is the problem of marriage, leaning forward, report problem number is 101, what is the problem of police, give us one and its quid, reasonable volume, maximum number of people can sit, then we are given a little in the name only, that melt, what is there in it. Like and if we talk about jeep players then in that 2019 indicates that you have to lift so many people, the second one is the starting point and the lighter, the third one is the indication there which means skin which is this one subscribe and then in between also you can get questions. So like in this regard, you will get three rides for free so that you can see it and after bringing them, I am leaving you in this attention right will come from here to here only once and you just have to tell that we will bring all the passengers. Will we be able to leave them in the country or abroad or not? If we leave then we will have to return the phone if it gets broken. So let's talk about this question. Let's just buy our car. Let's say this Chakli was ours and you are buying a Maruti car like this one. We are the first one. Let's make all the names, tell us how many people are there in the car right now, live like it's rubber, on this website that came from here, how many people will be there in the car at this time, two people will go here, pray to him, right before, Sindhu, now this is growing. Let's keep moving like after taking part, there were three more rides here, this Vansh husband man, there were more, what to do now because he has heart disease, he has to leave, then your electronics and here team man, he has got more if these three gomage It is sitting nearby, we can't do anything about it, so we will button it and the skin is not sitting there, Agarwal exam, if we need to take measures for pimples, then what to do now, this is near Kanpur, 120 proceedings have been taken on this one, if two accused are found on this issue, then this issue If you do n't get the subscription for three rides, then you have to leave it. Those who had it, leave it to the one who will get the subscription here. Bring it here and leave it. Will give as many subscribers as possible to do this question, what is the thing that first of all we create an ID which will represent these indexes like you know I am extra starting and question president subscribe 1230 1234 500 shy 12 This is like this This matter will be deposited by us till that time and whenever we get the winning index and quarter, we will give the account of that person bigger than ours, Kisan Express will decrement the leg of the bus by that much to deboard the passengers, it is okay as I say in the matter. On the first one, we got two riders, so what is there in this, now Vegeta, our channel is zero, has zero eviction, I have eaten the previous DP of my friends too, so what will I do to this account, then it will become a bigger plus two than that. Now where will I sit, look at the pages with daily discounts, I will decrease it by that much, meaning - I will save Krishna, now worry about the meaning - I will save Krishna, now worry about the meaning - I will save Krishna, now worry about the next time, where will Aamir get three rides, where did he get three rides, this is the thing on tips. I have an account of Rs. I will make it with this amount. Third, Chironji in it is zero percent and where will I leave it. Cement factories used to take out the customer - Ko - 3 Hey, what is it, used to take out the customer - Ko - 3 Hey, what is it, used to take out the customer - Ko - 3 Hey, what is it, we will first burn a clove and fold it, okay now we From here, we are clearing it by typing whatever value it will be, whatever the pizza bread is on the current index, it will indicate that and expect personnel is its ride, meaning that side effect, how many rides does it have and we will check that if this question which If it is less than or equal to our working capacity, then it is okay, as the fighter Sudhir will grow up, we can add this mail in it, as if we are adding from here, it is okay, now everyone is getting this question like my dad is the worst actor, okay, we will take it. Then he came here, what is this ride, there was no ride, if ever he is weak then let someone be okay, this is the meaning of the day on which Mother's Swami Country means this person's liquid is a man, this personnel please subscribe means school and every Then do the song from here, cigarette is okay then return it, subscribe because this time and the youth riding on this, people will lend because when in this, how many of this will I wash, okay, so here now I - I used to stay there again, now because I - I used to stay there again, now because I - I used to stay there again, now because Jatin, people were sitting here, now see how many people are sitting from here, as many people as you are sitting here, from rumor to both, then people falling here are five people, I will take them with me, I will wipe out the commission from the last, now something romantic like you. Its registration is here, both of them are China, so that means there will be a copy of this, it means that what we submit first is okay and whenever the destination for which the ride was, so that whatever you have subscribed in the appointment there. I will do it, subscribe to it and when Meghnad again gets any question, the painful pimple will disappear, the commission will be curvaceous, if the accused do share it in the comment box, you will get angry updates in this paste, thank you.
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
397
hey what's up guys so uh welcome to my little zone section so this is this uh 397 uh integral uh integer replacement oh so given the insurance you can replace the one or following so if one is even then you can replace and divide by two okay so that means if one is even you if it's even right then you don't have any way to do this the only way you can do is divided by two if n is then you have two ways which uh plus one or minus one okay and you need to return the minimum number options uh operations uh such that and become one okay so uh unless it is trivial right so just a4 to one okay so uh which uh this is a little bit difficult to prove right but hopefully you can easily say that if n is a power of two then you can quickly go to one okay so just by keep dividing by two and you can only divide by two right because by definition is even right so in this one you don't have any choice right you always need to go to uh you just need to you can only divide by two so there's no way that you can do other things a tricky part is seven right so seven has two ways it seems like if you mine if you add one become eight they become one okay if minus one becomes six then you can still become one okay so it seems like 47 that your answer is uh irrelevant for the first step okay so uh which makes a little bit stupid that let's write a code right let's suppose n0 let's say n is not one but i mean if one is one you just return zero right if one is not one then if one is even then the only way you can do is divided by two okay so here is the missing the interesting part you say that if an mod four is one then you can you must minus one if only small one is not one then you should add one okay so exception okay that is three okay so then this is okay so the problem so this answer tells us what tell us that let's do some uh theoretical understanding see why this is true okay so answer tell me what answer tell me that uh basically if any so if a mod 2 which is zero and you the only way you just divide by two right but uh there are two so uh so if you divide an and by four then you only get there are only four choices right so the first case is the four n let's say so you can view that n is uh let's say 4k plus one okay forget plus one 4k plus 2 or 4k plus 3. okay so this is even right so this guy can there's no choice so we don't need to discuss these and then we don't need to discuss this okay so we only need to discuss 4k plus 1 and the 4k plus 3. okay so answer tell me that the answer tell me that if 4k plus 1 then i should go 4k and go to k right because i divided 4. so this looks i think for this one it's very simple right you can just think it's you just add once you delete one that becomes even right so this should be the fattest that's the quickest way but how about this why this should add one right not minus one right because if you add one then become even if you minus one it still becomes even so the only non-trivial part in this so the only non-trivial part in this so the only non-trivial part in this model is that y why phone plus three should add one okay so this is uh how i try to explain it in this video okay so let's do this so let's try to give a simple argument uh so i would not say this is the proof but i would say this is an interesting argument so if you start from four wave plus three right you have two ways if you plus one become four one plus four and then you can minus divide by four right because after two steps it always becomes k plus one okay and then minus one you become 4k plus two okay then uh for this one there is no way you only divided by two become uh 2k plus one okay so now you still have two steps right so you can minus add one minus one so become a 2k plus two then it takes one step become k plus one okay so and for this one uh it's uh 2k it takes one step to become concave okay also for this one you can go to k plus two okay plus k uh minus one and one okay so now if i was here uh how many times can i reach k plus one okay so i take three steps to arrive k plus one right but in this case i need one two three four okay so i need four steps to arrive k plus one so the problem is that if you go these directions and up to here oh there is then up to the first round if you want to if your answer finally become uh so the problem is that suppose that if you arrive k plus one then you get your final beautiful answer then it seems like that add one is the better way right because if you want to arrive k plus one then you only need three steps in the right k plus one so it seems like that these directions may should be better right you just only take three steps and this guy takes one two three four right six four steps and uh the second is that those are the same right suppose you only need you want to arrive k then for this one you need to this and so you need four steps arrive okay but also for this one it takes four steps so mathematically then you should take the upper one because the in average case that upper the upper one is better yeah so this is the proof okay so this is the so the problem for this one uh this problem is hard to think of this argument but actually this is the answer okay so see you guys next video don't forget to subscribe to my channel
Integer Replacement
integer-replacement
Given a positive integer `n`, you can apply one of the following operations: 1. If `n` is even, replace `n` with `n / 2`. 2. If `n` is odd, replace `n` with either `n + 1` or `n - 1`. Return _the minimum number of operations needed for_ `n` _to become_ `1`. **Example 1:** **Input:** n = 8 **Output:** 3 **Explanation:** 8 -> 4 -> 2 -> 1 **Example 2:** **Input:** n = 7 **Output:** 4 **Explanation:** 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 **Example 3:** **Input:** n = 4 **Output:** 2 **Constraints:** * `1 <= n <= 231 - 1`
null
Dynamic Programming,Greedy,Bit Manipulation,Memoization
Medium
null
1,844
Salam alikum so we're going to continue with the lead code question 1844 replacing all digit characters as the question States you are given the zero indexed string s that has lower case English letter in its even indicates and digits in its odd indicates so there is a function shift C for characters X for numbers where see character okay uh for example as it shows for every OD index I you want to replace the digit with s with the index I with shift s uh inside the square bracket IUS one with s to the I returns this after placing all the digits with the guaranteed that the shift will be exceeding Z okay so now here is the example that is given but overall hopefully you guys understood now to tackle this question we're going to um convert the input string into character array for an easy modifier or modification let's convert the S to character array Char square bracket chars equals s.2 character array and we're going to iterate through the strings with the step of to process each odd index so how do we do that we're going to write our for Loop uh we're going to have our I in I equal to one instead of zero since we're looking at the odd numbers and we're going to have I less than s. length I plus equals two and inside the body we're going to calculate the character to replace the character I within the array using the shift function now we're going to have chars bring back our uh string that was turned into character array get the specific height where we're going to make sure it is shift to character I minus one that is given and uh how is it in the body shift s minus one that's what we're working on minus Char I minus zero character and we're going to leave our body a for Loop and then we're going to return a new string passing the character and after that we're going to come out of our for Loop did I miss something okay we're going to come out of our for Loop okay and we're going to uh write a helper function to shift the character by exp position so what we essentially did is uh we what we iterated through the string s and for each index I we replace the digit at s i with the character obtained by shifting i s i minus one by S minus the character Zero position and let's run it oh we're missing yes let's do this seems like we're going to continue our call on the next video
Replace All Digits with Characters
maximum-number-of-balls-in-a-box
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Hash Table,Math,Counting
Easy
null
249
hey everyone this is the lead code time so in this video there are two goals the first goal is to see how to solve this problem and then we are going to put some code there and the second one is to see uh how to behave during a real interview so let's get started remember the first step is always to try to understand the problem and also ask some clarification questions in case there is anything that is unclear to you and at the same time think about the ash cases so let's take a look at this question so group shifted strings so given the string we can shift each of its letter to its successive letter for example abc could be shifted to bcd and we can keep shifting which forms the sequence all right so let's take it take a look at this example let's say abc could be shifted to bcd and xyz as well okay so give a list of the empty strings which contain only lowercase alphabet group all the strings that belong to the same shifting sequence uh okay so let's see so suppose input is like this array we are going to group the this into an arrival array so it would be okay the first one contains abc bcd and xyz okay the second one contains a z and ba so let's see why so okay so a shifted to b and then the next letter for z is a oh okay all right so okay and then a c e f and a z all right so i think i pretty much understand the problem um and uh let's think about some ash cases let's see if there's any constraints so there's no constraints i would say definitely think about say some input case like uh suppose the strings input array is empty that would be the ash case otherwise i cannot think of anything special for this question so let's see how to solve this problem um so let's see of course the solution for this problem of course there is always a profile solution so for example we eter we use a for loop within another for loop to compare all the pa to compare all the pairs to see if uh one string is the shift version of the other one if yes then we put them together otherwise we are going to otherwise we just keep going to find other new pairs that are shifted that are the shifting version between each other um so that one is not good regarding the runtime because it's for loop maybe another for loop and inside of it we need to see whether a string is a shifting version of the other one so i would say let's say the average lens for so this is brute force average lens for uh let's say the average lens for each word is n and uh suppose we have m words then the runtime would be o uh m to the m square n times n so definitely this is not good regarding the runtime let's see if there's any other better option so i would say a another better approach would be you store a better version is you store everything other words into a hashmap and then you iterate through the input array input strings array and try to generate um all the possible iterations for each word try to generate all possible shifting for uh each string and then see if the if that exists in the hashmap if yes uh then that's the thing then we put them together otherwise we just uh keep iterating through it so i will say for this one um it's gonna be suppose the average lens of each word is n so we are going to uh do 20 we are going to find the 26 possible shifts for each word uh and then we are going to address through and worse so the runtime for this one would be m times n it's because there so although it is there is a constant which is 26 times m and times n because 26 is constant we just need to um omit it in the legal analysis so let's further see if there is anything that could be even better than this um so i'll say i would say currently the best version i can see is we compute the shifting uh between each letter within the word and then put the shifting pattern into a hashmap so like let's let me explain this so currently the suppose we have the we have abc as input string so we see that b uh so b is just one larger than a and c is one larger than a so we can say that the shifting within the word like when we compare the neighbor two characters it's actually one and then one let's take another example let's say if it is a c f so c is just a 2 larger than a so we put the first one as 2 and then c f is uh f is c d e f d e is three larger than c so we put a three here so this we call it the shifting pattern within the string and then we put we have a hash map so the hashmap key is a string which records the shifting version and the second one uh would be what the strings what are the strings that have the same shifting pattern because if two strings have the same shifting pattern uh then they are then than one word suppose word one suppose uh word one has same uh inward shifting pattern with uh word two then we can safely say that we can shift word one to word two so that's essentially the idea how to solve this problem so the runtime here would still be o m times n but because we are not enumerating all the possible shifting versions of the same word so we kind of made the 26 factor from the last uh from the last solution so this one although the runtime analysis is the same but actually it is better so let's see how to solve this problem uh let's put in some solid code here all right so we have okay sure so after we find the solution for this and the next part is about coding so for coding we care about the coding speed and your correctness of the code and of course the readability of the code so let's start to do some coding um okay so first of all um we will define the list string let's say this rt as new link blessed so uh if strings dot to a string sorry strings dots once is equal to zero then we just return ret without doing anything otherwise we need to go through the input string array and get the inward shifting pattern for each of them and put it in a hash map first of all we define hashmap so key the string which is the inward shifting pattern and the value would be a list okay so let's say uh i would say there's something worse consider is something worth consider is it possible there are some duplicate words within the input if we need to do some deduplicate then definitely we need to have this as a set otherwise we can keep the value of the map as a list so currently um it's not clear uh so let's assume that we can have duplicate words and then we will see so let's see this is um what is that pattern uh word words map okay as new hash map so first of all we are going to go through the all the strings let's say just the string that's the word strings so we are going to find the in inward pattern for it so is it possible that there are some words there are some empty words i'm not sure but let's assume there could be so let's define another helper function here so let's say we have the private uh string find pattern so input is a string it's a word so suppose we have this helper function which can find the pattern for it then the next step is to uh do string pattern is equal to kinda pattern of the word and then um pattern wars map dots put pattern and then new linked list string and also it seems like the it doesn't say if the return value could be in any other or whatever so let's assume yeah i know there is fine okay so actually there are quite some things to clarify like the first one whether there could be some empty words in the input array another thing is if there is uh there are any duplicate words in the input strings and the third thing i can think about is if there could be if the output should be in any other but um yeah so i forgot to add those questions but this question didn't clarify um didn't clarify those assumptions so let's say we made the assumption that output doesn't need to be another and there could be duplicate words but we are going to return duplicate words in our results and also there could be empty strings okay so let's see so we are going to put the pattern and okay so if pattern horse map.contains map.contains map.contains if it doesn't contain the key of pattern then we are going to say pattern words output the pattern new the string otherwise um and you're going to put pattern words map dot get pattern dot add the corresponding word okay and then finally we just need to go through each of them each of the entry in the pattern words map and add into the result so string key and uh say pattern wars lab dot key set so um rit dot add uh pattern words dot get pattern okay and finally we return rt so it's time for us to implement the find pattern function um sure so if um words dot lens that doubts or dot it's okay lens is equal to zero then we just need to return something empty you just return a empty thing um if it is one if word the lens is equal to one then let's return something a special let's say return a comma and then uh we are going to say okay for a in nice equal zero and smaller than word dot lens minus one plus i so um let's see this is string builder uh pattern new string builder okay uh and then finally we need to return pattern here you're gonna say okay pattern dot um append the uh okay word r at i plus one minus word the car at i uh i'll say this one let's define it as div is equal to the neighbor character div you're going to say okay integer dot 2 string diff plus the comma okay so uh we're pretty much co-complete with so uh we're pretty much co-complete with so uh we're pretty much co-complete with this one i remember this is not the final thing uh we always need to test this visual code so let's go through an example let's use the example provided in the input so suppose we have this input and first of all we are going to um generate the pattern words map so the pattern words map at the very beginning is going to be something empty and then um so for the first word we call the find pattern for the word it is abc let's go through the find pattern helper function so the lens of course is now equal to zero now you could one so the diff would be uh the div would be one and one so the div so for um abc find the pattern uh abc it is going to give us uh one comma and one comma so this one the pattern is one comma and the corresponding value is the abc and then let's and this for the next string bcd it had when we called the find pattern it has the same pattern so we are going to put bcd as one value append the appended into the value of key one comma so similarly for ac ef we are going to generate uh two and one and two and one comma okay so we are going to put a c e f here and for x y z it is going to be added into here after calling the pattern and for a z uh we the pattern is going to be uh 25 and then we are going to insert the az here and for the ba um actually yes for the va it's different that's the case that break our fine pattern function because a minus b is uh actually minus one so i would say diff if the diff is smaller than zero then we would say div plus equal to 26 so that would solve the problem 25 for the 25 comma then currently a minus b is minus 1 plus 26 is uh 25 here so we have the ba here and then um it is the it is the it is okay so it is a so a has a pattern which is comma and then we put the a here and the z here okay so i'm trying to see if there if this if branch still is still going to break something let me see if that could happen so suppose we have a something let's say a b c d e f g h i j k l m n so a n then the pattern would be a 13 and a comma so if we have something let's say it is n o p q r s t u e w x y z and a if it is an a then it is minus 13 okay so it should be okay all right so let's give it a shot by running this piece of code okay compile arrow let's see we're going to return pattern.2 string we're going to return pattern.2 string we're going to return pattern.2 string here okay it's accepted uh let's see let's give it submission okay it's accepted all right so it seems like it falls into our assumption so for empty string if there are multiple m string you group them together and if they're duplicate words then we output all the duplicate words and we don't care about the output the other of the output all right so that's it for this uh coding question uh regarding the task test case test cases i think only one test case is not enough so definitely set up some different case test cases to cover different branches so for example the first one i would say is the empty thing or actually we don't need to do special things here because if the if it is empty then we are not going to uh the map the pattern works map is going to empty as well so let's do a submission for it okay so we can save those two lines of the words the two lines of the input two lines three lines of the code and also think about some test cases which can hit this branch um otherwise i think we should be good okay so that's it for this coding question so if you have any uh question about this problem feel free to leave me some comments and also if you feel this a bit helpful please give me a thumb up and i'll see you next time thanks for watching
Group Shifted Strings
group-shifted-strings
We can shift a string by shifting each of its letters to its successive letter. * For example, `"abc "` can be shifted to be `"bcd "`. We can keep shifting the string to form a sequence. * For example, we can keep shifting `"abc "` to form the sequence: `"abc " -> "bcd " -> ... -> "xyz "`. Given an array of strings `strings`, group all `strings[i]` that belong to the same shifting sequence. You may return the answer in **any order**. **Example 1:** **Input:** strings = \["abc","bcd","acef","xyz","az","ba","a","z"\] **Output:** \[\["acef"\],\["a","z"\],\["abc","bcd","xyz"\],\["az","ba"\]\] **Example 2:** **Input:** strings = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strings.length <= 200` * `1 <= strings[i].length <= 50` * `strings[i]` consists of lowercase English letters.
null
Array,Hash Table,String
Medium
49
105
angry birds welcome to my channel it's all great problem constructed minority from creator and energizer traversal loudest offering being constructed by doing so for example this free mode traversal of history thing 30 to poisonous 500 600 you must not explain reversal on route subscribe which is not After detroit sub tweet a violin inorder traversal very first visit electric of the factory daru dandruff pm 385 over this period after the first of all way Thursday look proven in half- first of all way Thursday look proven in half- first of all way Thursday look proven in half- dead liquid are like this point subscribe to the right and left with some specific constructivist like This will Thursday 0 100 is internet all prevalent in which alone has left the rally will look pointer in which will be the root of the subscribe 0 subscribe this Hair disti mode switch board the laptop so and I will go to the rate of sure subscribe solving This World Will Start For Not Ranbir Will End In The Channel Subscribe Always Give The Tree Location Tomorrow Morning Lower Easy Ni0 First And For Solving This Will Call Build A Victim This Will Create A Root Not Using The Free Mode Vaivaswat Manu Screen Award Ki Tree Not also from pre quarter of india on the contrary that these next wali somvanshi godhead lord after delivery to build a laptop battery and allied subjects for left will call login the same method root for daughter of a called that record seat method file hair What We Can Do The Worst Index Positive Same Wild and Will Be Changed From Index The Index Will Find the Length of the Day in more subscribe and subscribe this Video give a to call and similarly I will call for rights of tree Nov 19 2012 Subscribe Simply Screamed Plus One That Know What Will Be The Index These Rights Act 2 Seen Should Distributor Reversal Bill Process Tree Only When Almost All The Life In Node To Live With This Process Decided Only Subscribe And Subscribe A Plus Number Of Note In The Laptop Tree Which Will We Inductive Were What Is The Cost Of The Tree In President Appointed Prof The Index P0 Start Let's Shortcut st0p Thers 400 First Will Get Dec 9 Will Find In The Mid-1960s Subscribe 0 Will Find In The Mid-1960s Subscribe 0 Will Find In The Mid-1960s Subscribe 0 Ki And For Rights Act Will V0 Plus One - 0512 subscribe and subscribe the Channel को subscribe The Amazing - The Video को subscribe The Amazing - The Video को subscribe The Amazing - The Video then subscribe to the Page if you liked The Video then thank you later this using while loop and all the record chipcooler left and right hand half -Adhe let's make this code that antiseptic see the time complexity of dissolution is will vanish you all and were falling victim method were taking delivery of this can be chief and takes time and time for switch of the day is next in case of whose daughter 16 Scooter is like this for this rights to three and four 200 how will optimized and volume in servi the node to know what will oo will just catch this in the map and they will not mean that in order to create a key and map difficult to create A local variable is just for engineers and just kidding noble but for creating local you need to update you all this structure of this record time and passed through our soft the fourth in ICC Twenty20 team not like this which is not i plus It which is not i plus It which is not i plus It is a Inverter of Yes Brother Ko Maaf Special Arrangement Easy Next9 Here Institute of Calculating and Started with a Simple Liked The Video Free Mode of Individual Were Compiled and Submit in Saudi Selection and Time Complexity of this Course Will Be Co Off and Because Now at Getting into Quantum Mechanics and Spirit in Father and Notes and Space Complexities Open Thank You Felt I Solution Please like button and subscribe To My Channel and press the Bell Icon to get notification of the new videos Thanks for watching see you again
Construct Binary Tree from Preorder and Inorder Traversal
construct-binary-tree-from-preorder-and-inorder-traversal
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** preorder = \[-1\], inorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= preorder.length <= 3000` * `inorder.length == preorder.length` * `-3000 <= preorder[i], inorder[i] <= 3000` * `preorder` and `inorder` consist of **unique** values. * Each value of `inorder` also appears in `preorder`. * `preorder` is **guaranteed** to be the preorder traversal of the tree. * `inorder` is **guaranteed** to be the inorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
106
155
what is going on everyone so today we are looking at lead code number 155 it's a question called min stack and so what we have here is we have to design a stack that supports push pop top and retrieving the minimum element in constant time okay so we have a class here min stack and we are going to initialize a stack object and then we're going to have the methods push that pushes the value onto the stack pop that removes from the top of the stack top that gives the top element of the stack and then get min that retrieves the minimum element in the stack okay so let's take a look at this and let's see how we can approach this problem so let's say we have a stack an empty stack and we have the numbers 1 5 minus 6 32 minus 15 3 and we need to create a data structure that every time we remove an element we can always keep track of what is the minimum number in the stack at that certain point but we have to do it in constant time so let's try to look at this without doing it in constant time and then see what we can do to implement a constant time solution so let's say we put in uh we use an array for this stack so this will be our stack okay and we can use just an array to represent a stack and we push in this one and so far our minimum is one and we can just run through this array and get the minimum we can push five and then when we call the minimum we can just run through this array and find the minimum same thing minus 6 32 minus 15 at each point if we ever want to get the minimum we'll have to just iterate over that array and find the minimum the only problem with that is that it is a linear time operation we're not getting constant time so let's think about this how could we do this in constant time okay so one way is we could just keep a minimum so let's say we have one here and we have a variable with min and when we add in min we're gonna set min to one now we add in five does not overwrite that one so our min will still be one we add in minus six here and now our minimum will update to minus six okay let's keep going it's going to then go to 32 here 32 will not change this minimum variable and then we'll get to minus 15 and this is going to update this minimum variable to minus 15. now we do have the running minimum but the only issue is that what if we pop off this 15 right then our uh minimum now is -6 but then our uh minimum now is -6 but then our uh minimum now is -6 but we have to iterate over this entire stack to go find that minus 6 and update it so again we don't get constant time so that's not going to work okay so let's think about this another way okay instead of keeping the minimum in a variable what if we created another stack okay that's a mirror of our current main stack and what we do here is we say okay when we push in let me just go ahead and erase this so i can make it a little bit clearer what we're going to do is when we push in these numbers and we'll go step by step and push these in okay so here i'm going to go ahead and push in this one and i'm going to check is there anything in that stack there's nothing in the stack so i'm also going to in their min stack here i'm going to also go ahead and push in that one okay now we're gonna get to five we're gonna push in five into the stack okay we're over here we're gonna go ahead and push in that five into the stack and we're gonna check what is the last element of the min stack and is it less than what is currently in there so five is not less than one so then we'll just go ahead and keep the one okay now we're going to push in the minus six and we're going to check what is the last element in that min stack it's 1 is 1 less than minus 6 no it's not so we're going to go ahead and push in the minus 6. okay now we're going to go to the next one we're going to go ahead and push in 32 and we're going to check what's smaller this minus 6 or 32 it's minus 6 so we're going to just go ahead and push in another minus 6. we'll move on to the next one we'll go ahead and push in minus 15 and we'll check what's smaller minus 6 or minus 15 it is minus 15 so we'll go ahead and push that into the stack and lastly we're going to go ahead and put in this 3 and 3 is not less than -15 so now we'll and 3 is not less than -15 so now we'll and 3 is not less than -15 so now we'll have minus 15. and now when we go to our pop operation we can just pop off the main stack as we would normally okay so we just go ahead and pop off this three and then we can go ahead and just pop off this minus 15. and at every element of the main stack we have a corresponding respective element in our min stack that gives us the minimum up to that point okay and so now we can pop off at any point and always retain the minimum and get that minimum in constant time okay so let's think about uh time and space complexity well our push and pop are going to be constant so we can say push is going to be o of one time pop is also going to be o of one time okay we have push pop we have top and get min top is also going to be in constant time and so is get min okay the only thing we're doing is we're creating a little extra space with creating this min stack okay so our space complexity is going to be o of two n okay which will abbreviate down to o of n okay so that's the idea let's go ahead and try to code this up okay so we'll jump over here and so here we have our prompt here we have min stack we have our push pop top and get min and what i'm going to do is i'm just going to go ahead and use the javascript es6 class syntax i think it's a little bit cleaner so we'll just do a class min stack we have a constructor okay and so what do we want to create our regular stack so we can say this dot stack and set it to an array and then we want a min stack so we can do this dot min stack and we can also just set that to an array and what this min stack will do is it'll just keep a running minimum of this of whatever's in the stack whatever's respective in the stack okay so we can have a push operation here we'll have a valve and we can just check if this dot stack if it's empty okay um then what we're going to do is we're just going to go ahead and push that value in the stack and the min stack okay if it's not empty then what do we want to do well we want to push the variable or the value into the stack no matter what we don't have to do anything there so we can do this dot stack dot push val but what do we want to do with the min stack well what we want to do is we want to find what is the last element in the min stack and then compare it to the value and push in the minimum value okay so we can do this dot min stack dot push and then we can use the math.min and then we can use the math.min and then we can use the math.min operator okay and then we want to get the last element in our min stack and compare it to the value so we can do this dot min stack dot length -1 that's going to be our dot length -1 that's going to be our dot length -1 that's going to be our last value and just compare that to the input value okay so that's all we have to do for push okay now we want to do pop okay and so what do we want to do here we want to say if the stack is empty we'll just return null so if this dot stack we can just use a not operator there and so if it's if the stack is empty we can just return null else what do we want to do well we just want to push we just want to pop off uh pop off the last value on the stack and the min stack so we can do this dot min stack dot pop that'll just go nowhere it'll just be collected by the garbage collector and then we want to return this dot stack dot pop okay to get the top of the stack all we want to do is return the last element in the stack so we can just do a return this dot stack dot length minus one and then we just want to do something very similar for get min we just want to return the last element in the min stack so we can do get min and then just return this dot min stack dot length minus one okay and that's it that's all we have to do and i think it's just important to remember that you just want to create a mirror stack name it min stack or name it min whatever's easier to remember and just understand that as you push into the stack you want to push into the min stack the minimum value up to that point okay and then you can just push and pop you can just pop off uh min and off the regular stack as you would a normal stack okay let's go ahead and run that okay and we have success okay so that is lead code number 155 min stack i hope you enjoyed it and i will see you on the next one
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
203
hey everybody this is larry this is day 12 of the uh november nico day challenge forgot what month it was uh hit the like button in the subscribe button join me on discord let me know what you think about today's prom seems like it's easy only because they tell me i don't really like classifying them but all right let's give it a hit i will link let's return we won't know that has returned the new head okay um just we took removing notes uh okay they only did the one but the one thing i was going to say is be careful about an empty linked list um but that is one test cases so unless you forgot about the test cases should be okay the way that i always think about it uh or at least maybe more recently i don't know about always but is to have a sentinel right of a something that begins like before the head so that um so yeah uh i guess negative one and then x or something like that right so then now you can kind of and the way that i always talk about linked lists and even trees depending on the problem is draw it out um time you have pointers and when i say pointers every i mean i know i'm hand wavy a little bit for people who actually know um the semantics to be direct i'm only using a little bit on one or more english terms so please forgive me if i'm you know it's me trying to uh explain in a way that is more understandable but i know that i know how these things work per se but anyway but yeah but try drawing roughly speaking every wearable um is um points to something it points to a reference in data so every time you move um every time you move something or set something to something else um you should just draw it out on a piece of paper or something like that so that you know you can kind of see how it moves and make sure that every step of the way it is what you think it is right of course you don't need to do this on paper you can do this you know programming it or whatever but these are the things that i would say to get started um but this is a easy one though so we should be able okay so we just start with current as you go to sentinel uh you know maybe it's like a sentinel head and then while current is not none uh current is your current.next of uh current is your current.next of uh current is your current.next of course this is just essentially like a for loop of just i always write them together because otherwise i don't always because i still forget it from time to time but i try to write it together so that uh it saves me an infinite loop because i'll forget it later um so then now okay so if current that row uh so this is something that we have to think about right is so the two things you can do one is either you remove current if current that routes you go to route or and keep track of the previous link or you could look at the next and if the next is you go to route then you get next you go to next or something like that right um how do i want to think about it so the case stat is a little bit tricky or just to make sure you think about um though it is also an example 3 is that you might repeat removing something so i'm going to do this with respect to keep track of um i should say previous is the go to sentinel and then current as you go to previous.next previous.next previous.next and then we do this loop if this is the case then previous.next is equal to current.next previous.next is equal to current.next previous.next is equal to current.next because now we get rid of the current.next um and then kern current.next um and then kern current.next um and then kern um yeah and then i think that's all we have to do um maybe and then we just have to return the sentinel which is the fake thing that points to before the head and then the next of that maybe this should be okay let's see now that i'm missing like off by one or something okay so i remove everything which is a little bit sad but um why do i remove everything is this set up correctly i never know i think this is right though but um okay well this part is right well maybe i have some weird typo but okay let's say i remove this for debugging uh and then see if that really that should just return the initial so um yeah okay uh okay so this is what we expect um sometimes you want things to kind of make sure that it is what you expect and not necessarily um you know okay so welcome is that none why is this wrong basically the previous is next is equal to the next one so you skip this current node and then we go to the next one right did i mess something up but why does this true oh i don't update previous.next whoops so okay so in this case i forgot to update it uh man i'm really sloppy today but um yeah so now you know you we think about it the previous one next we skipped this one and that's okay but in that case we do not move previous right so we only move previous if um i think we don't even move the current do we well i guess we move to current um i guess we always move to current and then else is previous.next is equal to is previous.next is equal to is previous.next is equal to uh yeah uh previous is equal to previous.next previous.next previous.next to move this forward yeah maybe i mean this is where i need to take my own advice and maybe draw it out but it seems okay let's actually run a few more test cases um yeah a little bit sloppy yeah i don't know i guess they're really so giving up the first element get rid of the last element and i think that's probably it because the other ones the other test cases seems pretty representative of the edge cases that i've come up with so this is good this i'm happy about this uh yeah let's give it a spin hopefully i didn't i don't get a wrong answer uh like last time cool uh yeah i mean i don't know what else to say this is so yeah so just be careful apparently uh but also just make sure you know because right here for example what i said the three pointers kind of uh one is appointed to a node the other one is the previous point and the current pointer and make sure that you know they move one at a time for both cases which is this one if they you go to value what the hell did that happen uh then you go to value you the previous next um you know you skip the current one and then you move forward otherwise the previous goes to the next one which is the current node and then you move the current so yeah so make sure you roll photo cases and just think about it through um of course this is gonna be linear time and constant space we only allocate memory for this node and a couple of pointers and of course this is linear time because we just go for the loop right um cool that's all i have for today uh let me know what you think um yeah these kind of problems i would say comes up uh maybe not as much anymore i don't maybe it's just not the matter or invoke it used to come up in a lot of programming interviews but these days i think people just go for something a little bit different i could be wrong though uh i just haven't seen it or my peers haven't asked it as much but i use that just recently um yeah i don't know anyway that's all i have though stay good stay healthy to good mental health i'll see you later bye
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
1,942
hey everybody this is larry this makeover q2 multiply weekly contest 57 the number of smallers on occupied chair so this one has two uh things you have to consider but otherwise it's what i call a bookkeeping prompt and so yeah you should hit the like button hit the subscribe button join me on discord and let me know what you think about this prom the contest and so forth um if you're interested in talking about the contest right after the contest might disclose the place to be anyway so yeah so this one's bookkeeping and what is bookkeeping is it's not an algorithm it's just basically keeping track of everything and where they are at every time and then make sure everyone gets updated in a good way so in this case the two parts of that one is for keeping the other is kind of making sure that they're out you're able to process the times away in order right in the arrival and leaving and so forth so that's basically um it's not quite sweep line but that's how i thought about it and that's how i think about these is a defense sweep out type thing um i keep a sword in this you can actually use a heap in this instead to be honest but i this is easier to type sometimes so that's how i think about it um and yeah so now of this sorted list will contain every available chair um so here we add everything every available chair from zero to n or n minus one sorry and then here we have the events part where we basically want to sort by whether the index person is going to be um sitting down or getting up so that's basically here we put it in this sorted event so that we could keep process of it this negative one is actually um intentional in that we wanted to process the leaving events before the starting events on the tiebreaker because well because that's what they tell you um like here it tells you that when a friend leaves the chair becomes unoccupied at the moment right so yeah so that's why we did it that way and then the rest is just keeping track we keep track of what see a person used if we get up we add that seed back to the available seeds as well as maybe available seeds maybe that's a better variable but of course these are my contest code so it's a little bit yucky not gonna lie um yeah so then otherwise take the smallest available seat and as i said before you can actually use the heat because you're only getting the mint heap every time or the minimum element of the heat every time so then you remove it at the right end or you remove it from the available seats and also if the index is the target friend you return what c they took that's pretty much it um this is going to be n log n because this sorting is n again um yeah and of course here for youtube van it's also going to take logan operation each so everything is pretty analog any so let's just call it and again in terms of space this is going to be linear space um this is also gonna be linear space so oh and this is also the near space so everything is linear space um that's all i have for this one watch me you can watch myself and live during the contest next that lag cost me like a 20 second summit okay foreign okay hmm okay i'm leaving time okay so you leave first okay um is okay what am i doing i'm a um bit slow today i guess but as long as we're waiting okay hmm um okay that's not right c now what is that two why is that too and oh man i am done today why did i take the biggest seat instead of the ladder okay hopefully that's right okay a little bit slow today but um uh yeah thanks for watching uh hit the like button to subscribe and join me on discord let me know what you think about this problem uh yeah i hope you do well and stay good stay cool i will see you later bye
The Number of the Smallest Unoccupied Chair
primary-department-for-each-employee
There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**. * For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a **0-indexed** 2D integer array `times` where `times[i] = [arrivali, leavingi]`, indicating the arrival and leaving times of the `ith` friend respectively, and an integer `targetFriend`. All arrival times are **distinct**. Return _the **chair number** that the friend numbered_ `targetFriend` _will sit on_. **Example 1:** **Input:** times = \[\[1,4\],\[2,3\],\[4,6\]\], targetFriend = 1 **Output:** 1 **Explanation:** - Friend 0 arrives at time 1 and sits on chair 0. - Friend 1 arrives at time 2 and sits on chair 1. - Friend 1 leaves at time 3 and chair 1 becomes empty. - Friend 0 leaves at time 4 and chair 0 becomes empty. - Friend 2 arrives at time 4 and sits on chair 0. Since friend 1 sat on chair 1, we return 1. **Example 2:** **Input:** times = \[\[3,10\],\[1,5\],\[2,6\]\], targetFriend = 0 **Output:** 2 **Explanation:** - Friend 1 arrives at time 1 and sits on chair 0. - Friend 2 arrives at time 2 and sits on chair 1. - Friend 0 arrives at time 3 and sits on chair 2. - Friend 1 leaves at time 5 and chair 0 becomes empty. - Friend 2 leaves at time 6 and chair 1 becomes empty. - Friend 0 leaves at time 10 and chair 2 becomes empty. Since friend 0 sat on chair 2, we return 2. **Constraints:** * `n == times.length` * `2 <= n <= 104` * `times[i].length == 2` * `1 <= arrivali < leavingi <= 105` * `0 <= targetFriend <= n - 1` * Each `arrivali` time is **distinct**.
null
Database
Easy
null
113
the old path sum2 problem which is the most important depth first search problem you're likely to encounter every how everybody has to do the path sum to problem it's absolutely the greatest bestest problem you've ever heard of nobody could live without doing the path sum two problem just one question what is the path sub two problem okay so it says given the root of a binary tree at an integer target sub return all root to leaf paths where each path sum equals target sum a leaf is a node with no children they give an example here the target sum is 22 which could be formed by 5 plus 4 plus 11 plus 2 or 5 plus 8 plus 4 plus 5. so that's what we need to return and here they give the example of target sum equals 5. we see that 1 plus 2 doesn't equal 5 nor does one plus three so you return nothing likewise you're given a tree which has nodes of one and two and the target sum is zero so no combination of one plus two or two plus one can equal zero okay so how do we want to play this well it is a depth first search and what we're going to do is go down the binary tree until we hit a leaf which is a node without any subnodes or child nodes as it were and um we're going to check the sum up until that point and if it equals our target sum we're cool then we just return we just push back onto our main return vector the current vector that we had accumulated so far as we were going down the tree so let's do that okay so first a little saturday check if the root is null then return nothing consider that this language is legal in c plus you don't need to create a return vector that just wastes memory if you don't need it otherwise we're going to create whoops we're going to create our return vector which is a vector of uh integer vectors we're going to call it my return and then we're going to eventually return my return after we fill it but in order to fill it we're going to have to populate it in other words yes we're going to have to populate my return so first we're sending the route then we're sending my return then we're sending a blank current vector that's each of these and at the moment it's blank uh what else do we need the target sum we need the current uh current sum is zero and i think that's it for now let's see if we could do something with that so let's create our in order traversal so this is the function we were talking about which takes a tree node root so since we're not modifying the root we don't need to put an ad percent here and that's fine then um then we're throwing in the my return which we're going to pass by here we do by reference later we're also going to pass in a vector of integers by value called current vector and we also want to pass in the target sum um and likewise we could pass in the current sum okay now i'm gonna see if we ever need to what is it um if we need to change those uh from something that's not const we'll see that in two seconds so the first thing is our root condition here well first if whatever we're looking at is null then we could return so there's nothing to do in this case now um now if we got somewhere and now we're going to do um current sum plus equals what is this current sum plus equals root val and what else we want we also want to insert the current sum in our current vector so current vector dot push back and we want um the root dot val in there okay so um now we're going to do our little checks here so okay if uh root dot right null and root um dot left equals null that means we hit a um oh what is it a leaf node so if that's the case then if uh what is it if um if target sum sorry if um if current sum equals target sum then that means we could add to our my return vector and we're going to push back the current vector and then we're just going to return so that's what we do if we found a leaf node otherwise um oh yeah the values could be negative so we're not going to return if we go overboard so that's fine we're just going to continue iterating down the tree um okay so if we hit a so okay if root dot right not equal uh what is it not equal um what is it not equal null then uh what do we want to send in order and we're going to just throw in root dot write how do we write this and then we're going to throw in my return and we're going to throw in current vector which is getting stuff pushed back as we iterate and uh target sum which doesn't change and uh what is it current sum okay now obviously current sum we could pass it by value over here because it's going to be modified and we definitely don't want it by reference in there now we're going to do the same thing here okay so if root.left not equal null then we're going to throw this in as well and uh i think that's it actually so this is not really an order actually we had to so actually i think this is probably something like pre-order so something like pre-order so something like pre-order so don't take my word for it uh or what is it post order or something like that yeah or post order traversal the reason is we're doing our current node first and then we're doing the others but actually it doesn't even really make a difference as long as you go somewhere let's just run this see what happens and it looks like it worked now let's submit okay it worked now the only thing you need to remember is that it probably wasn't added order over here and uh that looks like it works thanks a lot folks have a good day
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
1,347
hello hi guys good morning welcome back to a new video in this we'll see the problem minimum number of steps to make two strings anagram the problem is itself already like this it has been asked by do Dash and Bloomberg six times in the last 6 months and has been asked BYL and quadrix and Twitter so let's see what the problem says it says that we are given two strings which are s andt and we have to find the minimum number of steps again have to find minimum number of steps to make t an nagram of s now basically an anagram of a string is that contains the same character with a different or the same order which means that ultimately both the strings s and t should have same characters so uh what let's say if you have a string s if you have a string T then you can for sure see that uh I just want to want them to have the same characters right ultimately in the final end so what I can do is I can simply remove the ones which are already same so in this these two are already same so I'll just remove them and ultimately I'll be left with B here and a here so for sure I can just modify any one of them so right now I'm just thinking I'll modify my string s only so I'll modify my string s this B character to a and then you'll see I'll become it will become a and a so answer is one which means you just have one operation and again uh either you modify s or you modify T any one of them you modify you'll get the answer so right now we are thinking of okay we'll modify only s to get the answer and the same way let's say lead code we had practice we had firstly we cut out the same corrects okay e cutout t cutout c cutout then I can very easily say okay this L I can transform to P this E I can transform to R this o I can transform to a this D I can transform to I and this E I can transform to C so you saw that I transformed only s and thus I would need only five op operations and the same way for anagram and m n g a r I'll cut out every of those characters as you can see I cut out every of the character and th my I don't need any of the operations so you saw that firstly what we did was we cut out the characters which were actually same and then from the remaining s string or basically either you can say from the remaining T string uh we whatsoever was remaining we just got that and got that answer so ultimately what we saw was that we will have a string yes now to cut out and to not cut out it's just that okay we are cut cutting out the elements which are also in string T So to maintain what all elements were there we can take a frequency or basically you can use as an unordered map also which is a hash map and you also use a vector although I recommend that unordered map actually both have the same time uh but as you know that we are have only 26 characters so you can make a Vector of uh Vector of let's say int of size let's say frequency is 26 rather than unordered map of characters of int frequency so rather than this I'll recommend this although on paper both have the same time complexity but still it is much more beneficial to actually have it like this because it takes Les lesser space itself now what we did was we just simp had a frequency so as to maintain what all elements were there in s and then I'll subtract out the frequency what all was there in t so that whatsoever will remain in s I'll get that as answer let's try run it so L I increase the frequency okay one E I increase the frequency it's three but how three because e will be increased here also and here also okay the frequency of e is three in string s okay frequency of T it is actually a one okay frequency of C is actually a one frequency of O actually a one frequency of d actually one so now I have grabbed the frequencies of string s now what I'll do is I'll subtract out the frequency of string T by why I am doing that because you remembered that whatsoever elements were actually common we are actually cutting them out for example e was here so I know okay one E I can also find here so ultimately in string S I would be only wanting to grab two e so what elements are common I need to cut out so that cutting out is just subtracting the frequency so okay uh I'll just subtract the frequency of p as you saw the frequency of P here was actually a zero so it will become a minus one frequency of R will become a minus one frequency of a will become a minus one frequency of C will become a minus one how minus one because you'll see frequency of C is actually here two here it itself was 1 so 1 - 2 is here it itself was 1 so 1 - 2 is here it itself was 1 so 1 - 2 is actually a minus one okay great frequency of T is actually becoming a zero but how zero because frequency of T was actually one here then T again came in so it 0 frequency of I is again A minus one frequency of e is again a two but how to because frequency of e here is three one of the E got subtracted I got a frequency of e as2 so that's how I can simply solve it now so you saw that ultimately as it's the same frequency array so ultimately I will have frequency of L as one frequency of e as 2 because of this being decreased right as you saw here frequency of t as zero because of is being decreased frequency of C as minus one frequency of O as 1 frequency of d as 1 frequency of P asus1 frequency of R asus1 frequency of a as minus one frequency of C asus1 frequency of I is minus1 and frequency of e as 2 so this is a frequency which I will have entirely in my entire array now what I need to do is if you remembered one thing if you remember this one thing then we were seeing that c let's say here we saw that V cut out we cut out e and e we cut out T and T we cut out C and C so we had l e o d and e so if you look back l e o d and um L E O D and L e l e o d yeah because e you saw that uh e we had a cutout so yeah l e o d so l e o d were actually the ones which actually impacting my string s so l e and e again it is two times as you remember it is two times one e was this and O and D so we will only be needing to modify these characters which are actually positives so that's what I will do I'll just take the ones which having the positive frequencies what positive frequency represent positive frequency represents that they are the remaining characters of string s which I can now modify them and say okay I can modify my L to a p so that I can transform that to a string T so this is what I mean by modifying my string s characters so s is nothing but okay it's one it's two it's one you see 1 2 one and that's why I get the answer as five so now you know the code is pretty simple we'll use an unordered map again I said that in an interview you can just tell the interviewer that okay we can also use a vector of int of characters because it's a much more efficient way to actually have a data structure but uh both have the same time complexity then I will take the I'll go on and iterate on both the strings because both the strings are of same size which is n so that is representing my n size I'll go on and say frequency of that s of I'll increase frequency of T of I'll decrease now ultimately I go on to my frequency Vector whatsoever is positive add its frequency in my answer as you saw whatsoever you saw whatever was whatsoever was positive I'm adding that only in my answer because I know that I can transform those characters to actually my string P sorry string T now ultimately return the answer by this your time is over and space is over and that's how you simply solve it I hope bye-bye
Minimum Number of Steps to Make Two Strings Anagram
distance-to-a-cycle-in-undirected-graph
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Example 1:** **Input:** s = "bab ", t = "aba " **Output:** 1 **Explanation:** Replace the first 'a' in t with b, t = "bba " which is anagram of s. **Example 2:** **Input:** s = "leetcode ", t = "practice " **Output:** 5 **Explanation:** Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. **Example 3:** **Input:** s = "anagram ", t = "mangaar " **Output:** 0 **Explanation:** "anagram " and "mangaar " are anagrams. **Constraints:** * `1 <= s.length <= 5 * 104` * `s.length == t.length` * `s` and `t` consist of lowercase English letters only.
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the node that was seen twice and all the nodes that we visited in between. Now that we know which nodes are part of the cycle, how can we find the distances? We can run a multi-source BFS starting from the nodes in the cycle and expanding outward.
Depth-First Search,Breadth-First Search,Union Find,Graph
Hard
2218