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
500
hello everyone so let us solve one the problem from lead code the problem name is what you can say uh yeah keyboard rows so let us go the problem statement first you are given an array of strings words return the words that can be typed using the letters of the alphabets on only one row of the american keyboard like given in the image below so the american keyboard is such that the first row consists of all the characters that is given at the string the second row consists of all the characters that is giving you in the string as well the third row consists of all the characters that is giving you as a string so this is actually the whole problem that you have to tell what all words that are given to you as you can see there are different words that are given to you as input what all words can you type using only a single row from this alphabetical like this whole keyboard that is created you can pause of this video try to think of your own how you can solve this problem but there can be multiple ways but what you can see here is the two things which actually which i directly observe is that if i use these as a string these are small letters but there are some capital letters also in this whole string so keep track of those base conditions so it which means that before checking them out i have to somehow use all the lower cases like i have to standardize it the second thing is moving down to the constraints the controls are very small so you can use the most brute force way nothing more complicated fine so the most brute force way which i thought of while solving this problem was okay let us take every character or sorry not every word in this whole array and try to build that word only the characters present you in a single row what i mean by this is let us take the first like word and what you'll do is like taking the first word can you build the first word using only the characters of the first row if you can then it is very good like push that particular word in sub answer array of vector that it is good to go else try to build that word using only the characters of second row or try to build that word using all the characters of the third row and if it is like if it is not possible using like building that using all the characters of a single row then it is false like you cannot do that is the overall idea nothing more complicated nothing more difficult you can directly move down to the actual solution to the code part it will become more creative while we'll going through the solution so let us open that sign so because the constraints are very small i've used the most brute force way nothing more complicated so i have made a map you can also name it row whatever you like so this actually stores out all the characters given a particular row that is given to you now you have to print out a answer what like answer vector that is only consisting of strings now this is n now what you actually do is that using a for loop iterate over every word that uh that i'm doing here that is this n for every word i have to check that whether this word can be built only the characters present in a particular row so i have to iterate over all the rows actually one by one that's what i'm doing one by one using this j for loop because there are three rows now let us take one row the first row and given the first word let us take that can i make that how can i do that there can also multiple ways you can use maps but because the constraints are very small i can directly just use it using a folder okay so what i've done here is that this found is true actually true means that if i somehow find out a negligence that i cannot make that then i will make it false initially you can make it true which means that i know that i can be i can form this word using this particular characters of all this row fine so what i'll do is that i use a for loop what i'll do is that i have a word okay what i just have to check that whether every character of this word is present in the row letters i have okay so what i'll do is i will take every character of this word and check that whether it is present in the row characters i have now i can directly just use a for loop to pres check that whether it is present in the string or not i can just use a one more for loop but because it is there a lot of for loops i just write out a function actually here that is just checking out whether the word i have is present into the particular string that is given to us also what i've already told you that i have to match a particular word because the word can be capital or small so before that convert it to small only because the map and string that i have are all small so that is where two lower is used to convert the i like ks scatter and that geared character is checked that whether it is present into a particular string that is a particular row if this is not present that is exclamation if it is not present which means that i mark it as false that in this particular row i cannot make that because this particular word is not present in this particular row fine if it's checked out to be true if means that i can form out this word using all the characters of this particular row i will not mark it as false and the end i will just like this found will not change to false it will be still true if it is true i will push back that particular word into this answer vector and just break out this point that yes i can find it out that is the oral logic and in the end just print out the answer this check function is just checking that whether this particular word this particular character sorry is present into the string or not i'm just using a for loop to just iterate over the string and just brute force checking that whether this particular character is present into the string or not printing that true or false that is the overall idea for this problem nothing more complicated i hope you understand that logic as well as the code for this problem if you still have a doubt you can mention down thank you for watching this video till this point i will see you next time recording and bye
Keyboard Row
keyboard-row
Given an array of strings `words`, return _the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below_. In the **American keyboard**: * the first row consists of the characters `"qwertyuiop "`, * the second row consists of the characters `"asdfghjkl "`, and * the third row consists of the characters `"zxcvbnm "`. **Example 1:** **Input:** words = \[ "Hello ", "Alaska ", "Dad ", "Peace "\] **Output:** \[ "Alaska ", "Dad "\] **Example 2:** **Input:** words = \[ "omk "\] **Output:** \[\] **Example 3:** **Input:** words = \[ "adsdf ", "sfd "\] **Output:** \[ "adsdf ", "sfd "\] **Constraints:** * `1 <= words.length <= 20` * `1 <= words[i].length <= 100` * `words[i]` consists of English letters (both lowercase and uppercase).
null
Array,Hash Table,String
Easy
null
107
you know they're today's liquid in challenge process called binary tree love order traversal - so we have a love order traversal - so we have a love order traversal - so we have a binary tree and we want to return the botton upper level order traversal of its newest values since we're looking at the level order traversal it's very not sure to think about using BFS you can solve this with DFS but it's gonna be more complicated than it's necessary so we gotta solve this by a PFF search basically we're gonna start with a first level the level is only the root node there and from there we got a in the next step we're gonna visit all the node in the next level knowing in 20 and collect those nodes value for that level and may be forced out onto some kind of container then we're going to visit the third level 15 and 7 and put those up on the levels notes value onto the container so since that we're starting with the root and doing this level by level Traverse it's gonna be top down order but the question is asking for the important but enough love order so we can just return the reverse of what we collected on a long way or we could use something like a linked list so that we can have we can push these things onto the front yeah so that's pretty much it's just gonna play it sits level door Traverse it's very natural to use BFS I don't really see any points off for using DFS on this it's just making a question unnecessarily complicated so let's put the BFS solution so first thing first the handle educates if not rude returnees returning it entha list otherwise we would definitely have something we can work with so the first level it's gonna be a simple queue it was just the rule node on it and also we initialize a container to hold the level nodes values it's gonna be attacked so you can think about it as linked lists that we so that we can add things add levels to the left without necessary to copy everything so it will be more efficient so in the first level is just gonna be happy routes value so that's the initiator for these two things and then we're gonna just do a level by level PFS search while we still have a valid level meaning we have a level that has some valid note that means we can keep Traverse we use a simple list to hold the lowest values in the level of course India and that we would just want to push this level on to the order so we're going to looping over all the nodes inside this level so this follow-up is just making sure so this follow-up is just making sure so this follow-up is just making sure that we only pop the notes from the cards level and for every note that we're popping out we check the left and right chopper child note we are doing this in the left/right order doing this in the left/right order doing this in the left/right order because this question is asking left to right if the child is a null pointer we continue otherwise we would do two thing wrong is one thing is to push this child note onto the back of the queue so that we remember to visit it in the next level the other thing is to put the child's value onto the level here so if the current level is actually the leaf level that means none of the nodes on this current level actually have a child down then this level thing is going to be empty so to avoid pushing this empty list onto the order we just do a simple test in here so in your hands we just return this I think it will work yeah so this is the BFS top-down a BFS yeah so this is the BFS top-down a BFS yeah so this is the BFS top-down a BFS search whether we're using a list so that we can push the levels on to the in the reverse order so that's not the tallest faces both linear with respect to the total name of nodes inside the tree so linear entire space so that's this question today pretty simple
Binary Tree Level Order Traversal II
binary-tree-level-order-traversal-ii
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[15,7\],\[9,20\],\[3\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
102,637
265
hey everybody this is Larry this is me trying to do the weekly premium question I don't know why it moves for week three hit the like button hit the Subscribe and join me on Discord let me know what you think about today's problem or this week's plan I'm still in Athens very tired walks so much uh yeah that's all I have for Athens waiting for this spring to load so yeah all right it says how I perform 265 paint house too so there's a row of end houses each house can be paint with one of the K colors excuse me the cost of any charge of a certain color is different you have to paint all the houses such that no two or Jason house have the same color because of painting each house of a certain color is given okay M times K oh God I mean I was gonna say if uh if the cost is constant per color then we would basically be greedy and Alternate right there's one or two ways to alternate but because the cost is wearable per house it's going to be dynamic programming um yeah basically the state is going to be uh let's say the current house and the last color that was painted and that pretty much it right because you only need to do that right so okay because basically as long as the current house is not the same as the last house uh to color then it really doesn't matter what it is right so yeah so basically the way that we reconstruct is you know maybe some naming the function is always bad for me so yeah and we want the suffix of the houses uh so we've got we have an index that represent the suffix of the house houses and then the last color right so maybe last color let's see or something right and then basically if indexes you go to n then we painted all the house and we're good so it causes it costs zero otherwise uh yeah then we basically just do a loop of all the colors so for C in wait maybe I did this one wrong that's why hang on no that one is right but C is equal to label across of zero uh so yeah four range in range of C uh then if C is not equal to last C then we can paint it this color otherwise you have to use another color right that's basically the idea about this is and in that sense it's kind of proof for us e um and you'll be right because that's commonly what happens a lot with uh dynamic programming right it's just a way to notice that your Brute Force has overlapping sub problems uh meaning that you're brute forcing in a way such that uh we want we are able to we use results that we have calculated another time right so uh yeah so we're going to get min whoops oh in this case then yeah okay no that's still fine but now the best is going to be some Infinity value so I always use 10 to 20. it actually overflows long so definitely depending the language you know do your best thing but I want to minimize best and then get min of index plus one because we don't paint it this color right and that's pretty much it to be honest uh zero and negative one say it doesn't really matter um of course this is going to time out because uh uh and also have the wrong answer because I forget to put in the cost of the color uh yes of course uh index and C right but uh yeah so that's basically it um of course we have to do the memorization part uh yeah basically it is noticing that index is going to go from zero to n and last C is a color so it's gonna be zero to C and so the number of inputs is O of n times C you know hopefully that part makes sense and each input takes o of C time so total time is all of n times c times C which is NC squared NC Square um I was wondering why that sounds familiar and I was like Oh e is equal to m c squared in a light Mass ratio thing or not ratio of it uh equivalence but uh yeah so that's basically the yeah of course total space in this case is O of n times C still so yeah uh man I'm so tired uh yeah I gotta pack right after this uh I'm leaving tomorrow morning but it's like a very relatively early flight so I have to kind of uh I like to pack before um before going to bed otherwise you know it gets chaotic when you try to pack in the morning in those situations for me anyway uh yeah uh so yeah let's just try to cash it because this need some caching right so what were we doing here is n times C so yeah so we want uh hmm time C4 right and cash is you go to none times so yeah so it has cash of index and last C and of course that's is not equal to negative one which is really awkward to do maybe that maybe I should do this in run away but I feel like that's still represents like in teaching uh I do get question as to why I do it the way that I do I think it just it's a little bit funnier for beginner to kind of figure it out and also um it's better for interviews to be honest because you get used to using decorators like cash and stuff like this um and then you don't even know how nothing you might build but some people do not uh remember how to like analyze it and stuff like that so at the end of the day the two you know you're here to demonstrate your abilities uh for interviews I mean anyway for competitive stuff do whatever you want as long as it works if you want to demonstrate your knowledge then you know and this is needed anyway uh I am passing out so that's all I have for today let me know what you think stay good stay healthy to go mental health I'll see you later and take care bye
Paint House II
paint-house-ii
There are a row of `n` houses, each house can be painted with one of the `k` colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an `n x k` cost matrix costs. * For example, `costs[0][0]` is the cost of painting house `0` with color `0`; `costs[1][2]` is the cost of painting house `1` with color `2`, and so on... Return _the minimum cost to paint all houses_. **Example 1:** **Input:** costs = \[\[1,5,3\],\[2,9,4\]\] **Output:** 5 **Explanation:** Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. **Example 2:** **Input:** costs = \[\[1,3\],\[2,4\]\] **Output:** 5 **Constraints:** * `costs.length == n` * `costs[i].length == k` * `1 <= n <= 100` * `2 <= k <= 20` * `1 <= costs[i][j] <= 20` **Follow up:** Could you solve it in `O(nk)` runtime?
null
Array,Dynamic Programming
Hard
238,239,256,276
783
hi everyone so let's do the problem for today which is a minimum distance between BSD nodes uh to be honest this is supposed to be the minimum difference in the BSD node because I think this title may not be correct so given the root of a binary search we return the minimum difference between the values of any two different nodes in the tree so here we're given this tree and we're supposed to find the minimum difference uh between two nodes within the tree so the best way to do that is by using an inorder traversal and let's see how we can do that so here we have our tree and let's identify what the input and output for the problem is so the input to this problem is going to be the root node which is four two six one three this is the tree that we just saw and our output is going to be one the reason why it is one is because the minimum difference that we can find is 2 minus one uh we'll see that how we find that out in a second so let's identify what the constraints are to the problem so the constraints are the number of nodes in the tree can only be between either from between 2 and 100 so at minimum it can have two nodes and that maximum can have 100 nodes and the node value cannot go over 10 to the five so those are the constraints to our problem uh how we would go about doing this is let's first understand the tree so we have four uh as our root node and then we have two as our left node six as our right node and one and then three as the children for the node two so initially we will like initialize uh a minimum which is going to be float uh infinity we'll initialize an Infinity a minimum variable as an infinity and we'll also have a previous variable which is going to be negative Infinity and um so we now will have we'll also use like node.value which is uh the current like node.value which is uh the current like node.value which is uh the current value that we as we Traverse down the tree and then another minimum um so this particular minimum is going to be the minimum that we just saw over here so when we Traverse down um so the approach that we're going to do the approach that we're going to take for this problem is going to be and in order traversal so as we do an in order to pursue when we reach to the leaf node what we're going to do is we're going to find the minimum uh at every single node as we do the inorder traversal so we for that we need to set the minimum to be initially infinity and then we also have to have a previous value that we set to be negative infinity and the algorithm the core algorithm to calculate the minimum is going to be as follows so the minimum is going to be equal to the minimum of the minimum comma the node.node.value the current node that node.node.value the current node that node.node.value the current node that we're traversing minus the previous value so this is the actual logic behind finding the minimum uh difference between two nodes in the BSD so our node.value so let me explain as we go node.value so let me explain as we go node.value so let me explain as we go down the tree on how this is actually done so our node.value at the very done so our node.value at the very done so our node.value at the very beginning is going to be one as we do it in order to reversal down the tree when we reach the leaf node our node.value at we reach the leaf node our node.value at we reach the leaf node our node.value at the very beginning is going to be one so initially we have our minimum to be set to be float infinity and so we're going to find the minimum between infinity and node.value which is one minus the node.value which is one minus the node.value which is one minus the previous which we set as negative Infinity so 1 minus of negative Infinity is going to give us Infinity so this is going to give us infinitely so we're finding the minimum between infinity and infinity which is infinity and then as we go back up the tree by one uh we are going back to the node two so our current node.value is node two so our current node.value is node two so our current node.value is going to be 2 and our previous uh we're also going to reset the previous to the minimum that we found which is actually not the minimum the node value that we had previously which is one so our previous value is going to be run now and the node.value at the run now and the node.value at the run now and the node.value at the current position is going to be 2 because we are at this point And now when we calculate the minimum our minimum is going to be the minimum between the minimum that we found so far which is infinity and so minimum between Infinity comma the no dot value which is 2 minus one because the previous value is one so minimum between infinity and one is going to be one so our current minimum is going to be one now our next minimum is going to be the minimum between the minimum that we have found so far which is 1 comma no dot value so now our node.value is going to be 3 because our node.value is going to be 3 because our node.value is going to be 3 because our in order traversal is going to be left traversal and then our current root and then we're going to do the right reversal so our next minimum is going to be 3 minus our previous value uh became our current value so our current node.val value is value so our current node.val value is value so our current node.val value is three now and then the previous value is going to be two so three minus two is going to be one so minimum between one and one is one so our current minimum is still going to stay at one so far we have found the minimum uh the minimum most minimum between these three nodes and we know that it is one so we have finished the left subtree so the same process that we did just now we were going to do it on the right node as well and then um and then move the most minimum to the root then we would bring that back up to the root so to describe this I've sort of written this like pseudo code to explain how it is so we initially we will have our base case and then we'll have a recursive case the base case is when we hit the leaf node we're just going to return our call back and then on the recursive uh on the recursive calls what we're going to do is I'm going to Traverse to the left we're also going to Traverse the lower right and in between we're going to calculate the minimum and then set the previous node to the new minimum so the code for that problem is going to be as follows so initially we set the minimum to be infinity and previous to be negative Infinity we start by or we also have to bring in the scope of the minimum in the previous into the helper function we can also do this by just you know declaring this inside a Constructor but I just decided to go with this just to save time now our base case is going to be if node is none then we'll just return back and our we're going to call we're going to recurse to the left by calling the helper function on node.left and then we helper function on node.left and then we helper function on node.left and then we calculate the minimum by saying minimum of minimum comma no dot value minus previous now previous is going to be reset to the current node.value so this reset to the current node.value so this reset to the current node.value so this is what we saw here the previous at the very beginning is going to be upload negative infinity and then every time so this is going to be our first previous and then our current and our current value is two our previous is going to be one when our current value is uh three then our previous is going to be two so that is how this logic works and then after that we're going to request to the right and then towards the end we would return the minimum uh we're going to call the helper function uh and Trigger it with the root node and then the whole process starts from the top which is the very root node and then uh once the recursion finishes it's going to return the minimum which is the minimum most minimum that it has found so far by through all the recursion process and then towards the end we'll return them let's see if this works okay great so it does work so we see that uh the it is efficient and the time complexity for this would be o of N and um yeah I hope the solution was helpful and uh thank you so much for watching and uh hope you have a great rest of your day
Minimum Distance Between BST Nodes
search-in-a-binary-search-tree
Given the `root` of a Binary Search Tree (BST), return _the minimum 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, 100]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
null
Tree,Binary Search Tree,Binary Tree
Easy
270,784
1,992
um hi friends uh welcome to my channel let's have a look at problem 1992 thanks all groups of farmland uh in this video we're going to present two methods or two formats of method so the first one is the standard depth first traversal and the second one is a traversal algorithm along two directions so this problem asks us to describe a group of farmland in rectangleship so let's look at one example so in example one so let's look at the group of farmland corresponding to the four vans in the lower right corner so this four ones so the top left corner has coordinates one so this corresponding to here and the bottom right corner has coordinates two so corresponding to these two components in the second component of the return so for each of the form group of farmland we are required to return such a list describing the top left corner and bottom right corner coordinates so with that said let's also have a look at the constraints so the size of the lens is described by m and m so both the two numbers are bounded in between one and three hundred so the length consists of zero and ones so this is standard and the last assumption is that the groups of farmland are rectangular in shape so this last constraint is important information for this problem so with that said let's look at the method we're going to present so first one is a standard depth first search traversal so in this method we didn't use the ship assumption on the group of farmland and the second method is a traversal algorithm along two directions so here we do use the ship assumption so here are some comments first this problem is in essence no difference no different from the problems listed below lackluster problems 1905 1254 1020 733 200 and so on so especially if we use standard traversal algorithms to solve this uh this set of problems so in this specific problem the key observation is the following this is the following assumption so group of farmland is of rectangular ship so if we iterate in a format like below see 4i in range the rows and the 4g in range the columns then we always first meet the top left corner of a group of farmland so therefore to locate the bottom right corner so we just need to see how far we could move starting from the top left corner to the right add to the bottom respectively so that's basically the second method so our plan here is the following first i'm going to implement a standard depth first search without using the ship information so this is going to be a little bit brutal force and then we're going to implement the two directional traversal algorithm this is more ideal for the problem at hand with that said let's first look at the first method that is basically of berliner steps for search without using the recliner information so first i'm going to check track the meta information so about the rows and the columns that is length the length 0. so this is standard so next i'm going to write a hyper function the hep function is a standard depth first search helper so i'm going to call it dfs ig so ig will be a coordinate i'm going to initialize a set called visited to represent the corresponding farmland or cluster then i'm going to initialize a container let's see it's called ig and then we're going to do the standard iteration that's a while loop well container we're going to get the position by container pop so um we'll visit this con uh position we're going to add this to the visited side and then we're going to look at the four neighbors of this position so for x y in r minus 1 c r plus 1 c and r c minus 1 r let's just make it slowly so r c plus one so um then we're going to check if x y uh is inbound and uh not visited yet and it's also a land cell so if zero less or equal than x less than m and zero less or equal than y less than n and the length x y is a land cell and also we haven't visited yet not in visited uh we're going to uh put this to the stack we use it as a container as a stack so append x y so the after this value actually we finished uh we'll finish or included all the cells in the current group of farmland so to locate the top left corner and bottom right corner actually we just need a thought so let's see i'm going to introduce a temporary variable let's call it temp sorted the visited and then the uh the return of the top left corner corresponding temp times zero so let me write like this zero temp zero one so this two number two numbers correspond to the top left corner coordinates so then let's get the bottom right corner coordinates that's corresponding to temp negative web 0 temp negative 1 to 1 so then we also need to return this the cluster of the file the group of thumb itself so with that said we finished the implementation of the hyper function so next is we do traversal and prepare the return so for this i'm going to initialize a variable called result so we want to use this variable hold the information so then we also need a set to add our torso so next is just a standard iteration for i in range m for g in range m so if i g not invisited and also fig so let's see land ig equals one and so that's not in visited then we're going to do a traversal starting from this position ig so we're going to return the coordinate pairs and also the formula so let's call it dfs ig and so we're going to append our result with the coordinate pairs and also we want to enlarge the set with the formula we have visited so that's all we need to do for preparing the return now let's do the return so that's a full solution format for this problem let's do a special case check here it passes a special case now let's do a generic test check uh it passes uh all the cases so this is advanced solution but in this solution we didn't use the information for the ship so now let's do a second solution let's copy this signatures and then mark this as solution v1 so for this i'm going to do what we are going to do is a two directional two direction traversal so for this again we're going to track the information for the number of rows and number columns let me track this information and m and n are the number of rows and columns respectively and also we're going to initialize a variable let's call it results this is the first part and the second part is hyperfunction again so this hyper function will be a true direction traversal so for this i'm going to define it as that edge so find start to be precessed from rc so if this rc is the top um left corner of the group of farmland then we're going to reset this uh let's see our let me use uh let's use r2 c2 maybe so just for then we're going to start from this position and then we can see how far we can move to the right and to the bottom let's first move to the bottom so well r2 plus one is less than m and land r2 plus 1 and c is 1 then so we're going to increment r2 by 1 so this way we can move to the bottom to get the uh first component of the coordinate for bottom red so notice that we check the while loop with increment one right so if we exit this one we're going to get r2 still inbound so this is the see traverse to the bottom and next we're going to traverse to the right so basically we are checking if c2 plus 1 is less than n at land c um r and c two plus one is still one so if this is the case so actually we can uh we can start from any r here between the r at the very beginning and the final stage of r2 right so but it's okay here uh then we're going to move to the right so we're going to um increment the c2 variable barely so this way if we get out of the well loop where actually look uh able to locate the largest red coatings actually this coordinate corresponding to the second component of top bottom right corner so then what we're going to do is that so we want to set all the cell cells in this rectangular with top left rc and the bottom red r2 c2 by 0s so this way we're going to avoid repetition in the following steps so for i in range r and r2 so we are ending at r2 so we using r2 plus 1 and 4g in range so c number c2 plus 1 right then we're going to make it o zero so this finish is the main logic then we're going to append the corresponding coordinates rc this is the top left corner and r2 c2 this is the bottom right corner to the uh result so we can think of this guy as a traverser or a worker right so next what we're going to do is call the function to do the work and prepare the result so this is basically for i in range m for g in range m then we're going to check if land ig equals one so if this is the case we're going to call this function sent h i g right so this function will automatically add the list to the result then after this we just need to return the final state of the result variable so that's actually the full solution for the second format so let's do a special case check yeah it passes a special case now let's do a generic check yeah it passes the all the generic cases i guess so this finishes the second method so let's give a quick summary to end this video so in this video we pre presented two method one is a standard depth first search the other is a traversal along two directions taking into consideration of the shape assumption in this specific problem so with that said i guess that's about it for this video thank you so much
Find All Groups of Farmland
sort-linked-list-already-sorted-using-absolute-values
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group. `land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].` Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_. **Example 1:** **Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\] **Output:** \[\[0,0,0,0\],\[1,1,2,2\]\] **Explanation:** The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\]. The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\]. **Example 2:** **Input:** land = \[\[1,1\],\[1,1\]\] **Output:** \[\[0,0,1,1\]\] **Explanation:** The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\]. **Example 3:** **Input:** land = \[\[0\]\] **Output:** \[\] **Explanation:** There are no groups of farmland. **Constraints:** * `m == land.length` * `n == land[i].length` * `1 <= m, n <= 300` * `land` consists of only `0`'s and `1`'s. * Groups of farmland are **rectangular** in shape.
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
Linked List,Two Pointers,Sorting
Medium
148
1,026
hello everyone welcome to let way coding today welcome to soft problem 1026 max difference between node and ancestor and we can see this is a really commonly asked questions by Facebook so let's see the problem given a tree we need to find the max value for which there exists a difference between node a and B and note a has to be an ancestor of B so first of all what is an Assessor so for example note 3 has access to 8 and Note one has adjuster 3 and 8 so a sister is all the node above it so yes this is the problem and given this tree the answer should be 7 because in this tree the maximum difference is 8 minus 1 which is 7 so yes so this is our tree and we need to find number 7 so we need to traverse every node we also need to know the Assessor so we need to traverse all the note and we also need to keep track of the Assessors of a single note right so for examples are starting from here we know it has no Assessors and we initialize the maximum difference as largest number then we go to 3 and 10 first we go to a 3 and we know 3 has an ancestor 8 and then we check the difference between three and five it is five so we update the difference five then we go to one we know one has to assess errs three and eight so we check the difference between 3 2 1 and 8 to 1 and the maximum difference is 7 then we go to 6 also has two Assessors 3 6 8 then we check the difference between three to six two six and eight to six the largest difference is not larger than seven so we go to four the Assessor is 6 3 8 then we check the difference between 4 and 6 4 &amp; 3 4 &amp; 8 difference between 4 and 6 4 &amp; 3 4 &amp; 8 difference between 4 and 6 4 &amp; 3 4 &amp; 8 the maximum difference is 4 not bigger than 7 we go to 17 I mean we go to 7 g7 equal to 77 the Assessor is 6 3 8 maximum difference between ancestors and the note is all negative number it is not larger than seven then we go to the right side the ancestor is eight the difference is negative two is not larger than seven then we go to 14 the ancestor is eight and ten all difference are negative we go to 13 the assessor are fourteen ten and eight now we traverse all the node and we find the difference seven so how should we do this how to do we traverse all the node we use a stack to do a depth first search okay now let's code it so if there's no we just return zero otherwise we initialize a maximum difference as the largest member first we first will utilize the maximum difference as the smallest number then we initialize the stack and we put the root on the stack that's how we do the depth-first search so when the stack is depth-first search so when the stack is depth-first search so when the stack is not empty what do we need to do so we need to put is ancestors and the current route through the stack so ancestors so Esther's and note we get it from the stack we know the current value is not that value and for number in is ancestors we need to update the maximum difference value so it should be the current value comparing to the assessor number minus the current value then if the node has a left child we need to put the course node as an ancestor of the next node so ancestors plus the current node value which is current one and the next node same for the right node you then in the end we just need to read her the maxed if so let's run it first you so let's run it first yes it's correct and let's see our ancestors and note that value who opes typo okay so let's visualize the stack so on the root level it has no Assessors and then next node has assessed her 8 and 10 then the last node has assessed her 8 10 and 14 same for the right side yes that's how we do this problem now let's run it okay we need to catch the absolute difference yes that's it so let's analyze time/space Catholic City the time/space Catholic City the time/space Catholic City the time complexity is all of N squared the space complexity is o of n because we use a stack Y n squared because um for this node we need to traverse always ancestors and for this node we also need to favor us always ancestors and there are a node for every node at most we need to traverse always ancestors so that is N squared ok thanks for watching the key point is to know how to use depth-first search if my solution helped depth-first search if my solution helped depth-first search if my solution helped you please feel free to leave a comments see you next time bye
Maximum Difference Between Node and Ancestor
string-without-aaa-or-bbb
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\] **Output:** 7 **Explanation:** We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. **Example 2:** **Input:** root = \[1,null,2,null,0,3\] **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[2, 5000]`. * `0 <= Node.val <= 105`
null
String,Greedy
Medium
null
279
Hello 12210 Adherent Drama Hai A Question On The Real Question Have Given Figure In Teacher In A Bid To Delete Number Office Padh 600 Ki Shopping Yeh To Return Minimum Account Of Ko Ye Number Dial Per Number Thursday 333 Number Four 3232 Number 9 The 15-minute doing this question to answer this The 15-minute doing this question to answer this The 15-minute doing this question to answer this question is required to take all possible options do give oo [ possible options do give oo [ possible options do give oo ki naav pani peene part par select question minute tawe newsroom report subscribe now to the number a better way to think about this Went on becoming difficult entry point click a subscribe button on request that android whatsapp number given attacking but condition * garlic and 323 294 subscribe and subscribe the option to two three idiots and half a minute plate that sort of a computer industry For many years paper subscribe Video like subscribe comment and subscribe quit dark line half black unauthorized minimum set I am safe how will meeting are currently I am just simply regret particular number result with that nine under way at something good morning use Painted On That Tractor 415 Think About This Question In Terms Of Fiction Non-Fiction Option Required Subscribe To Me Also In Flight Mode Setting On International Slide Subscribe Don't Forget To Subscribe To Point Subscribe - Vid U That Angry Birds Century Liquid Top This Number Subscribe to this channel if you liked The Video then subscribe to Ki Know What Option Real Pacific Dost Point Hi Number Video subscribe to I will have to three by clicking on subscribe button to subscribe to this course Central and State Level Peace Possibilities for It's President A Sort Of Dad In Her Every Level Pind Pendant And Dual Air Condition David With U's Days How Many Pockets Per Number Three Code Top Student Twitter Account Number Perfect Square's Paste Pocket Any Number Starts From A Point Patti Wrap Number A Lucrative Square year of two lotus ayurveda india vid oo ka anniversary hai is anmol the wire testing vivar tight is remedy only top that abhijeet returning officer title childhood mein and vipin gupta loot mid and modi live video vid oo MP4 latest short patwan ine adrak hair in Her Pocket Ko Number Four Without Makeup 2017.2018 Bluetooth Setting On Off Equation In The Father Shri Krishna Paksha Pimple Hai Me Itna Which Text Typing And Interactive Water That Condition Which Farting Report Subscribe Solution Hai Near International Why Water Before Taking A Note Via Please Pen function is more, I have used tractors on Wishes Plus Live - Sid channel and good doing is a viewers page using a typing meter reader 130 off account with Titanic number one 12314 looting 9th minimum post. Bill Account Of Square Meal Tak Hi Use To Make A The Right Foot Ulcer Acidity Answer Birthday Points Avadhesh Diverse Famous Number Sirf Is Ped Possible And Subscribe To 162 Accused Account Of This Prayer With This App You To Do It Main Baitha Hoon Asaf Request Tubelight Side acid id m id result subscribe to torch light table's vitamins maximum turn off the speaker the subject of the growing in president take only one side subscribe to [ subscribe to [ subscribe to [ laughter] that cheese's a particular number at number rich voting in to-do list Number 2 are fennel rather under that means some loot is determined [laughter] a top debit appointments will give pot amendment but subscribe now to receive that superintendent of police complex drank difficult to login
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
240
welcome to february's leco challenge today's problem is search a 2d matrix 2. write an efficient algorithm that searches for a target value in an m times an integer matrix the matrix has the following properties integers in each row are sorted and ascending from left to right integers in each column are sorted and ascending from top to bottom okay so if we want to see if a target exists inside a matrix obviously we could just search every single cell and see if it exists but there's this property that both the row and columns are sorted surely we can take advantage of that to make it more efficient well the very first thought i had was well we could just do a binary search on every single row to see if the value exists that would be a what n log m solution but that doesn't take advantage of the fact that this side is also sorted so that's probably not going to be the most efficient so what if we did binary search on both the column and the rows we did like a for instance here if we did a binary search and we looked for five we would probably end up here saying okay well we can't find the five but this is the uh greatest number lower than five but you can kind of see that it's not going to work if we started to do my research here because we'll check here and we'll see five doesn't exist and now where do we go there's no real good way to know where to go from there so that's also not going to work all right so let's think about where can we start to start eliminating rows and columns what if we started at the bottom left now if we check to see all right is the is our target greater or less than this value here if the target is less than this value we could completely eliminate this row here and just move up right in the same way if the value is greater then we can eliminate the first column and just move our point pointer this way if we did this each time we could eliminate a row or um a row or a column and that's going to end up becoming a m plus n time complexity so let's try going with that first we'll initialize a couple variables we'll initialize the n and m to equal the length of the matrix and the length of matrix 0. now we need our pointers row and column so row we want to start the very bottom that's going to be n minus 1 and column we want to start at the very beginning so i'll be a zero okay so while the row is let's see greater or equal to zero and the column is less than m what do we want to do well first we want to check to see if the target is equal to this so if matrix dot r or c equals target then we can immediately return a true now otherwise we kind of want to do this quasi binary search here right if the matrix our c is less than the target we know that we can eliminate this first row if it's less then we know that it can't possibly be in this first or this last row here so we can just move our row value up so we'll say row minus equals one otherwise if it's uh greater if their target or i should say rather if the target is less then we know that it's got to be um oh it's shoot i think i'm confusing this okay if the value is less than the target that means it's greater so we move okay so that's i flip that around that should be column plus one otherwise row my school one uh if we can get out of this loop though if we get out of bounds that means the target just doesn't exist so we can go ahead and return a false so let's go ahead and make sure this works it does let's go and submit it and there we go very simple algorithm now it's not that easy to come up with this i know like in hindsight it seems very simple but initially i kind of floundered about thinking about binary searches and all that it's only when you start thinking about well where else could you begin like to start eliminating whole rows and values where this algorithm can start coming to you so yeah i hope that helps thanks for watching my channel and remember do not trust me i know nothing
Search a 2D Matrix II
search-a-2d-matrix-ii
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: * Integers in each row are sorted in ascending from left to right. * Integers in each column are sorted in ascending from top to bottom. **Example 1:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5 **Output:** true **Example 2:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= n, m <= 300` * `-109 <= matrix[i][j] <= 109` * All the integers in each row are **sorted** in ascending order. * All the integers in each column are **sorted** in ascending order. * `-109 <= target <= 109`
null
Array,Binary Search,Divide and Conquer,Matrix
Medium
74
878
hey everybody this is larry this is day 11 of the dissembly go daily challenge hit the like button the subscribe button join me on discord let me know what you think about today's farm 878 and magical number positive integer is magical if it is divisible by either a or b okay given n a and b find the nth magical number uh okay and n could be really big 10 to the ninth right so okay huh so a or b hm okay so my first instinct um to be honest uh and okay so i am solving this live so if it's a little bit slow just fast forward um but my first instinct is to um my first instinct is to do like um like a breath first search type thing um like a q like okay you start with a and then you start two a you start b you stop two b do some kind of heap type thing and kind of sort it out right and of course when you see that and it's really big that's not really feasible and then my second thought immediately is just binary search um and in this case the only two numbers so i will get into maybe i'll talk a little bit about the general maybe not general but um a method to kind of let you figure out how to do it for more than two numbers right and that is with uh something called the inclusion error how do you say inclusion exclusion principle which is allows you to kind of calculate the math behind that um and but of course if only two numbers um i think you can probably come up with how to um how do well okay let me step back for a second and let me just go over it right um with binary search what are we binary search by actually is that um that's really i mean i think this one threw me off a little bit but i think at least in pi finder should be okay um given that yeah i mean we could do some math on the bounce it may be very big to be honest but either way binary research is okay because okay so instead of asking what is the n magical number you at um the way that we structure this as a binary research is that given a number what um what magical number is it right um what like what is this position magical number it is and yeah it should be relatively uh i wouldn't say it's straightforward but you can calculate it relatively easily um because you can't so for example like two and three so a is equal to two b is equal to three then your magical number's gonna be um i mean you could sort them but i'm just gonna split them out split them up so you have two four six eight oops ten you know dot right and you have three six nine twelve fifteen dot and of course you wanna combine them and sort them and also d dupe right and of course the math is relatively straightforward in this case where the detailing is a times b is equal to six um so multiples of six are going to happen um it's going to do right so with that in mind um the formula of given a number let's say i have some f of a number so returns the um returns k where k is uh where uh x um where the cave uh um where sorry i'm just trying to anguish this part where x is the cave magic girl number right um and in this case uh maybe i'm dealing with all five ones we'll have to kind of think about it a little bit but you can just do x um this is gonna be this is the number of um this is the number of numbers that are ma and okay let me actually rephrase this for a second um this means that there are k minus one is this one uh one based doesn't actually tell you per se though with the example it tells you but it's a little bit awkward there are k minus one um magical numbers smaller than x right so uh wait so actually this is not true i lied a little bit um like we this is what we ideally want but what we actually have in a function is actually calculate um how many smaller magical numbers or how many magical numbers are smaller than x right um and then here then we can use this formula okay i think this is a little bit more better of a question to ask um because then now you guys okay um because the reason why i say this is because why i changed to this is because um where from here um you could get from here to this question but um but they're not equivalent right for example in this case between two and three you can say you have 11 and 11 obviously is not a cave magical number but we do we are able to calculate how many magical numbers are smaller than it and of course you can do some math about that later um but yeah so then here to end to answer this actual question um yeah let's and the way that i always like to think about it with respect to off by one they just think about edge cases right um so by default i'm going to jump to this but let's say we have x is equal to six or let's just say x is equal to 12 and a is equal to 2 like we have here then how many numbers are strictly smaller than this one right well it's going to be it's not 12 divided by 2 it's actually 11 divided by 2 uh the 4 of that so that gives us you know this and then the other component is you know obviously some symmetry i don't have to prove it or you know you can prove it at a smaller pace if you get and then um x so you have these two things oops right i mean of course we should probably cache this so that we don't have to calculate it all the time um right um yeah and i'm just double check gang yeah okay so i'm working in my head whether this is you know how many duplicate numbers are there smaller than this one so basically this is number of smaller numbers that's more than eight then what's more than b and how many dupes so then you just have to um you just have to you know sum this up obviously you sum these two components i always put parens i know the order of operations but it also makes things readable i believe um and then you subtract the duplicates um and this is yeah this should be good right and like i said for more than two numbers you use something called the uh inclusion exclusion principle but yeah and then now we can do a binary search so we're gonna left and right is equal to so this part may be a little bit tricky because now we're trying to figure out the bounds by which we set the right and in this case n is 10 to the nine so and b is four times ten to the fourth right and that means that if we draw out the sequence where b is four times ten to the fourth um and there's ten to the nine of them um then it's just these number two numbers combined or multiplied by each other so roughly speaking i'm just gonna it's like 4 times 10 to the 13 or something like that maybe but the beauty is that you can actually you know uh as long as you're pessimistic in terms of you know going further off you know you always get a right answer so i'm just gonna opt for this um it's a little bit slower but that's fine yeah and now we're gonna do our binary search um and note that this fits in the long so you know they want you to return it mod this number and also actually let me before i forget let's actually uh do the mod thing because i forget a lot actually and usually i do a little song but today i did not um okay so yeah so what was i saying uh so yeah so this fits in the long so you don't have to worry about big ends or anything like that um so i would be confident in most languages and then you do this and this is regular binary search and then the question is okay how many magical numbers are smaller than uh in this case x uh and this may not be the question that i asked to be honest let me think about this for a second so let's say we want to try to figure out the magical number n right so then we ask ourselves okay given oh not x oops mid um how many what do we want right if this is so the n magical number would have exactly n minus one magical number smaller than it so if it's equal to or greater than this then that means that um what does that mean that means that this is now an upper bound right because every number that's bigger than this will have more than n minus one so now we can move the upper bound down and that means that and it's inclusive because f of mid is a part f of mid equals n minus one is a possible answer so that means that this is inclusive so we do this and then otherwise left or mid is not a possible answer and that's why we do mid plus one like this um and that's pretty much it um yeah and so the reason why i hesitated a little bit when i saw the mod is because if you needed to do big end or something like that i mean python actually is par it's okay um and i probably should have proved this ban first to be honest i did this a little bit in a weird order for you out um but um because you cannot do the modular before the binary search right so that's why it's a little bit awkward if you need to do a big int i mean you have to do a big int you cannot do it with modular right so but now with this i am a little bit more confident so let's give it a spin uh and of course we'll do a big case later we just want to check at least these bass cases uh and i got the wrong answer so i'm feeling a little bit sad am i just off bye huh welp that's a little bit sad uh oh i was wrong on this one i think yeah so basically yeah i mean i looked at two relatively prime numbers and then i went oh okay yeah you just multiply them duh um and that's why sometimes you know uh you gotta validate things and i went a little bit fast because i was my excuses that i'm shooting on video i'm doing it live but yeah but now as soon as you see this you know that you actually want the least common multiple right for example and you can play around with examples here but like for example you i didn't even see the examples but that's what i imagine um but like i know and i'm off by one to be uh to be honest um so i've double checked that um that is a little bit awkward actually but anyway we'll double check that off by one uh because usually that means that i'm asking the question wrong and then as a recording but let's say for example this is i don't know something that's um let's say six and eight right i want something that's not a multiple of each other so a times b is obviously 48 but lcm of a b is what is that what is this right um well 24 right so of course we're gonna double uh we're gonna under count actually because if you just you know what's the 6 12 18 24 dot um 8 16 24 dot well of course this is a dupe but we are now formula we did not calculate the dupe so we just have to do this uh by getting the you know um getting the least common multiple and then we should this should be good other than the off by one which we'll look at in a second but you can vertify that at least it's consistently off by one um so then my question is did i ask the questions incorrectly right why is this off by one i mean of course i can just do a plus one or whatever a bit but i actually want but usually that means that there's some that uh my understanding of the binary search is a little bit off um or just in general i mean it doesn't have to be a binary search problem for it to be off but it is some you know an indication that something's off and you know uh for me especially when i'm you know trying to teach or whatever um trying to understand why that is and stuff just like oh yeah just add one and then we're done right now i mean try to understand it a little bit um because my understanding was that okay so that means that this part is probably a little bit off um because that's the only place that we really make a decision um let me think about this i mean this is inclusive so that means that mid is a possible answer so why is it that and if this is smaller than n we need a bigger n minus one did i mess up the n minus one point because we want the first number essentially uh in which f of mid is greater than oh okay i see i actually messed up uh on this one because i asked the wrong question okay um so actually i don't know if plus one works maybe a plus one works but now my understanding is a little bit better and i think i got it wrong and i see why i'm wrong and i'll explain why i'm wrong and actually i think this will be uh this is a good lesson to kind of figure out off by once i think maybe but um but what happened here is that for example what i ask is so what i end up asking here is actually what is the smallest number um where uh where there is n minus one uh magical numbers smaller than right so english is a little awkward but hopefully that uh gets my point across where that actually isn't true i think in the innately because i was thinking about the first thing but actually that's not true right because for example let's say we go back to here um if we were here let's just say we're looking for i don't know the sixth number or something the sixth number uh or even doesn't matter just the fifth or just the second number that means that we are asking for uh what is the smartest number in which there are one smaller magical number right and that means that for if you put this in a list a sorted list then the number is actually seven right so this actually returns seven instead of um this actually returns seven because seven has one smaller magical number so actually what we want is the largest number where this is the case of course there are in other ways to solve it there for example um you can actually make this like smaller than or equal to then you want the first number because then you get the first number which is the z code to end my uh um and exactly and or um because if you set this to uh smaller or equal to then your question becomes what is the smallest number in which this um is equal to n um and that also solves the problem but so there's multiple ways to kind of resolve it and that's why i say um it really matters how you ask the question and like state these questions out um and yeah and now we want we now change the question to what is the largest number right and then what does that mean that means that if this is equal um let me think about this for a second right uh if that means that if this is equal then we actually so now we fix this a little bit because if this is equal that means that um if this is equal that means that this can be bigger right so now our thing is a little bit awkward um i mean you could split up into a ternary thing and i'm gonna do that just for illustration because i think um the right way is to switch the signs and it might not make sense so i'm gonna break it down a little bit more so let's say we have this function from the previous one um we'll break it down a little bit so let's say we have this and then else if um because i want to demonstrate very clearly why um right so this is equival equivalent to this and i think this part is not that much of a leap um yeah but then now that was so this is for smallest number right now we want the largest number and then now we have to think about the cases right well if this is bigger than n minus 1 what happens if this is bigger than n minus 1 then this is true um is this true yeah so i'm confusing myself for a little second um so um at least in terms of explanation um so what is the largest number with this is the case so if this is bigger than that then actually this is not possible so this is right minus one right because we want something that's um exactly and minus yeah we won um we want a number that is exactly that has exactly n minus one items right so we convert this to right equals mid minus one uh what happens if it's equal to well if it's equal to then actually in this case we want left is equal to mid right because now if this is equal to n minus one um then our number because we want the largest number we want it to be possibly to go up right where but it is mid is a possible answer but it may not be the largest number uh answer so that's why we're gonna set it to this um otherwise if it's smaller we set um left is equal to mid plus one um and i think this will give us the answer um though of course um uh the reason why i wrote this a little bit awkward um is that you can also switch the signs if you're um if you're very observant and actually you know left is equal to mid minus one uh plus one is fine um but you know if you want to be pessimistic you can also just you know remove the plus one and then as a result um this is you know you could um wrote this into that and that means that you just end up being this thing right and that's the short way of doing it uh and that's what i was thinking about writing actually i was thinking about like switching the signs a little in a different way but uh but yeah that should work in theory unless my understanding is off again so let's give it a spin yeah so that looks good now that we really understand why we write these four if statements right and i think that's one thing that comes from practice and me going over it um hopefully will give you some insight as to how these things are because i think one thing that happens a lot is that you see these if statements and people just kind of give up give you like random things and they just tell you why it is and just go whatever right and like i said um uh yeah so these if statements have meaning and that's and i hope going through it in a more deliberate pace will help you out and of course these if statements also depend on this question and this question also depends on this question right so they all follow through and so if certain things a little bit different you may actually um have slightly different answers right because for example if you don't use n minus one you use x over a instead then this is smaller than or equal to and that makes the question different to get your answer um yeah so now let's actually try a number that requires modding so yeah let's just do two three and uh what's that ten to the nine where n is first right so oops uh yeah okay so that looks good so i'm kind of uh or happier i don't know let's do it one where they're not mutually uh they're not mutual um uh they're not relatively prime that's what i was going to say so that still looks good so let's give it a submit uh well i haven't done this one before i mean i've been done this one before on lead code i have done similar problems before so yeah um day 6 20 streak um yay um yeah um of course i the complexity is um straightforward for binary search um we look at the search space and this is constant in the size of the search space i guess or log of the u where u is the size of the universe which is uh the range which is 10 to the 14. um so let me write it down log u time where u is the size of the universe which is the range of 10 to the 14 say right and of course space this is just over one because we have a couple variables and that's it um you can also analyze it in terms of the number of digits um i'll leave it up to you at home uh but it's going to be linear is the there's the short story um if you want to analyze into number of digits so yeah so anyway um i think that's all i have for this friday or maybe saturday to y'all i hope y'all are doing well stay good stay healthy to good mental health uh hit the like button hit the subscribe button and join me on discord take care of yourself i'll see you later bye
Nth Magical Number
shifting-letters
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = 2, b = 3 **Output:** 6 **Constraints:** * `1 <= n <= 109` * `2 <= a, b <= 4 * 104`
null
Array,String
Medium
1954
322
welcome to this video in this video we're going to solve this coordinate equation queen change in this problem we're given an array of integers and a variable amount we have to find out a minimum number of coin from this integer array and the minimum coin should add up to this amount and we can repeat the coin as many time we want so here we have one we can take this one six coin of one so we can get six if we get this coin two three times then you get six if we get this coin two diamonds then you get this six they started six so we can find out this amount six by taking minimum two coin that is three we can assume that we have infinite amount of credit we can choose as many coin as we want we have here one we can choose six one to add up to this target we have to we can add up to we can use three two coins to add up to six and can take here two coin three to add up to this amount six this is the problem now how to solve this problem first let's talk about the main solution to this problem first thing what i will do we have the unknown six now we can choose here three query we can choose one we can choose two or we can choose three if we choose here one then we will have here amount five here we have again three choice we can choose here one we can choose three now we can choose two we can choose three if we choose here one that we will have here four we're going in dfs manner then if we choose here one then we'll have three we have also three so is here if we choose here one then we will have two if we choose here one we will have one then if we choose here one then we will have zero so when we find out zero we can find out the path in this path we have six scoring one two three four five six so this is your one this is your six coins that add up to this amount six so at this point we find out minimum equals to six minimum six coin required now can you choose here the coin two if we choose then we will have the amount remaining about minus 1 this is invalid if we choose a 3 this is also invalid we will have minus when we have 0 what we will do will return 0 and we'll add 1 to the zero because we have we are getting this zero by subtracting one coin from our amount so here what i will read it will written zero plus one that is one so here we written one and here we see we have in invalid this is invalid so we do nothing here now here we have another choice we can choose at the point two which is going to we will have here 0 so we find another path this is a valid path this path okay this path 1 then 2 and here we have 5 coin so we can keep track here the 5 now minimum is five now here if we move if you choose another coin that is three you can choose here we'll have minus one this is infinite this is invalid okay so we're done with this we can do this recursively we have three choice for each node if we consider a node now here for three we have choice we can choose two we have one for one if we choose one then we will have zero this is another path the length one two three four five if we go in this way we will have a path which is three and three okay so here we will have if we subtract uh three from six we'll have here three if we substitute integer three will have zero this will be the shortest path or we can say with the minimum number of quite required to add up to this amount six this is how we can solve this problem but this is new solution this solution will takes amount if we consider is this amount is to the power n or n is the length of the given array this is exponential time complexity this is not super efficient can we optimize this time complexity yes we can optimize this time complexity let's see how to optimize this time complexity we can convert our exponential time complexity into o of s times in this is the given amount and it is the number of integers we have in the given array now first thing we have amount so six now first let's choose your one if we choose one we have five if we choose again one we have here four where uh we're moving in dfs manner then three if we choose zero one then again if we choose here one we will have two equal to zero one we'll have now one now if we choose here one we will have zero so the number of coins we have in this path one two three four five six to optimize this algorithm we have to use dynamic programming if it is dynamic programming we don't have to recompute one things many times so let's create a dynamic programming table the link to dynamic programming table is the length of the amount plus one so six plus one let's create a diamond for a table right here one two three four five six okay and here zero this is our dynamic programming table at one whatever install at index one will store the minimum number of coin we need to add off to one okay to reach this amount one so here we see to uh to get this coin to fill up this coin or this amount one if we have amount one we need just one coin right so we need one coin so here whatever will written zero plus one that is one let's do here one now we have another choice here the choice is uh here we have another choice the switch is into zero two if we choose with a minus one if we choose zero three we will have a minus two these are invalid will not take an invalid value here okay so we have here one now let's move to two how many coins we need to add up to this amount two actually we need just one coin okay so here we see we have one if we substitute one from this and if we subtract one from this we have already computed for one if we substitute one from these two we will have one so one plus whatever solution we have for this one so here we write it just two so for this direction we'll have two if we choose here two that will have zero so in this directions what i will do we have zeros will return zero plus one for this coin one we have here no more amounts we have we need no coin here so zero plus 1 a 1 for this amount that is 2 we're subtracting so for this path we will have 1 if we choose here another number that is 3 then we have minus 1 this is invalid so here whatever takes only the minimum two and one so here one is minimum so here we will return one we will take it this path okay so here we will have one for this node so we have here one we solve this now let's move to three when we move to three on the left when we choose one we see we have two to get this value to we have already solution in our time programming table so we don't have to repeat our same work multiple times so what we can do we can get the value from here for two and we can add to one for this node because we're subtracting for this amount because we're subtracting so here let's written one plus this value once that is two so for this path we have value two here and here if we choose two then we'll have here one for one we have solved already right we have solved already for one so here we will return this one for one so one plus we're subtracting one uh coin so we'll have one plus one that is two so here will have two now we have here another choice three which is three here we have uh for three if we compute uh if we subtract this three from this amount we have zero so we have here just to one coin all right so here we have normal coin required here we know uh here we see that we don't need any more query here so zero plus we need here one coin so one here this direction written one so minimum of one two and two this three are valid paths so we will determine the middle minimum is one so we will insert this one at this index so here what i will return this one plus one for this path let me choose one so here let's return one let's move to this direction we move to this direction here we can choose two then we will have two what do we have already solved we need one coin the minimum number need for two easy ones one plus this coin that is two so this path is two actually here from when you're going from here to here we have the minimum one here so here it will return to one plus one for the square one and here for this we need one coin so two here this path is two if you choose here three then we have one for one we have already solved so here this path also return true so mean over two and two is two so here we have 2 so what will written to this by subtracting one node and 4 we have solved 2 so 2 plus 1 is 2 this direction written 3 now let's choose here uh 2 then we have three for three we have solved already we need only one point so one plus one is two this direction is taking two now for these directions we can take here three we will have two for two already solved so we have one and we need here one point so one plus one is two so minimum is two so here we'll have minimum two okay so for this coin five here for four we see we have two we have to insert here for five we have to insert here two okay so to get this amount five we need minimum two coin we're optimizing it our algorithm right and here for six we can choose here for this direction let's stop it we have we need five uh two points for five this amount five and one coin to get this value of five from this amount six so two plus one is three here these directions gives us three if you choose here two we have four we have already solved four two four we have two so two plus one that is three this direction also gives us three and let's move to these directions if we move to these directions we will have here three for three here we'll have three we have solved already for three which is we have here and we can see here this okay so minimum is this in this path so here we have already solved so we have just we just written zero plus we have substituted one coin so you know it's zero uh three for three of one plus we need one for this coin uh for this amount we need one point one plus we're subtracting one point so two so here we have two a minimum of 3 and 2 is 2 so the answer is 2 this is the algorithm to solve this question and this voltage of is a space complexity now let's write in the algorithm let's call the function queen chant we change its takes to parameter given array and amount it takes this two parameter now we're going to create a dynamic value table difficult to new int amount plus one so we have this dynamic programming table now let's call a recursive function dfs let's call here return dfh this option takes three parameter first the number array the given average then the amount and our dynamic programming table this function will written the minimum query needs to add up to this value six if there is no subscript we should written minus one now let's implement this database function d f is it straight to three parameter norms amount this amount let's call it remaining okay let's call it ram for remain then dp this is our dfs function call now we have our base gauge if we find it really equals to zero then what i'm gonna do i'm gonna return zero so return zero if we find it remain is less than zero it will written minus one now here you could check because we're using dynamic programming table if dp ram is not equals to zero it means we have some uh element edges to have minimum number of queen or minus one so let's return it i return db ram and here we have to declare a variable minimum v equals to maxine integer right you can you have let's try and move here for coin in coins okay let's call it here function we have here have okay we have a closed let's call this function dfs with three parameter nums subscribing that queen so amount minus queen then we have here dp okay now here if we find out it's not going to reach out instead original if we find out the result is less than or equal to here it's valid if we find out uh results result is less than minimum so we have a minimum here so once that let's skip to the middle minimum goes to one plus phrase now right here we're going to insert in our db digital also dp red equals to if we saw minimum is equals to max integer if it's not changed so it mean equals to max int then what i will do i'll just insert here minus one otherwise the minimum and we will return this daily ram this is your goal thanks for watching this video
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
395
in this problem we are given a string and we have to find a substring out of that string based on the condition that uh all the characters in that substring should appear at least k times so this is a long problem statement so let's look at a couple of examples to understand this problem let's say this is the input string and we have to find a substring out of that and k given to us is 3 and we have to return the length not the substring just length so in that substring each character should occur at least three times it can occur more is fine but not less than three so if you see this substring clearly it's just a and a is occurring just once so it cannot be possible if you look at this substring then we have a is occurring two times still not good enough but if you look at this part then we have a and in this substring there is one only one character a which is occurring three times so it satisfies the condition so this is a candidate three length we have to return just the length but can we find a bigger substring so we look for all other substrings clearly b is occurring just two times a is occurring three times and c is occurring one times so these cannot be part of the substring just a can be part of the substring and if any of these character comes in between then we cannot include that so this is the essence of this solution and we will use this concept to solve this so in this case it will be just 3 and the answer will be corresponding to this substring there can be multiple but in this case there is a unique now let's look at this problem here it's just 2. so if we take a or a b we have a occurring one time b occurring one time not valid if we take this part then a is occurring twice but b is occurring once so this b or due to this b we are not able to include this and we are moving towards solution this pattern if you keep observing that if this b was not present we would have happily taken this but since b is in between it ruined our solution so we will explore further so we come to this part now b is also twice a is also twice so this is valid so we have already got a length 4 but we will not stop we will continue in this substring it's again b is three times a is occurring two times so both are more than or equal to two k so we got a better answer five now if we include this c then c count is one so we cannot include this so in this case the answer will be 5 and this will be the corresponding substring we have to just return the length so i hope you understood this problem well now let's see how to approach this problem so we had already seen in both these examples that if any character occurs in between in this case if we are just looking at this part so any character which occurs less than k times in the complete string then the substring the answer cannot include that character since this character in the entire string is less than k so how come it be more than k in this smaller part of that string that's not possible so clearly those characters are dividing this string into smaller chunks we cannot include this so let's take a more generic statement so we have a long string and we what we did it's composed of just small english letters small a to small z and uh here we have taken count of all the characters all the unique characters maybe a was occurring five times b was a occurring three times c was occurring six times d was occurring four times and so on some characters may not be present and let's say our k is four so any substring which includes the characters which occur less than k times so first we will look which characters occur less than k times so clearly you can see that b is occurring just three times so none of the substrings would have b in it let's say b occurred here and maybe there are some other character let's say f was occurring two times and there is some f here and b here and let's assume that these are the b and f are the only characters which are occurring less than k times rest all characters are occurring more than or equal to k times now what we will do so we will see wherever we start from beginning so we check this character is occurring more than k times fine this character also when we reach here we see that we find it b or even if we had found f we would have stopped here so we know that none of the substring can include this so it cannot be possible that a substring starts in the left and ends in the right of b since b is occurring less than k times again i am repeating it again and again so that you realize that it's not a tough problem you may be intimidated in the beginning but it's not so whenever you find these characters you know that whatever is our solution will lie either in this part or from here till the next time we encounter one of these characters which are occurring less than three times so this is another part of this string and these all are cannot be included so where they end so it ends here and this is the third part so if we first count each character's occurrence then we do a linear scan from beginning till end then we divided this bigger string let's call it s into three parts s1 s2 and this one is s3 or more generally you don't need to look to the right of b also so first time you encounter such character this is s1 and consider everything else as s2 second part so you have we have break broken down s into s1 and s2 so you see we have broken the bigger problem into smaller problem so we are heading towards some solution so what we will do we will recursively call the same function whatever was the function let us call it longest sub string and it was taking s and ks parameter so we will again pass again called lss s1 this is the s1 so every character is occurring more than k times in the original string and we pass this k so this is the we are calling this recursively on this part so it will return something let's call it l1 and we will pass the second string also so l2 will be lss so we don't need to include this and we can further optimize to check till where we may have some characters like this in continuation so wherever they end just take the end of that so it ended here so take the next character and starting from here till the end consider everything as s2 so call it on s2 and k and now compare which is more so we return max of l1 and l2 so this should give you the idea this is the in fact solution uh we have missed some base cases but we will define that so what should be the base case would be that if k is more than s dot length then it's not possible even if all the characters are same still their count will be s dot length but we need more than that so we will return 0. so this is one of the base cases what is the other base case otherwise case could be that this length is itself 0 then also we will return 0 and what else if k is 0 then all characters are valid so we will take the entire substring if k is 1 then also we can take the entire string since each character is acting at least one time so in these two cases we return the entire string not length so these are two base cases and here we can do some early return we don't need to continue like this so maybe we started from beginning and we found a character like b in the end as the last character of this string so in that case what we will say that uh if we take this part of the string then all characters are occurring more than k times so just return this part of the string that is n minus 1 or n minus 2 or it may be possible that we did not encounter any such character then we return the complete string so we can add a check here so let's write the code for this and we will write it in c plus java and python also let's pause for a minute and analyze the time complexity so creating this count map from this string will take end time linear time we scan through it and keep incrementing the count of each character then what we do again we start from beginning do a linear scan the first time we encounter this we stop so it will be some so we are breaking it into two parts so this length may be n1 this length may be total length n minus n1 minus 1 at least if we found a character like this and we are passing this to again recursively to the next function so overall it will be some linear of the order of n only so overall it will be of n and a space we are using a map and map can be of maximum 26 size if all the characters are present so you can consider this as constant so space is constant now let's write the code so this is uh the problem there is not much to see here we have a couple of examples very similar to what we saw so i am storing it in a separate variable because we are using it many times so better to keep it in a variable so either string is empty or k is more than its length then we return 0 what was the other base case it was that if k is less than equal to 1 in that case all the characters are valid so we return n that is the length of the string then we keep an ordered map which will be care and int carries the character into the count and let's call it counts so counts map is now ready so we will define some index so let's call it l or equal to zero and while l less than n this is the bound check and counts s of l is more than or equal to k then we are good to go we keep going forward unless we hit a character which is occurring less than k times and after that we will add the check that if l is greater than equal to n minus 1 so it may be that we did not find any character whose count was less than k in that case this loop ended because we reached past the last character that is l was more than n minus 1 or even if we found the last character as the character which is occurring less than k times then we will return l so let's say the length of the string was 10 and only the 10th character which will be at a index of 9 if that is the mismatch we return 9 because first 9 characters are valid then we will call it on the substrings that we broke it into so in c plus was first is the starting index again is the length is l and k will remain same and we saw that there may be this may be b and then followed by a few more characters which are occurring less than uh k times maybe there is an f and followed by again b so just to reiterate through this unless we find the first character which is occurring more than k times and we will treat that part as s2 we can even start right after this that should work but that can take some extra time and we may exceed time limit so this is just kind of optimization not this is not required if the test cases are small and this is the second substring after that character and if we don't specify the second index it will go till the end of the string which we want here and we can add some more check here that if l is less than n then only do that otherwise if l becomes equal to n then this will be invalid this substring index will be invalid because it can be possible that we have this b and then after that all the characters are like that only which are occurring less than k times so this s2 will be empty so that's why we need this check that this index is valid otherwise ls2 is simply zero because the substring length is itself zero and then we take which is the maximum left substring or right substring this will again further call break it into a smaller substrings if required so let's run okay if and this works for this case so we will submit i don't know why it's taking too much time and it works so it took eight milliseconds i don't know why it was spinning like that now let's and it's better than 56.8 you now let's and it's better than 56.8 you now let's and it's better than 56.8 you can try it a few times this is still quite a small time it can fluctuate a bit so let's write this in java and python so if this is being inserted for the first time then it will not be present so get our default so if it's present you see otherwise the default value will be 0 and add 1 to it and this way we have the counts map ready now this is fine and here it will be get and s dot care at and here it's substring and first index last index one more than last index so it's very valid and so the java solution is also accepted and this one is even better it's done in one millisecond and it's better than 82.50 better than 82.50 better than 82.50 of the accepted submissions so we are making some progress without making any change in the logic finally we will do it in python 3. and here it's very easy in this thing i like our python and we are done and it's also easy here and here it takes 40 milliseconds and this time 36 milliseconds so it's better than 75 and this time 32 milliseconds so it's decreasing and it has reached very close to 90 in terms of time and space
Longest Substring with At Least K Repeating Characters
longest-substring-with-at-least-k-repeating-characters
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`. **Example 1:** **Input:** s = "aaabb ", k = 3 **Output:** 3 **Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times. **Example 2:** **Input:** s = "ababbc ", k = 2 **Output:** 5 **Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 105`
null
Hash Table,String,Divide and Conquer,Sliding Window
Medium
2140,2209
72
Do it Hello ji How all missions Love breakup Attendant Help Today we are going to solve a very asked question of Deep Conference - very asked question of Deep Conference - very asked question of Deep Conference - Edit Distance, so let's quickly see what happens in this question and then we will solve it quickly. Okay, so the question comes, I will give you two increases, I will give you two in the building, the question said, I will give you two words in the install, one and yours, world one is done, the second is your battu, okay, these are springs, okay so. I said that the value you have here is the one from which and the next value is ROS, it is ok, you can do three operations, you can insult any character, you can delete any character and any person. And I have tried to do this by deleting all the breads, two requests will be made, but if I replace them, it will cost one, so you have to pay the minimum number of operations equal to convert to top, so any ribbon of yours, this category. You have to convert it into wards, this is the operation you have to do, then you have to do the work of minimum number of operations, look carefully here, I have to convert this into charges, okay, one by one. One way of doing this is that I converted it to a different one, so it went to RAC to check it in the match, so I cut it into two, deleted the Hello SG reminder, deleted the reminder that operation should be done one over here One here, within four operations, you converted the horse into a charge. Sister operation, which was the first operation which was your replacement, second operation which was also your replacement and the remaining two operations which are dated from being in your favorite list. The question is, okay, then you do four operations, this is a solution, but is this minimum number operational? Yes, no, this is not the minimum number of operations at all, so how will you ask a question, brother, you will cancel, you will ask such a question, see, we do yours, we said. That we have h.or in the input we said. That we have h.or in the input we said. That we have h.or in the input we need and that is this so I have done the first question and replaced it I am with you so I have replaced this and put it here now make up your singh mangi allegation r&amp;b so match with this By doing very good, r&amp;b so match with this By doing very good, r&amp;b so match with this By doing very good, I have deleted it, deleted history is gone, okay, I have deleted it, I have solved and converted it through three operations, subscribe, I must have done any You need it, I am standing here on someone, this is mine, please place me on someone here, no problem, you have put forward the strings for the inaugural match, now you have called in five to solve this train, but the test match. No, you may have to set it there, may have to delete and replace, and whatever MS Eminem tears I saw, I will take it. The minute I said this, if the characters match, what do you do? So what do you do, if you call then call for the ministry, next child who is in this trick, you will shed tears for both of them, you will check the knowledge, okay but if they do not match, if the current character does not match, then one of your By insulting you will get bamboo. By insulting you will get cancer. By deleting you will get fight. If you deleted the control then France would have come out 18 years ago. If you had replaced the left by replacing then you would have done all three 249 and see what is the answer. This is coming from delete answer 11 replace answer yaara I don't want my final answer what will be my final answer here is it from my penis or these three brother of minimum of insult dancer and replace answer is finish That's all the solution, if you think about this request, power work becomes easy, I will not make you do anything extra, we have forgotten the quarters of two strains, meaning, are both these actors equal, do you match this and then do that match, okay? So the next string of both of them is from example late that this was your H.O.R.A.C but this was H.O.S. So I H.O.R.A.C but this was H.O.S. So I H.O.R.A.C but this was H.O.S. So I said, I am standing on the space, let me make it clear by matching both of them, then I said, now this is just the further stuffing. Get this train checked and make it on Strangers [ __ ]. train checked and make it on Strangers [ __ ]. train checked and make it on Strangers [ __ ]. If it was me, but if there is no match in the case i.e. If it was me, but if there is no match in the case i.e. If it was me, but if there is no match in the case i.e. this is the RAC and this allegation is like this i.e. this and this is the mechanic, then allegation is like this i.e. this and this is the mechanic, then allegation is like this i.e. this and this is the mechanic, then what if it happens, then do the install operation. Lo, you install operation, what happens with operation, it becomes G R H O R S Chief and it becomes R O S T. If you do this then you are solving it and then fold it or delete the second option read. Do life place and such and this is RO address proof Saurabh, okay replace it, please add it now it has become RSP and this was done by the accused, what kind of correction do we need from these three, what answers do we need which I You need that answer because he said, I will do it from here, okay let's fold it once and try to understand, then I said, do it brother, I will end the functions in solve and pass my weight and he will talk to me. From where to do 60, I am starting from 0, so I said, end solve, this has come, I will take the wrist, this is the next one, I will also restrain and this has come and this is 6, so we have understood this thing, this is what Prem has passed. Given and these two, we pass the indexes, now SK has 20 pieces, what will happen, I have made it very simple that suppose your eye is not landscape and it means that your first spring is over. Okay, so once you understand this. It will be understood, let's say there is this type of string here, your I also passed I believed but I got out of the first spring i.e. I it is out of the first spring i.e. I it is out of the first spring i.e. I it is already what does it mean it means it is shortened in these times of people this allegation And this is the RAC, so you first come first serve, after this, fry this and this, then you did this, then you went out here, the main festival here is over, so when I say your I, be the first dot lens icon. The length of Gaye in Support of World One was short, the length of two has to be done in this way, there is a much simpler answer than this, look carefully, send us these two fanatics that will be given by setting vigilance, then it always means what will be my answer here? Always full of this attitude here, this is full, this is also length 8 - - where his G stands, 8 - - where his G stands, 8 - - where his G stands, where his J-10 does, also where his J-10 does, also where his J-10 does, also depends on the praise, here you have changed 5 - 3 tats If you go to train video, if an you have changed 5 - 3 tats If you go to train video, if an you have changed 5 - 3 tats If you go to train video, if an incident happens then I will answer either my answer will be B dot lunch is 8 - Jeet If it seems confusing then there is a - Jeet If it seems confusing then there is a - Jeet If it seems confusing then there is a way to solve this question If you do not understand this then how we also That this is how we organized the test of the year and this was how we started, so put it here and put it here, I have a method, instead of doing this, I am going to call the question on this. I have done it, but what did I say here? What did I say here that I am here and it is like this but here I have sounded the alarm and I have also sounded the alarm to others, thus I have set out to solve it, if you solve it in this way, then your son How will it be made, instead of return you will get a simple return here, yes, it is ok, but we started a machine, so we will be folded in this way, all around you and then your wish is internal, I want to say in it that when yours came first lead. If it happens to a girl, that is, if our princess comes, then go out, your world one and two, the rest was small, in these terms of plan, whoever your extra fanatics settle in, how will your homework account be run, there will be a competition for them, you will be supplying the team. Same on Ajay, if we assume that he is equal to B.Com, he is equal to B.Com, he is equal to B.Com, what does this mean, it means that he is two smaller than Warden in terms of cent, then here also there will be extra characters like this forward 152 small. Whatever the title song is, it will be from the hardcore bhaiya shop, the focus will be the same s dot length - I same s dot length - I same s dot length - I understand that you have made it your call that in this way you have handed it over and got it ready, how is it okay? Now I have taken my answer here. Shri 420 What was my condition, do my current characters match, is one off physical 222 is also 4G, if it matches, then if you talk, call ahead, return the function, brother, so always be mother, life is also ahead. Increase it and check that you will have to try matching the results of both the matches. I will also have to increase it. If all the mails do not match then what to do. Then you can do three things. You can select these three things here and delete them. And you can replace it, I am very strict, so I found out the answer inside thumb in short answer, you have insulted someone's position by being late, you have insulted someone's position, for thinking once, the actress does not want to interest you are small that You used to set pin here extra here was that here or was this permanent 2012 MP3 then this is here late you said that I have insulted here so any sort in short you If I insulted here then on install this character matched with the scooter. You have to bring it to Earthquake. Now I have to compare this entire string with this entire team. If you think carefully, yes, mine was here and mine was here. What was here is still here, my interest is where it was before, but what is mine has moved ahead, so I have to do the same thing on the same thing, this solution was given to a common man by making fun of my mother, then I took the digit of the second. Digit answer has been taken out, delete answer is how to do it, Manorath is fine, where are you now, you are standing at HP now, from the RAC ROS letter, I said that mine is here and this is what it is here, I said that I deleted it, I edited it means I will contact this train completely, see, it is sending mine there, but what is mine has come here, so I come here, neither is its sum. I mean, you have moved ahead, but I am okay with replacing a common man with my plus one. I said, I will do this also, brother, I have done this much, this is also correct. Will you leave the prince and see who will be in your place? You said this. This is a festival which has been changed by replacing the meaning of 'Yes' and ' This is a festival which has been changed by replacing the meaning of 'Yes' and ' This is a festival which has been changed by replacing the meaning of 'Yes' and ' Ok, here was my Aai and was sitting here, now what do I have to do, I have to complete this train, look with this Aai, one of mine has moved ahead and this too is one of mine. Snowfall has moved forward, an innovative you have forced the garlic to come out of the name, I am the final answer's, this is mine, you all's or minimum of institute answer, kill the minimum of delete answer, replace answer is fine and you return the answer here. When we finished preparing the pakodas, we did it and she said, it's on you, this is the bungalow of A's rocket, Babu Bhaiya, we made it run, I made it run, the answer to the hot love question is wrong, why, because we did, I said that I did an operation. I have taken this, neither will I have to use it here, nor will I have to search here, will have to do it here, now let's scrub it got affected by the color, we have collected it because if there is a question, then the possibility of coming to Delhi is very high, let's see our reality. Okay, now the question arises that the other person is going from yours to yours and this is our first work, you have celebrated the work of Dot here and there, after this send it to all the function halls. Brother, solved lifting and sent it to me, you will have to write here above also, so you have copied it from here and have written it here and you will pass all this function to the executive, you have made it DPCO Deputy Chief Free First Chapter. After passing all its function colleges, its permit was given by Ravi Shankar very good, what happens often, wherever, by putting the answer and softening it in Delhi, the Deputy Chief of Army Chief, the question whose answer is correct, it is fine, front chup 20 is ending there. If the answer is difficult then the answer is already present. If the answer is all different in Deputy Hey, then return the same to you. It is not for the next process. I said, it is absolutely right, Congress has tried it once. Tried and checked, it is not working, we have submitted it, we have got this question solved by the top-down tp.is submitted it, we have got this question solved by the top-down tp.is submitted it, we have got this question solved by the top-down tp.is present in your sequence, very good questions, all the top notifications have been done, but can the bottom of this be done by the guest, absolutely not. Whose friends, if you look carefully here, inside this question, you have taken from zero to one lunch of what you got in Top Dondi, I said absolutely right, if you look at this, then I have taken it from interest rates also, Akhilesh sir. Said absolutely right, if I have to do bottom approach or not, tablet Amit Aggarwal, to ask that question, then come, I will take the cord, brother, egg dot length - I will be connected to the mind and will brother, egg dot length - I will be connected to the mind and will brother, egg dot length - I will be connected to the mind and will also take the check, don't length - 101, then also take the check, don't length - 101, then also take the check, don't length - 101, then solve the tick. Once I said yes. Enter solve tab and you said, what are we passing here friend, I am passing the time too, first of all what is the support, I am DP, wow PR, I have quickly copied it from here and pasted it here, this company is SpiceJet Zero. Along with this, its name is this and its name is also okay, this thing is understood, okay, understood, this thing is understood, okay, what to do about it, advise us one more thing after looking at the 20th part of the solution. It happens that whether there is any change request in the DPR or not, then I will keep in mind that I is equal to a great length changes also i.e. i.e. i.e. absolute , your answer should absolute , your answer should absolute , your answer should be like this - By now it be like this - By now it be like this - By now it can be anywhere, you can put it here Which will be the points available to them in 2006 B.Sc. In B.Sc. In this way, you must have put a loop and you said, brother, tell me, IG has given S dot length form of DNA test and what do we have to do on this prison column of yours. We have to give this answer B. Dot Print - If you want, then how did you know the base, Print - If you want, then how did you know the base, Print - If you want, then how did you know the base, very good, but what happened brother, you hurt me so much, this only means item explanation, investment - add and access points here on force. investment - add and access points here on force. investment - add and access points here on force. To do this, it gets the meaning and here we will have to request Bible and here also we will do it. It is okay here because the secondary will be believed. Our test match can be done whenever your column will be of dance i.e. column of dot length. column will be of dance i.e. column of dot length. column will be of dance i.e. column of dot length. But you should be surprised Same means your again people started and introducing idols in a dot land coming out of eye plus again and again what to do this tomorrow DP of eye and your wife daughter selected at random you have to enter answer or description Tatva B.Sc Moon Answer: This is going to be description Tatva B.Sc Moon Answer: This is going to be description Tatva B.Sc Moon Answer: This is going to be very good, so you have understood this thing, by liking the base, basic is dependent here, what to do after this, in which you were told that inside the bottom up DGP, like this Your value is going to go so you said point your request uh don't length belt length - 134 let belt length - 134 let belt length - 134 let go to 2nd floor and - - A go to 2nd floor and - - A go to 2nd floor and - - A Luta I said this point J is equal to B dot length a minus one J Girdhar in record 20 - - a minus one J Girdhar in record 20 - - a minus one J Girdhar in record 20 - - Finish, what should be the rally inside, what logic should be written inside, I said simple brother, I have written on this and copy pasted it here, you copy pasted it here, okay, so it will be my job to convert it here, so I said yes, this Plus one plus one here, so I called this function once. I called this function, added the runs and let's see. Time did not pass. Then something went wrong. Then we have to point out that problem. Let us understand what is wrong. So, we went up to find the problem. We are Tractor Operator of NDPL Plus One Left B.Com Plus 1020. From Z to Plus, this is how you updated it, war, this way, and this is how you updated this also, this - 101 from now to fall 20 - is exactly the right answer, the now to fall 20 - is exactly the right answer, the now to fall 20 - is exactly the right answer, the purpose is this, you compared this, the answer should be returned and In the case against, extracting its answer, extracting its juice, extracting this rule, toeing the answers and putting this answer, correct mistake, here, we have returned it here, we have to answer it here and did it Let's do it, now we do it, we kidnap the friend, thank you or there is no issue, from here you know what I did, if it is, then I return you that we are ok, it's going well, we submitted, so we submit. Given this and in this way we can also subscribe to this channel, subscribe, that is, here and B.Com and subscribe, like and B.Com and subscribe, like and B.Com and subscribe, like you can do a current, which is basically what will happen, will be of this loot. And we will do a little with this, similarly you have created another one, its name will be next because depending on depression, wi-fi because depending on depression, wi-fi because depending on depression, wi-fi opposition shown current and DP five plus one hero angle chemical maybe okay now it is not for this okay so here. Change this entire scissor course, you will handle the entire Mahalaya course, you will do this also, okay, I will take two, let's move ahead, all this is okay, absolutely okay friends, five plus one means next day, EPFI means current. Chief i plus one means next deposit plus one means next 9 deposit means current track know hydration descent is controlled this and you will get dip in many videos in the last key videos right here inside this i tell you completely comfort and you Next we will fit Khusro Okay, this was all easy Sara's is here Sara's Sara is here how to handle this How to do this honey I said it is very simple I said very simple look carefully now you do What are you, I said that this column has run a loop, let's look carefully, Rusal should go to your column, that the column has run a loop, you said adult length Rupert, meaning in the darkest, how much total provide, dot length in the beginning, as a result, rural tight, if I tell him. That total, we must have made these pictures, so the index of Emperor will be Dahan of Kayamganj, so it is showing the last, so if I talk about current on Ghaghra and next, then it happens like this. What I say, I do, we have written this, so you said next look at this, what you have written is that this answer has to be given on this in every RAW, here the question is that here in this whole world The most important of every RAW, give this answer on this one, you are very embarrassed too, you are the first one, your cameras cylinder, guava, TBI, reconnaissance, daily tight, so you, what is an international current and I am here, okay, what happens in the next test. Current is stuck above and next is stuck here. Things work with this Advani, so he said that on every day's B.Ed so he said that on every day's B.Ed so he said that on every day's B.Ed entrance, this is the last next class, that is, for every day, this is only yours, this is a disease, this is This disease is a disease. Your answer is on everyone's last stand. I want your answer in everyone's last element - want your answer in everyone's last element - want your answer in everyone's last element - So you guys, your B.A.D should be B.A.D should be B.A.D should be there - there - there - it should be there, it is the entire coat and pants that you have removed from the country. Have you brought me once or twice, understood the Quran, tried to enter the birthday front so that we can optimize on it first and the medicine is free to you, Reddy, yours is only minimum of and kill MRP, okay, what is it, I don't length. He does n't know what DPI is. Okay, I have to remove it on line number 34. Friends, I have kept it running now, after all I had updated the Chola Room app, we submitted it but we saw that the answer came and asked why is it so? Brother, why can't there be something wrong in the code? There ca n't be something wrong. You have written the connecting function. It is written correctly. Kiran has taken out the next one. This was written by the SDO of the country in the development of the country. The first one was written in the development of the country. After this debate, we wrote this one. We wrote the one for people and we found out that this is our extreme most extremely important. In this, what you read is that our Praan solution, it was written there that in every disease, after the index of B.Com, of the clans are important index of B.Com, of the clans are important index of B.Com, of the clans are important - I would have seen it. We have updated it here. Yes, - I would have seen it. We have updated it here. Yes, - I would have seen it. We have updated it here. Yes, okay, why is this our wrong answer? This is what could be done in the case, your wards will be examined, the plate is ABCD here, MT is big here, so I guess I will have to insert the name of, I will have to do the beans, I will have to do the confidence, these are the four questions, the astrological secret was opened, same case, back to Varsha, you said that How can this word of AR Rahman be one daughter in law that if RICO surgical strike is zero then I will be the prince of Ramsar, the world does not drink or should I say if the record of Heart to the link returns 000 then mode on daughter in law. Now try running it, run it in friendly manner and see if it is accepted, submit it once and see if it is successful, so in this way, I wrote this question in the most optimized solution, where what is your time complexity? Ambrose m&amp;p what is your time complexity? Ambrose m&amp;p what is your time complexity? Ambrose m&amp;p Spring Balance MP3 Spring Balance Press Complex The minerals of these two can be asked in your press quantity in this effort, both the plants song that if you sit directly to write this code then yes means I tell you son Marg's record from here After those people, convert it into a tablet while taking a bath, then inside the type solution, you will find that payment is impossible, but if yes, then again and then match, then friends, if you know retail marketing, then explain it to the customer, if this You will solve eight level questions and will understand the video. They will understand 99% of the translation. understand the video. They will understand 99% of the translation. understand the video. They will understand 99% of the translation. Like and comment on this video. Subscribe and share the channel with other children. You can do this much. So we can do it by sitting at night around 02:33 campus I sitting at night around 02:33 campus I sitting at night around 02:33 campus I can submit it so you can do this much thanks see you in the next video till then
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
128
Hello Hi Friends Welcome Back To Go Into Solitude Problem 120 Four Longs For Executive Sequence Are You Front Subscribe Order To My Channel Please subscribe My Channel I Have Lots Of Good Playlist This Interview For Java Admin Please Give Up Eating For A Telephonic And White Gold Code Interviews A Play List The Play List And Please subscribe The Channel So Let's Look Into This Problem Details Forgiveness And Solidarity Name Of Winters Find Limb Longs For Executive Element Sequence Pure Algorithm Shoot Run In Order Of And Complexity And Links Of Numbers Is 1000 So will have maximum 1000 elements and number servi and have to our algorithm shoot running shoulder off in right the modern 512 find the longest conservative sequence side 100th post thought comes into the mind which was not to just light which you should be win-win which was not to just light which you should be win-win which was not to just light which you should be win-win Justin to the solidarity goti consecutive numbers of sequence right and will be to front positive sequence in solidarity but as you see this condition you know how to find the solution parents in oy android shoulder off and complexity now when you are sorting garre defective soft you can You Please Like Mer Should Work Hard With Sister In Law Android Sweeties More Than What Is Expected In The Answer To Have To Find Out Sambhal Gori Dum And We Have To You Contemporary Of External Data Structure That Will Help To Implement This Algorithm In No Any Time Complexity night so let's statement example over here and they can yes this notification implement this pollution in the end complexity right so common member given to that for example solve will be using state should be used and withdraw this here end wish to avoid numbers in awards and Right Solid Say This Is The Worst So I Will Store Numbers Clear That New Year Set 60 Here Deonar Will Wither The Soldiers Give 120 Will Wither Days 321 That Woman And 210 Water Works At Witch Contents That Choice Its Justice Order Of These In Thee To You Stood Up and go to all the values in the satellite and in what we will do is unknown width purpose yes are ones and will return for example will get this hard number oldest son will take medicine at number and will tried to check if you have any Value Which App Connects Quantity Value Right Sohn Do You Will Get Din Ubal Tried To Give One Is There In To Our Seth Saunf Andher In To Our Set Show Which Give 125 Longs For Executive Sequence To Wheeler Final Tried To Find Out Which Will Not Find Out Elephant With Folder Maximum Variable Here Right Swar Maximum Valley When Will Store The Longest Born In Active Sequence Length You Have Seen So Far And Son Of King How To Connect With Just One Because They Do Not Have Any Positive Number 120 Will Go To The Next Number Nine Ek Number Hui Hai 400 I Will Take For That And They Will Strive To Check If You Have Any Which Guddu Number Clear Life Is There In Our Set Subha Will Not Find Any Five Years Will Just And Experiment One Right Because You Will Not Be Getting Enough Without Number Brightness So Similarly E Will Go And Will Check 420 406 420 Which Coating Element And Number Were Trying To Find Out Which 2018 Solvent Right To Check Your Website Contents 2013 Doesn't Contain 2010 Then And Mix Will Be Given Rise to power max is descent that is what we have found maximum for now sun will go on and built after now you are visiting number one right choice that is what we have found out Find out here next positive servi again tried to find out next free source servi again tried to find out next quantity which comes under forest officers also clear and you will now try to find out which code number 5.25 is not clear so What we will do it 5.25 is not clear so What we will do it 5.25 is not clear so What we will do it is this number five that 2.5 minus one means is this number five that 2.5 minus one means is this number five that 2.5 minus one means basically hui tax department - Vansh and basically hui tax department - Vansh and basically hui tax department - Vansh and this is basically will give his mother length of our khan executive sequence which give will updater and max pro m1 will spread twist French 20 round updater max Mueller Platform THE IN THE CITY 100 OUR LINK FOR THE SEQUENCE RIGHT NOW HIS FIVE - 3 WHICH E THE SEQUENCE RIGHT NOW HIS FIVE - 3 WHICH E THE SEQUENCE RIGHT NOW HIS FIVE - 3 WHICH E REQUEST U RIGHT CHHOTU IS NOT GREATER NOIDA AND MAXIMUM LINK FOR THE TO FIND A PREVIOUSLY IT SO I WILL NOT UPDATE MAX NA HU WILL GO TO THE 2538 ANSUAN Too Novel Tried To Find Out Next Tours Is There In The Right Clear And You Will Find Chand 600 800 60 F H Not Here In The Way Calculating Languages ​​Including Five - Calculating Languages ​​Including Five - Calculating Languages ​​Including Five - 2123 You Can See Putri And Which Two Three Four Link Ki Stree Raees Ko Cut Will Not Late V Mexico And Maxis Mordhan Length And Width Sharing Will Return Khabar Max Shoes For Rights For Is The Answer Swain Seervi Output For This Is For Beginners For Is The Maximum Quantity Sequence You Have Found So Let's Look Into The Details Of The Implementation Data a plate already to you so much hui creator mac variable 201 check this initial check gift and name bath side 0.8 at cent will create set which is the 0.8 at cent will create set which is the 0.8 at cent will create set which is the state of teachers and will oo through the number and will have to the she tried so is Vansh volume actually viewers order of individuals were looking through all the numbers from right to left and now they have another followed this is also available in this is also going to give shoulder of a 100 total complexities for the solution is going to be order of in which is The Largest In The Question Bhai Sun Will Just Looked Into The Haddi Chalu Song Again They Are Going To Lootere Of Numbers And Will Just Create Like Waves In Next Equal To Our Reason Number Current Nam And You Will Check On In The City As Long As They Contains the next element belief in preventing next for example in case of one first next nuvve check for two things will change for free in which aims for below will check 5.32 is planned stir with lots of things 5.32 is planned stir with lots of things 5.32 is planned stir with lots of things alive 1234 510 what they are doing year buddy In Preventing the Next 100 Wars Basically Checking Which Protein Sequence Length Was Right and Which Sequence and Lag Hui Calculator That Is - Number Hui and Link Fauji Cutting Is - Number Hui and Link Fauji Cutting Is - Number Hui and Link Fauji Cutting Sequence and Will Always Keep Updating Our Max a Long as They Find a Better Life long a sequence I will keep updating and inventors return max 100 we let me just you on this is the so let's check the test data time data enemy se example will take and will smith and chords running point from this is because of this witch This is the way you can solve the longest positive sequence problem by coming in order of. Complexity Solve This Problem In But Login Using Priority Queue And If Options Much Easier Birthday Idea Is To Find Out To Any Related Entries You Know You Have To Same To You Have To Find Out Which Quoting Sequence Length Like This Is Don't Hear His Work Is Thought At Its Work Sharing It With Your Eyes Not So You Will Also Know How To Find The Longest Porn Tube Stream That Common Number So Common If You Haven't Already Subscribe To My Channel Please subscribe to the Channel Now My Channel Is That Sort Of A Interview Coding Related Solutions S Well S Java J2ee Related And Interview Relax Related Videos In No Way Discuss Vinash Me Electronic Configuration Questions And How To Answer Questions In Telephonic Interview Say And Drop Ideas Like Wild Fire Shot Questions For Job Listed Out And Subscribe The Channel thanks for watching video
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. **Example 2:** **Input:** nums = \[0,3,7,2,5,8,4,6,0,1\] **Output:** 9 **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Union Find
Medium
298,2278
30
hi everyone let's have the code 30 substring with concatenation of our words um it's a hard problem but there are a lot sometimes actually since um it's not easy to code elegantly but personally i like this problem since uh it's something like a sliding window problem okay let's take a look at problem so we are given string as an array of string words of the same length we need to return all starting indexes of substrings as such as a concatenation of each word in this word except once in any order so for example zero we have bar four now we have four bar okay so one if solution for this problem is um like we just try every starting indexes and process starting indexes we just try to match the word like in this words yes it works but it's kind of slow as i mentioned previously it's like a sliding window problem so we can process index 0 3 6 9 first then in the second run we test 1 4 7 10 and so on and in still run we test 2 5 8 11 and so on okay so first we test index zero three six nine and so on and we have two pointer i enjoy is slow pointer through its first pointer and we have map here we just follow each word in this words and increment as long as we say a word and we also have so count here so count means in current sliding window how many valid words i have for example if country 3 which means it's same as the word lens and settings a sliding window i have all the words in this words that's a valid and substring okay let's start so first for tree we have what bar then we just consume this bar we eat this bar so bar is like in the map we eat this but we consume the one bar here so the currency from unlike one to zero since we eat it we consume it which means we consume one use forward so my account becomes one then i eat a four also um becomes zero from one like from one to zero then my count is two next i it's one more four like becomes negative one which means like i x or i like i consumed um unnecessary or redundant word so we don't need to change count here now it next way is bar also becomes negative one at this point we know in this sliding window we have four words so we need to pop one word so we start to move index i so the word is back here we just pop this bar so the bias are from negative one to zero which means we pop unnecessary bar so the count also does not change here then we consume this third c becomes zero so count is becomes like three then here we pop a four becomes zero like from negative one now we as conscious three which is same as what's this the size so we just push current i into our answer i six next we consume 4 but we pop 4 so counting still 3 we push 9 next we hit bar and we pop bar we push 12 next we eat a man so man becomes negative one but it does not change my count then i need to pop the word at index i it's the thi becomes one which means we pop a used forward so continue to decrease by one count becomes two and then now the iteration finished then we can start use the we can use the same method to try index one and two and finally we can just return our answer okay let's take a look at the implementation first way defines the local variable result and return result at the end okay and this is my dictionary to contain the like count occurrence of the word and we have some variable here first we just iterate each word in my words and update my dictionary okay as i mentioned first we need to try index 0 3 6 9 then we start trying index 1. at last we try index two so here is a for loop for each uh specified index i like we maintain a local variable count and we copy this dictionary to my copy since i need to update my dictionary in my for loop so i just copied here and update my local copy okay next and this is the first pointer so initiatory string we just move this first pointer and we get the control word like in this first pointer and we update the local copy if after the update the value is still greater or equal than 0 which means we consumed a useful word so count plus then we try to say if we need to pop a word then we get what we need to pop then we update our local copy if after on the update the value is greater than zero which means we popped a useful word so con minus at the end if count is same as m is what's the size which means this substring is the value substring so i just push back my starting index okay here i only have a first pointer i don't have a slow pointer this i is not still pointer since i just to specify we need to like first we need to process index 0 say 1 and two it's not just a stop pointer so here i don't have an explicit slope pointer since for this sliding window it's a fixed lens sliding window so for this pop start there is a way to calculate the slow pointer from the first pointer since it's fixed length okay what's time complexity here assume any extra length and wl is length of each word says them complexity since we visit each index at most twice you know we have five pointer and a slow pointer so we visit each index at most twice and for each index we may use substring or and we may like update the data structure of uh hashmap okay so this is time complexity yes that's it so i personally think it's a good problem and there are many methodology and metrics we can apply and learn from this question okay that's it thanks
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**. A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated. * For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abefcd "`, `"cdabef "`, `"cdefab "`, `"efabcd "`, and `"efcdab "` are all concatenated strings. `"acdbef "` is not a concatenated substring because it is not the concatenation of any permutation of `words`. Return _the starting indices of all the concatenated substrings in_ `s`. You can return the answer in **any order**. **Example 1:** **Input:** s = "barfoothefoobarman ", words = \[ "foo ", "bar "\] **Output:** \[0,9\] **Explanation:** Since words.length == 2 and words\[i\].length == 3, the concatenated substring has to be of length 6. The substring starting at 0 is "barfoo ". It is the concatenation of \[ "bar ", "foo "\] which is a permutation of words. The substring starting at 9 is "foobar ". It is the concatenation of \[ "foo ", "bar "\] which is a permutation of words. The output order does not matter. Returning \[9,0\] is fine too. **Example 2:** **Input:** s = "wordgoodgoodgoodbestword ", words = \[ "word ", "good ", "best ", "word "\] **Output:** \[\] **Explanation:** Since words.length == 4 and words\[i\].length == 4, the concatenated substring has to be of length 16. There is no substring of length 16 is s that is equal to the concatenation of any permutation of words. We return an empty array. **Example 3:** **Input:** s = "barfoofoobarthefoobarman ", words = \[ "bar ", "foo ", "the "\] **Output:** \[6,9,12\] **Explanation:** Since words.length == 3 and words\[i\].length == 3, the concatenated substring has to be of length 9. The substring starting at 6 is "foobarthe ". It is the concatenation of \[ "foo ", "bar ", "the "\] which is a permutation of words. The substring starting at 9 is "barthefoo ". It is the concatenation of \[ "bar ", "the ", "foo "\] which is a permutation of words. The substring starting at 12 is "thefoobar ". It is the concatenation of \[ "the ", "foo ", "bar "\] which is a permutation of words. **Constraints:** * `1 <= s.length <= 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 30` * `s` and `words[i]` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Hard
76
1,979
hey welcome guys welcome to my equals section so this problem is 1 9 17 find queries comma divisor array so given the array we can equate this comma divisor smallest number and not just a number in the numbers so basically uh yeah i think everyone knows about where this karma divisor so this is the uh the standard approach so basically it's the uk the algorithm if they are the same within a otherwise you just a equals a minus b and a b equals to b minus a okay so if equation and b then a will be smaller and b will be smaller and uh and you take the mean and the maximum they return this that's the greatest common device yeah so very straightforward okay that's it see you guys next videos
Find Greatest Common Divisor of Array
maximum-number-of-people-that-can-be-caught-in-tag
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** The smallest number in nums is 2. The largest number in nums is 10. The greatest common divisor of 2 and 10 is 2. **Example 2:** **Input:** nums = \[7,5,6,8,3\] **Output:** 1 **Explanation:** The smallest number in nums is 3. The largest number in nums is 8. The greatest common divisor of 3 and 8 is 1. **Example 3:** **Input:** nums = \[3,3\] **Output:** 3 **Explanation:** The smallest number in nums is 3. The largest number in nums is 3. The greatest common divisor of 3 and 3 is 3. **Constraints:** * `2 <= nums.length <= 1000` * `1 <= nums[i] <= 1000`
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not "it" cannot be caught, and the person who is not "it" is on the left of the person who is "it", find the next leftmost person who is not "it". If the person who is not "it" cannot be caught, and the person who is "it" is on the left of the person who is not "it", find the next leftmost person who is "it".
Array,Greedy
Medium
2191
219
welcome back everyone we're gonna be solving leeco 219 contains duplicate 2. so we're given an integer array called nums and an integer K we want to return true if there are two distinct indices I and J in the array such that nums at the ith position is equal to nums at the jth position and the absolute value of I minus J is less than or equal to K so we can solve this with a hash map and we will say mapping will be equal to a dictionary so let's take a look at example one returns true right at index 0 we have a one and at index three we also have a one right so zero minus three the absolute value of that is going to be three right that Which is less than or equal to the K so we return true so what we're going to do is we're gonna Loop through our original array and we are going to get the enumeration so the index and the value what we're going to do is if that value is already in our mapping then we can return the uh index at that value minus the index that we're currently at otherwise we're just going to add the value to our dictionary along with the index so what's that going to look like that is going to look like this so for index value in enumerate nums if that value is in our mapping that means we have two distinct um two distinct indices which contain the same value so we need to check if their absolute value if the difference of the absolute value is less than or equal to K so we'll say if V isn't mapping we need to say if I minus mapping of V is less than or equal to K we will return true otherwise if it's not in there then we can add mapping V is going to be equal to our current index and then if we ever exit this Loop it means we have not found a pair of indices which satisfies our conditions so we can just do a latent return false so let's get rid of some spaces and run this and we can see we pass all three test cases we'll submit and it does Pass Perfect so what is the runtime of this is going to be o of n right we're only doing one pass through our original array and no doing some checks for uh the difference between uh some values right so our time complexity is going to be o of N and the space complexity is going to be o of n in this case right it's going to be based off the length of our mapping so we can say o of mapping dot length
Contains Duplicate II
contains-duplicate-ii
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`. **Example 1:** **Input:** nums = \[1,2,3,1\], k = 3 **Output:** true **Example 2:** **Input:** nums = \[1,0,1,1\], k = 1 **Output:** true **Example 3:** **Input:** nums = \[1,2,3,1,2,3\], k = 2 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `0 <= k <= 105`
null
Array,Hash Table,Sliding Window
Easy
217,220
1,090
so for this problem you are given a set of n item and then you're given two integer arrays values and labels and they are used to store the first arrays used to store the value of the item and the second array is used to store the label of that item so it's a case where the ith element of values I and labels I used to store the value and the label of that item and then you're given two extra integers num wanted and use limit so what you're asked to do is you're supposed to create a subset from the N items by the number of items inside of that subset is always lesser than or equal to num wanted and since you're taking values from them you should ensure that so if two labels are the same the use limit specifies that a maximum number of values that could be in the subset that belong to the same label and you're supposed to return the maximum score that could be for the subset um so yeah it sounds a mouthful but actually it's pretty simple essentially they're asking us to create a maximum subset and they're given some restrictions so this problem is categorized as a common Google coding interview question and I think the reason they make it ambiguous is to hopefully you know to make sure the person or candidate is able to you know have some technical understanding of the problem where he takes down notes asks clarifying questions and based on the feedback is make able to make adjustments to the problem um so you have to understand it here they've given us a few examples so given these two integer array the first array represents the values and the second is the labels so they're specified that the num model is three so you need to create a sub array with a maximum size is three and the use limit is one which means that items which have the same label so here is the case where 5 and 4 have the label one so we can pick only one item from each so since it's one we just save five so that's a maximum item similarly here we have three and two have the same label we pick three and then finally from the we pick one because that's only one available with the label three um so yeah we calculate that the maximum value that could be achieved is nine so yeah let's try uh so given this problem the best solution always involves using a priority queue data structure so the advantage of that data structure is that it ensures all the values um the maximum value will be saved at the top of the queue and all insertion deletion operation take place in login time so it's easy for us to have given a restriction we can easily achieve which is the top uh you know the maximum K items um so yeah we'll just add a data structure and we'll use another data structure a hash map so hash map the advantages it has constant lookup time and since they're giving us a restriction that items to the same label they cannot exceed the use limit we can use that map to keep track of how many times we're using the item given that same label um so yeah let's try coding the solution first we'll uh create a the hash map and Prodigy data structure so cash so this one is just to keep a count of how many values belonging to the same label is being added to the result next the queue so here we are seeing the argument will be an integer array this is because I think now we are going to create uh retrieve the values from these two integer arrays and save them there we say PQ is equal to new foreign so we'll add the label and then we'll set the count to zero and then we'll add the values to the priority queue data structures so we just say values I um and I guess and now we'll Define what's the manner in which we are going to sort the queue so one of the way we can do it is during initialization is using a Lambda function where we just say that a b Aroma and then we say that sorted by the second index value of this integer array so say B1 minus A1 so what it does is that now given we are adding this um all the labels and values in the as an integer array into the queue data structure they'll be sorted based on the value so the ones with the largest value will be saved at the top of the queue so after initializing it um yeah let's create two variables to store the result an account so that's because they're giving us a restriction that the value could not exceed num wanted so we'll create a while loop so now we keep removing values from the queue data structure so PQ dot port so this one just uh keeps removing items from the top of the queue so here we have specified that the label cannot exceed the number of values from each label cannot exceed the use limit so for that we'll just make sure by checking the hash map so hm dot get num0 lesser than use limit then we start browsing else we do nothing first thing we'll do is we'll keep adding it to the result so result plus equal to one and then we'll increment the value in the hash map so for that we just say nums zero and we say num zero plus one so this value essentially what it does is keeps incrementing the count in the hash map so once it reaches the use limit we keep ignoring it until then we keep adding it to the result and incrementing it um finally we say return result so yeah quick recap we're using the queue we specify the Lambda function where we're using the second index to decide how the queue should be sorted and then we add all the labels and values inside of that queue and then we use a hash map to keep a count of how many times so you're using values from each label after that we keep removing it from the queue and ensure that the number of times is special than the use limit we keep adding um the values to the result incrementing the count and we do it until either the queue is empty or we have reached the maximum count that we had um so yeah it's pretty straightforward let's try running the solution oh we're making mistake in the same bracket so yeah all the three use case have passed I will try submitting it so yeah the time complexity will be o of n log n so by n is the number of items uh so here it's a case where we keep adding it to the queue data structure so like I said earlier in a queue all the insert deletion operation take place in login time so since we are first adding and then removing them so it's two n login which is you know we can still say n log n as the time complexity uh for space we are using a couple of data structures um both of them really have size o of n because n is the number of items so one is to keep track of the labels another is to just uh you know store the values in a queue which will maximum size the queue will be n so we can say the space complexity is m so yeah let me leave comments let me know uh anyone has a better solution for this and uh yeah like And subscribe the video I'm planning to add I think one video a day depending on how busy I am so hopefully I'm able to add more
Largest Values From Labels
armstrong-number
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
Math
Easy
null
1,041
welcome to september's leeco challenge today's problem is robot bounded in circle on an infinite plane a robot initially stands at zero for the x and y points and faces north the robot can receive one of three instructions g goes straight one unit l turn 90 degrees to the left and r turn 90 degrees to the right now the robot performs the instructions given in order and then repeats them forever return true if and only if there exists a circle in the plane such that the robot never leaves the circle in other words does the robot travel in some sort of circular fashion now to give you a couple examples here uh ggl gg here it would go up and then turn left and then come right back down right down so it starts at zero and then ends at zero knowing that this row is just going to continue doing that forever and it's going to exist inside a circle so it never travels out forever to infinity here gg uh goes up two units and then repeats that goes up two units and then up to units and it just goes up and up forever and here with gl it goes up and then turns left then it goes left then turns left and so it goes in like a square so that's technically like a circle right now to give you a couple hints here it says calculate the final vector of how the robot travels it also says the rope if the robot stays in a circle if looking at the final vector it changes direction or it moves zero so in other words if it stays in the same zero x y points now this kind of confused me at first like vector is this a linear algebra problem but that's overcomplicating it like let's just think about this very simply if we had a robot right and it either turns left or right at the very end whatever direction it goes it's going to keep turning left once again right and that sense it doesn't really matter how what direction it goes in whether it's going diagonal or what it's going to eventually be a circle because it's always going to turn left at the final point same with right if it turns right wherever it goes it's going to turn right go that direction again turn right and right so it's like circle again right the only exception to this is if it goes back into the middle if it goes back into the zero point i'll always go back there so whether it's whatever direction if it's facing the same direction it's fine because it's gonna go somewhere come back base the same direction go somewhere come back so that's still technically inside of a circular plane right so knowing that forget this whole vector thing that just over complicates it let's look at our instructions and think about how we could do this so we already know g is going to be moving up one or moving a unit and left and right is changing direction right so what we might want to do is start with a starting point and the way i did that was just initialize the x and y points as zero now we have a couple direct things we can do we could for our instructions so i in instructions there's three choices right either it's going to move up a unit it's going to move left or it's going to move right so let's think about what that means now moving up a unit with g is going to change this x and y points right we just don't know exactly how it's changing because we need to know which direction it's facing so knowing that like that kind of gives us a hint there like what would that mean as far as directions go so if let's say we were going up what would happen it would not change the x-axis but it would not change the x-axis but it would not change the x-axis but it would increase the y-axis by one right increase the y-axis by one right increase the y-axis by one right now what about if it's going right well then it would be increasing the x-axis one but it wouldn't be decreasing x-axis one but it wouldn't be decreasing x-axis one but it wouldn't be decreasing the y-axis at all now what about if it's y-axis at all now what about if it's y-axis at all now what about if it's going down now if it's going down then it would be decreasing the y-axis it would be decreasing the y-axis it would be decreasing the y-axis and it would not be changing the x-axis and it would not be changing the x-axis and it would not be changing the x-axis or i'm sorry the x-axis decreasing the or i'm sorry the x-axis decreasing the or i'm sorry the x-axis decreasing the x-axis and not decreasing the y x-axis and not decreasing the y x-axis and not decreasing the y and here if it's facing left then it's um oh i think i confused that sorry it's gonna be zero negative one and this would be negative one zero right because this is left this is down this is right this is up so what do okay we can have use these directional points i suppose put this inside of a list and what we're going to do is depending on whether we're going left or right move our pointer upwards if it's going right and move it left if it's going left or move it yeah move it decrease it if it's going left but what we'll have to do is like use a modular to make sure that we do this in a circular fashion this is like a cycle um so that way we know that whenever we move left it's going to move the pointer this way and right moving this way it's only when we move g we're going to add to our x whatever direction amounts we do have here we add that to our x y points all right so if um i equals g what do we do well let's first add whatever direction we're pointing at right now with the first element so one of these right and at the beginning it starts with zero so how about we have some sort of pointer we'll call it d and we'll say id right here and we'll use the modular to make sure that it's going to go circular around if it's like too much or if it goes uh negative right because there's only four elements so we just use a modular there same way with the y we'll say d modular four we'll get the second element now this is when we change if it's left or right this is where we change our d pointer so if it's right what we do we will increase our d otherwise if it's l will decrease it now finally what do we want to check are we facing a different direction other than north because that's how we step that's how we started or are we um at the same point right so are we at the same point different direction so we'll just return let's say whether x or y equals zero so that means we're at the same point or is this d pointer still pointing at the first one or if it's not pointing at the first one so if it's as long as pointing out one of these then we know we're pointing at a direction we're facing a different direction so d say modular four does not equal zero and that would be it let's make sure that this runs so this returns true let's submit that and accept it so is this the best way uh i mean it's pretty good but i think there might be a mathematical way to make sure that we're going to go maybe we don't need this array but i'm not really sure how to do that and really it's so small that i think it's fine uh let's like let's just see with our details it's about sixty percent uh 32 milliseconds i think that's pretty good and hopefully i explained that well i think this is pretty intuitive so thanks for watching my channel and remember do not trust me i know nothing
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
1,386
hello everyone so in this video let us talk about a medial problem from lead code the problem name is Cinema seat allocation so as you can see that there is a cinema with n rows of seats as you can see here and in an example from 1 till n all the rows are there and there are 10 seats in each row as you can see here so number from one till 10. now given an array reserved seats as you can see in the example there is an array that is given to you which denotes that what is the ith seat that is reserved so it is given in this let's say a pair which means that the seat located at the third row and eighth column you can say or the eat seat is actually reserved so three eight means that the third row eighth seat is booked now return the maximum number of four person groups you can assign on the cinema seats a four person group occupy four Addison seats in a single row you just have to tell that how many four percent seats you can assign like you have let's say four groups you have to assign it throughout this whole Cinema now seats across an aisle means that whatever is the you can say the very end of any let's say section is this is like this C doesn't I'll see this seed is an aisle seat okay so I'll use a let's say a very Corner seat of a section so this three four seven and eight are the aisle seats so seats across an aisle are not considered to be adjacent so if you cannot take a let's say a four person group like this oh sorry you cannot take a four person group like you can just put one person here and three persons here this is not considered for this three percent growth like uh this is not a four arrested group okay I understand that now but there is one exception so in which you can split a four person group in that case the I'll split a four person group in the middle which means that two person on each side so this is considered good which you can see here on the second row that you can put two persons on one place of like one position of the let's say uh one section and two portion on the next section but they are completely addition by their eye this is valid but yeah which I've told you this part this type of sitting Arrangement is not valid okay now what you'll actually have to just find out is that given the proper constraints you just have to find out how many four uh people groups you can fill in this particular uh Cinema Hall now what you can see is that n is pretty large which means that you cannot just create like you cannot just build the complete uh rows like this complete Matrix of let's say n cross 10 and just fill these addition Matrix like seeds and just check out because n is pretty much but if n is pretty much large and the total number of seats is 10 to power 4 which is good okay so what you can do with this scenario is that instead of finding out for all the rows how much position how many people I can sit I can just find out the values for all the rows which are booked so I have some positions so it matched into a four rows can be booked so let's say if all the people sit in every particular different row 10 to power 4 is a number of touch points we have to do so which means that I can do very simply in of L and for all the other rows which are not touched which means that all the row that is completely unfilled completely unreserved so let's take an example in which you can take this let's say the last row as the example the very first and the very last let's say seat of any row is invalid for us because that doesn't give us any benefit I have to somehow fill this set so what you can see is that for this as a row and the answer is not three I cannot like I have to check that this is one of the options and this is one of the options I don't have to find options I just have to fill the seats let's say I just have continuous four people groups that are coming to my let's say uh Cinema Hall so I just have to find out continuous four section that I can fill so I can just let's say fill one uh let's say group of four people here one group of here which eventually just means that for all the rows which are completely unreserved so let's say I have 10 to the power 8 rows and among them let's say 100 rows I have data key some are reserved some are not anything so 10 to the power 8 minus 100 are the rows which are completely empty means that completely unreserved we don't have any data for them which means that are completely empty so for every row that is completely unreserved what I can easily do is I can just make two groups of size four easily sit on them so I can make a group like this one group like this and I can easily shoot them so what you can easily understand is that 24 8 minus hundred all the rows I can just fill two people like two groups in them and for all the 100 rows which I have data I can just brute force all of them one by one and just find out how many let's say people I can fill or how many groups I can fill in these hundred rows find out the answer and just add that answer in the total answer which you have calculated so total number of rows that says n and the number of data I have for some rows let's say n small n so I know that for all these rows the answer is 2. so 2 into this row is the transfer and for all the N rows the small n which I have the data I will find out the answer for all of them using both force and just add the total and as a note on so that's you can see in the total answer as well 2 into n and it's a total amount of rows I have into the rows that I have know the values I have filled the values so I will get the answer of all of them into two and all the other rows which I have the value I will find the answer in total and I will I would add all of them and I will get the product okay that was the idea that for this particular problem now uh how can we do this in a very beautiful sphere how we can find out and how we can bundle them up it's pretty much simple you have all the seats you can first sort all the seeds by their let's say row so because the first one is the row and a second one seat you can directly just sort all these rows now all the let's say all the complete array will be sorted such that all the seeds which are booked in a particular row will come consecutively addition to one another which eventually means that let's say 2 comma 1 2 comma 5 2 comma eight then three comma 1 3 comma eight so all of them will be this in this man and the in the let's say in the sorted array in the sorted result there because I will just sort them so which eventually I just means that all the seats one five and eight are booked inside the row two then one and eight are booked inside the row three and I have these rows now so let's say I can just make simpler array or let's say a vector of size 10. and just fill out that I have uh the first position booked fifth position about eight position both and so on I just have to complete uh like the complete uh reservation for a particular row now I have two options I either I can fill uh two so after filling this complete row whatever reservations I have two options which are can I book or can I fill two groups of size four in this particular row or can I fill one group of size four in this workload okay so just I just have written these two functions check two and check one the on this particular row so this will just check that whether I can fill a row with two groups of size four or I can fill one group of size 4 in this particular how can sector for two groups for if I want to fill two groups all the rows for all the yeah all the columns sorry for let's say all the seeds from two second position till line position should be empty okay and if I want to fill one row then or let's say one uh complete section of size four or one group I want to book one group then there are three cases either I will book one group like this or I can one book one group like this or I can book one group like this so there are three positions if either all of these four seats are empty I will just check a Folly portal of them if all of them are if either one of them are empty then I will book a one okay and uh that's it I just have to calculate for all the rows that I have and then just okay there's a complete Logic for this particular problem let's move on the code part now so what we have done is that in this function we have to first sort all the let's say reserve seats and then this is the row I am on and then what I'll do is I will iterate over all the rows because all the seeds that are listened to each other either they will belong to the same row or not if they belong to the same Row the last row this is just a variable that will tell me what is the last index so let's say I am on the road to so all the let's say pairs that are having the row S2 I will mark it inside the same let's say row that I have so I will make a vector that is let's say rows or you can just mark it as a and then I will fill all of them whatever row I have with one which means that the tat is resolved now whenever I find out a switch which means that I have let's say to one book two four booked two eight book then I have a let's say the next prs38 whenever I find a new pair which means that which blocks your new row so which means that this row is completed all the reservations in this row is completed so if the if all the reservations in this row is complete I have the complete visualization of how this row is looking like I will increment the road and I have founded the look for one row incremental low then I will check that if this is the row can I fill two groups can I fill one group if I can feel I can I just find an answer and now I have to move to the next row so if I wanted to and I because the next row is started three eight so if I go to the next row I will make my row array that will or the row Vector whatever it said which is storing out the complete uh you can say the uh the complete uh like the representation of the row that way I will make it 0 which means that I will start from a new row all initial F to zero and I will mark because I have taken this particular uh you can say pair so I will mark this pair as booked inside the row and I will Mark the last which means that now I am on this row so I will mark this variable that is last as this particular row value that is u which reminds me that all the now all the new pairs after this will be in the row three if they are in the row three I will update them if they are not in the Row 3 I will now have the complete view of the Row 3 I will check it out now how this checkpoint and check to function Works let's take a look at that so this check to function will just iterate over from all the so I this is of indexed from 1 till 10 but I have stored in some index 0 to 9 so I will move from index let's say one to 8 if all of them are empty which means that all of them are let's say uh if you can say if any one of them is one which means that it is already filled I cannot fill two groups here but if any one of them is one then I will return false if and all of them are empty which means all of them are zero I'll return true which means that I can fill two groups here and to check if I can fill one group I have three cases which I've told you I will make a total of zero and I will check out from this position to this position that is index 3. index six if all of them are 0 increment account if the increment is four which means that all of them are let's say empty I will return true the next case is just checking from this to this and the other one is checking from this to this if any one of them turns out to be let's say true the answer is true that I have one of the options which I can fill a group of size 4 in this particular if not I'll return let's say like false okay that's the complete logic and the code part for this particular problem as well yeah I will just code it one more slowly so you can just take a look at this once again and if you still have any doubts you can make in the inbox for this particular video I will see you International coding and bye
Cinema Seat Allocation
shift-2d-grid
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved. _Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. **Example 1:** **Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\] **Output:** 4 **Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group. **Example 2:** **Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\] **Output:** 2 **Example 3:** **Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\] **Output:** 4 **Constraints:** * `1 <= n <= 10^9` * `1 <= reservedSeats.length <= min(10*n, 10^4)` * `reservedSeats[i].length == 2` * `1 <= reservedSeats[i][0] <= n` * `1 <= reservedSeats[i][1] <= 10` * All `reservedSeats[i]` are distinct.
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
Array,Matrix,Simulation
Easy
null
752
Hello everyone welcome back to the channels so today we are going to discuss the problem the name of the problem of the exam challenge is open the lock so this problem we have a combination given and we will increase one string and that combination is 00 Okay, we can't take that to zero and do anything else, if the number is this number then we can do this 12345 60 so if we see what we have to do is give us the minimum number of comments, how many of us should we use that minimum number of items required to To 1500 and so on and what and you can increase everything or you can do - like if you can increase then I can do this test word and thing for each digit or either that You can increase or remove it, you will understand the problem of toilet of AP, you will tell us a minimum number of units in the total, how to update it, we will take whatever input we find in the question, so basically we will start from zero, Robert De Niro 202, so this A, how can you see the paper and understand the approach along with it, then see and then after that we are going here that the complaint consumer and E0 what we have done that we have presented it in life here, so our A and after that What ground, after that we have this one which is stable and this one which is a, okay, so this one which is zero, give that one, I mean one and So what did we do after that here so 1212 this Close two how to delete died and this is ours see this eight zero on target 202 then tricks and useful 12345 6th and 8th this so I see above now I take out some innovative actions used to think how to make approach right With this, we can solve some problems, first of all, look at this, you are on every stage of your own free will, I am here, every detail, every Tuesday, December 4th digit, whatever lock I have, will die. We have appointed Shyam Digit from here till here, it is ok and lastly, Amazing, it is very important that every step has been decided only by you, so now in this link, all the possibilities, how to extract song loot, it is doing 100 fine. We have a text, how can we make eight, how can we make it 1234567 and how can we make eight, we can increase it to whatever it is, we can increase the number 90, so if we add two to this or remove this, it will become 1120. This one is criminal, either you give a bigger 200 to this one, otherwise we have increased this last one, or decreased me, okay, so how will there be eight on every seat on every stage like this? Okay, so what have we done? If we take a wedding, then after this we have the sleeve, then how is the one, so we make this one pan, okay, so if we make this one pan, then see what will be made, 12 everywhere I have our hands, how are they, okay, 1234567 and today the situation is I One and four, five, six, seven and eight, okay, then what will happen, then either forest campaign people were here, you make it bigger, 220, okay, hey friend, if we remove you, we will reduce it, then it will become 30, because we will lose first on protest. If we have already done this, then we will not take it, okay then what will we do? Now come to the second one, either increase it, if you increase it will become from zero, okay, remember, reduce me, but what will become of reducing the duration? No, it will be 90. And then come to the third one, friend, if you can increase the little one, then one will be bigger than zero, then what will become of one, okay, otherwise if you subtract, then tell me, then it will become the similarity, you will increase the last one, 540. If it does n't go then it will be 0. Okay, so which one of these will go next? If this is the one that will go next, then this one has hit $11, this one, so let's test it and see where it hit $11, this one, so let's test it and see where it will move ahead of the 11th around us, how sorry, 84 1234567 and eight, okay. So see what can you do in 1110, this one which I have made either if we increase it then it will become one then this is this and if we decrease this then what will become of zero reduced to zero Okay then we come to the candidate second If we increase ego, what will happen if we reduce it by half, what will happen, will it go to zero or Hussain A. Okay, after that now see this 20, we had taken this here earlier, so we will meet again, once this is gone, if you stop this, then that is neither, otherwise. Then after that we take this 00000, if we decrease it then 90 is fine, let's do this one too, one by one, if not the last one of 031 is deleted, then tell me, keep it now, which one will we take after this? It is 2010 112 Let's extend the gradient A web 18 people explain Similarly make a table and show how to enter Now only you can see who will become after 12th 2001 is coming i.e. what will we do in it is coming i.e. what will we do in it is coming i.e. what will we do in it Now Om will become Bigg Boss. Okay, friend, if you increase this one, then if you decrease them a little, then this will become. Okay, if you increase tu, then it will become 3000 and if you decrease tk, then it will become 1110. And then if you Increase the first one so that it will go to 12101 otherwise want to decrease it to 90 ok no the last one has 1201 or 120 9th so what paint will we put in it in this we will take and after that we have 2010 water that this one is So what will happen after this, so here we make a pan, so here we see what I am of celery, I am not all at all, but in the cross, we will come after Salman, 2002 is fine, that is, here, 2002, that is, here. But when you increment God, then what will become zero, then this case, then after this, when you come to this case, today he will become father, his father will become art, then among those eight, which one will give our answer in which we will study this point as Yadav Increment? We can make Twenty-20 this, we can delete this request make Twenty-20 this, we can delete this request make Twenty-20 this, we can delete this request so it will become 2020 mode on 20102 and this is our target so when we have ribbon we target was present that now see this how to calculate moong now see here first of all So what we did each one here, all this became one, then after this, we did this, so this should be the second movie, and then after this one, we did frequent, this is my third Mumbai dear, I am the fourth, okay. This done on individuals means where one is big but if then here on this one is done right on the coins here this I here this will be this and this last a total we have increment and decrement this time. So, this is how we will make all ours, so now there are two ways to fold it or you can use defense or you can use face, then it becomes difficult. In the last question, edifice was used in the previous one, we can do BF. Now what will we do, basically we will discuss all this in how, we will put in why and we can see it with the youth, this will give a clear understanding, so see what we have to do in the court, we had discussed it here, see where We will lick the beans and this, see where we took two kills, see like it is here where you were born, you were here again, Hussain was there, friend, if we take it from here, then what will we do, we should keep putting everything of ours in the guestted and on every digit, we What has to be done is to increment it, to decrement it, okay and if we have any death like a dent here 0201, if we have 0201 somewhere or it must have come somewhere and any dip from inside like everything. Take someone else, like if any one of them comes, then we will make their days better than that, okay, after that, we will not make anyone else, we will just hit them back, okay, then let's see what we do in the court, first of all, this is what we need. Dent's speed and collector were given and the target was given and as far as we knew and what we had to do, after this we made a set. Well, we are putting Dent in the set because if someone was repeated in death, he was Basically, this will start the time complexity like the entire run. By taking the set, we put our updates in the set and why did we take one, why not, why are there tricks for them and why did they make them of love in which Singh Rintu's why because Here but pay attention, it is everywhere along with it, what will we do here, let us give whatever is ours, as if it is 1102, it is okay, we will kill both of them, how many idols are there for us now, how many idols have we created? If you don't do it, then in our why, first of all, whatever is our current, Google of combination and second, whatever total we have till now, its good, okay, so we have made this for this reason, we have made widgetized set and What did we do in the beginning, if our dad is zero, if we increase it in any Roman race, then if there is rear dead inch, then we cannot marry her to a landlord, so we will first check that if our dad is in our set, if our zero is in our set. You must not have read that then we will put it in why and in the roots of English, we will put it in chicken districts and we will also put it in visit. Put it in the age of doing two jobs, there is withdrawal, after that why it is not going till now, till then we will work. What will work, listen to the knowledge, every time we will take out that it is okay, we have put a string in it, so why we have put us in it, neither is this gender, whatever is our combination lock, we are putting it in it and this is the current moves, how many seals. We are putting it in the account, okay, what we are saying about it is that if the current is opened for our target, then we have reached, okay, we have reached it, so whatever it is, remove it. The current setting here is here so you can contest the account is fine and otherwise what do we have to do here we will put and why the eye of the lens is equal to zero four because we thought of we thought that We have to do this carefully, we thought that whatever our number is, we will go to its corresponding digit and what will we do with each digit, either we will make it or on the attend side, then four, then we want the mission digit, it is not starting from zero in the lock. Will do all the details, always from this point it will run till quarter inch and four. For purchase will run on after and through each we will create a new team, so why not make a number like first we will take out zero from this one. Interior, this team will wake up in this. Given in the season, we will take out these zero entries, then increase it to one, what will we do, refilling the gas is left, we will put it in this, by doing all the tricks and submitting, we will make this new drink and we will add it to our why if this order David No, it is okay, similarly, from here, this Rolia should make it - if it is there, then if we subtract it will make it - but we will add a plus to it, the tension is a rag, so that should make it - if it is there, then if we subtract it will make it - but we will add a plus to it, the tension is a rag, so that it is deprived of youth, okay, so we will make a plus so that if - a little, then that line whereas plus so that if - a little, then that line whereas plus so that if - a little, then that line whereas if we decrease it. In the year 2009, I am telling you that here we will do this operation, this time Pawan Singh Manali temperature will be made in then we will check, if there is no redemption point in my date and our time is also not there in the widgetized one, then why is it so? I add it, put it in detail and account Laxman because to make them sad, we have done these preventing ants here, so one and that but in the next ones, we will do Laxman in the phone for time two, we have added it in that temple. There has been a big time to the medical officer Dr. and this is in Udaipur and if here Vitamin E means we cannot do it to our skin - E means we cannot do it to our skin - E means we cannot do it to our skin - means if we were not the target then basically who was this then once we understand well that we should keep this string. And it was simple, just pay attention to what is the use in it, the thing that made this Mukesh was that we are doing only one lift on every stage, it is okay, not like this, two-three is okay, not like this, two-three is okay, not like this, two-three can do it, one is doing it and Each digit can be increased upto
Open the Lock
ip-to-cidr
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot. The lock initially starts at `'0000'`, a string representing the state of the 4 wheels. You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. **Example 1:** **Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 " **Output:** 6 **Explanation:** A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ". Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102 ". **Example 2:** **Input:** deadends = \[ "8888 "\], target = "0009 " **Output:** 1 **Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ". **Example 3:** **Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 " **Output:** -1 **Explanation:** We cannot reach the target without getting stuck. **Constraints:** * `1 <= deadends.length <= 500` * `deadends[i].length == 4` * `target.length == 4` * target **will not be** in the list `deadends`. * `target` and `deadends[i]` consist of digits only.
Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n.
String,Bit Manipulation
Medium
93,468
1,197
hey everybody this is Larry this is me doing weekly premium problem five of October hit the like button hit the Subscribe and join me on Discord let me know what you think about today's Farm uh I forgot to do an outside intro for this so I'm going do it now um but yeah today's Farm is 11 97 minimum night moves and I haven't done this before so let's see what's going on in an infinite Infinity uh infinite chessboard okay we return to min number of moves to move the Knight to XY okay well the how big is this is 600 by 600 so 600 by 600 should be good enough uh for us to Pro Force it or not pro force it but just do a bre search um you still have to be careful because you can't go over 300 I think like there's some like weird like you know you have to go up and then come back or something but if you do like 302 or something that should be fine um and you could also just I think there's also like a symmetry thing where we just take like the you know you could do a symmetry thing for sure but we'll just do a i thing for today uh and then see if it works if not then we'll see if we do some optimization but yeah but let's just say yeah I mean so directions is youal to uh these are just like all the possible night directions um and yeah I wonder if there's a cener way to write it if you know one do let me know but I've been doing it like this forever and have a typle forever I guess but yeah and then basically yeah and I guess the other way that you could think about it's moving it toward 0 so is that easier it's easier in that it's computational faster because then now you don't go a bounce as much maybe but maybe I'm wrong on that one don't know if it matters that much so all right let's just start from zero Zer let's just um you know do it the silly way and then uh we'll see what happens right and then we WRA like a distance ring we'll just put in a set for now because I'm lazy today and we'll see if that is good enough for us to you know do what we need to do I just turned on my monitor brightness and I was like wow now I can actually see stuff oh I guess I did it wrong but usually I do it a cener but today I'm just really out of it I'm just want to get it done um so my apologies but basically this is just break search and if it with bre search doesn't work in theory you do like a star search or some uh cener thing but we'll see how that goes oh do you ever want to go okay whatever uh let just say uh NX is equal to this plus two I don't even know right something like that oops that actually could be bad wait what no it's just so that we don't go bounce too much otherwise the branching Factor along would kill us um and then yeah and that's pretty much it really then now we can say something like and we will always have an answer so let's give it a spin I mean collections I mean course oh cuz I'm returning none why am I returning n uh today I can't even do a symbol problem what I mean it's this one but why is it not going to let's see 42 why is it not going to three4 oh what the that's a really nasty typo actually but uh still not fixed but maybe I still have another typo which is possible still not going to 3 four 42 is in here do I have a typo here seems okay for now and I am out of it today I guess let's see we have 42 go to 34 with three four 34 is our P why or Y is I guess my question is why is NX and Y so low is in the 55 oh I am dumb cuz I we used the XY here and so this is confusing okay fine that's why never matches that's a way I'm exhausted as you can tell I can't even you know and it's going to do outp put limited errow or something maybe uh oh maybe still none maybe I'm well oh because this is still I didn't fix this uh output two expected one h i mean that's just silly oh this is of course you start at zero not one I don't know why I did it that way I'm making a lot of silly mistakes today all let's give us some well let's do a 300 case and then we'll give a submit oh actually I missed that what does that even mean for me I don't know but I guess it's good makes it even smaller maybe not small enough uh one second is pretty slow though let's give us some mid I'm not sure in this one like maybe I should do a plus two or plus three instead oh I guess I don't never check this that gets me all the time I don't know why I do it that way well I know why I because I don't have this if statement because I think that this is early termination but I just didn't know I mean that's just silly I mean if bit times out that's another story but yeah another I mean I don't know it's hard for me to say this is a silly problem when I obviously do you know do not get it wrong but yeah like how do you make a mistake and be like a this is easy so easy but I only got one wrong answer instead of five but uh but yeah anyway I'm in a very quiet place today that's why I'm kind of talking a little bit quietly uh let me know what you think let me know how you do it uh and yeah stay good stay help you to mental health I'll see youall later and take care bye-bye
Minimum Knight Moves
parsing-a-boolean-expression
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists. **Example 1:** **Input:** x = 2, y = 1 **Output:** 1 **Explanation:** \[0, 0\] -> \[2, 1\] **Example 2:** **Input:** x = 5, y = 5 **Output:** 4 **Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\] **Constraints:** * `-300 <= x, y <= 300` * `0 <= |x| + |y| <= 300` "t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
String,Stack,Recursion
Hard
null
76
hey everybody this is Larry this is day four of the Leo dily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this one um yeah oh it's a hard one hopefully uh we have time because I need to well the contest is coming up and I'm not going to do the um the premium prom today just because or the extra prom that I usually do because um well there's a contest in like an hour or so yeah but today's PR is 76 minimum windows substring so given two strings s and T length of M and N respectively return the minimum window substring of s such that every character in t including duplicates is included in the window if there no substring we turn the empty string uh you uh well just empty string okay the answer will be unique okay so basically you have this thing which is really a set of characters do uh does the case count I think they probably change the complexity at some point for the followup because the only way that this would pass would be an M plus n algorithm anyway I guess like maybe it was short enough at some point that it was M * n but that what is going on here was M * n but that what is going on here was M * n but that what is going on here every character oh including duplicates I see um so it's not a set so I misspoke okay yeah okay that's not that bad I mean basically the idea is still going to be the same there's still only 26 characters I mean there a couple ways you can kind of optimize this but we'll do it the silly way um the core part about this problem is going to be greedy and by the ways of um sliding window right um cuz we're trying to find the minimum uh we can definitely find a subring window um but we'll try to get minimum because if we have enough then we can kind of reduce from the left and we add one at a time to see if we have enough so let's uh let's kind of do it that way so let's say uh ft for I don't know frequency of T see so then we kind of get the frequency table of T and then now for um so left is equal to zero um and then now we do right in range to n this is a very standard uh sliding window setup at least the way that I do it I mean you can definitely write it different way but the setup is kind of the same and then the current is going to be the counter that reflects um that reflects um the thing that reflects uh sorry man I'm want to I'm on a 44-hour fast so definitely I to I'm on a 44-hour fast so definitely I to I'm on a 44-hour fast so definitely I don't know my brain is like I think changing a little bit between uh energy usage so I'm a little bit slow but yeah so the current basically represents the um the frequency table of the colle um of the characters that are inside left and right uh inclusive at least inclusive after we do this right uh s um yeah so basically if this is greater than t uh or ft of S Sub right then we have to remove characters from the left right so uh yeah current S Sub left and then left because basically the idea is that there only one Char there is only one character in which you can go over the number allotted right because if you have like two A's in the substring then it's wait is this right now this is not right sorry man I'm thinking of a different problem uh this greedy is wrong because you can have multiple A's um like for example you have multiple A's but it will still be the shortest because you don't have enough the B and the C okay huh it's okay yeah this is a little bit wrong though you yeah this is wrong I mean this is definitely wrong sorry friends wow I'm really off today because this feels like pretty a standard problem but um yeah I mean I guess you could do it this way for every character so maybe something like for C in uh current. keys I just like to make it explicit wait that's not right either is it um that's not it should be that it is um H okay fine um I you should do it the other way that's why I'm a little bit um yeah okay fine let me rewrite this cuz I usually think about this the other way because the other way it's just more optimal but I was trying to kind of mix it up a little bit by doing it this way but I mean it's fine this way should be fine right so basically like if all of currs of C is greater than or equal to um ft of C for C in ft. keys and the Ft part is the more important part that means that this is good but then we have to I'm trying to F so the why I'm struggling a little bit is that this part is a little bit greedy so I'm just trying to go for the cases in my head whether um there is a counter example that's basically what I'm trying to do here um okay so if they're all good that means that the current string is good okay and then now that means that maybe something like while um current of left is greater than ft of left or S of oops then um yeah we can subtract it and then we increment so this is now basically almost the same as we had before actually but this is basically if it we all satisfied um if this is strictly greater than we can and go and remove characters from the left so that now we have um we have the thing that is um now after this the uh invariant is going to be that um oh I forgot about okay so after this V Loop it means that this is still true because it has to be strictly greater than and that means that we can do a check on whether you know so right minus left plus one is going to be the number of characters and then we're trying to see if it's the Min right so we have to just do some like Min index things so uh so yeah best is equal to I don't know we just have some crazy long things right so maybe this times n or something um and then here um this is it's going to be a string going from left to right so basically if this number this is the length is going to be less than length for best then best is equal to um maybe this is a weird way of writing it uh best just write best start is equal to none best is equal to n + 1 and then now none best is equal to n + 1 and then now none best is equal to n + 1 and then now if this is then best is equal to right minus left + one best stor is equal to left + one best stor is equal to left + one best stor is equal to left and then here at the end if best start is none we return empty string otherwise we return um s best start to best is the length so it is best do plus best right someone like that yeah I don't have a silly mistake okay that's good 1405 day streak and that's pretty much it I structured this a little bit differently which is why I'm I struggle with this the way that I would actually recommend doing it if uh you're not I don't um but this is easier to understand but it is a little bit trickier um to kind of go through it especially if you haven't done it before and maybe I haven't done it in a while because this is strictly a little bit worse than the other one and the other way that you would maybe do it is counting down strictly because if you count down then you could actually uh count stuff in all of o of one instead of O of alpha where Alpha is the size of the alphabet and the alphabet can have upper and lowercase letters which is 52 right but yeah but the key part about this one is just trying to think about the invariance after every Loop um so there is an invariant here uh that after this Loop then it is still uh this condition still holds which means that it contains all uh the substring contains all the letters of t and this is why we do best otherwise we just kind of keep on going until this is true and as I said this is going to be um o of alpha this is all of n so this is actually over of alpha time n um yeah so this is after Alpha time n you can actually uh reduce this and all of alpha time M plus N I suppose where n is the length of t or something I don't know let's change it real quick so this is let me just write it out so this is going to be o of alpha or a * S Plus T going to be o of alpha or a * S Plus T going to be o of alpha or a * S Plus T right because T is the length of T and S is length of s I think that's more straightforward so that's the time and for space is just going to be o of alpha right um but you can actually do better if you're a little bit careful like I said um this if operation and yeah this if operation takes all of alpha which is the expansive part after everything but you can actually if you do a countdown thing instead then you could just check that it is empty so then that gives you all S Plus T time and O of a space still and that is obviously just um better but I didn't do it this way I don't know I thought this way is a little bit more straightforward the idea is just invariant so you kind of keep on adding letters to a set and then once you're able to match it which means this has happened then you try to make it as small as possible so that you know um this is the best string the smaller string that ends with um this current character the right character where the condition fits so yeah um yeah that's all I have for this one let me know what you think uh I'm so bad at like spamming and advertising so I'm just going to say check out my walk-in just going to say check out my walk-in just going to say check out my walk-in channel uh in Japan I'm still working hard on the next episode and stuff like that so yeah uh but that's what I have for this one let me know what you think if you're doing a contest later good luck and have fun of course uh and wish me good luck the contest stay good stay healthy to your mental health I'll see youall later and take care bye-bye
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
419
hello guys in this video I will solve battleships board from leak code so in this problem we are given a 2d board which contains empty cells and battleships need each battleship is either placed horizontally or vertically and each of these battleships my is at least separated with oneself from other battleships so and the question here is how many battleships are on the board but the real challenge comes in follow-up where we are suggested to follow-up where we are suggested to follow-up where we are suggested to solve this problem just in one pass using zero we go from one extra memory and solve this problem without modifying the value of the board so the idea of solving this problem is very simple we will just iterate over the board and for each value we will just count only its last itself so for example in the first example for the first battleship we see that it's the last cell of this battleship because it's the only cell so we will count it and for the second battleship we see that this cell contains a cell below it and this cell contains a cell below it so for the two upper cells we won't count we won't increment our counter but for the last cell we will increment our counter we can check that there is no cells below it or there is no cell on the right side of it so we will meet count which is initially 0 and then well I tried over this board first who check if bored I J is in the so example then we will if I is less bored sighs - Juan now if i is equal to board size minus one and so if i his last ten boards is minus 1 and if board I plus 1 J so it means the cell below this the current cell if it's also a part of this battleship then we will continue and the same for the cell do it so J plus 1 and J is less than board 0 size minus 1 then we will increment our counter and return it as a result was check the solution ok it was accepted guys please subscribe to my channel ask me to solve any other recode problems I will make videos of solving them and explaining them and thank you for watching this video
Battleships in a Board
battleships-in-a-board
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. **Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). **Example 1:** **Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\] **Output:** 2 **Example 2:** **Input:** board = \[\[ ". "\]\] **Output:** 0 **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is either `'.'` or `'X'`. **Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
null
Array,Depth-First Search,Matrix
Medium
null
1,396
hello and welcome back to the cracking fang youtube channel today we're going to be solving leap code problem 1396 design underground system right now this is bloomberg's number one interview question so if you have an on-site interview with bloomberg coming on-site interview with bloomberg coming on-site interview with bloomberg coming up you're probably going to encounter this question so it's definitely one to know let's read the question prompt and it's quite long an underground railway system is keeping track of customer travel times between different stations they are using this data to calculate the average time it takes to travel between one station to another we want to implement the underground system class which has a function check-in which returns void which takes check-in which returns void which takes check-in which returns void which takes an integer id a string station name and an integer timestamp a customer with a card id equal to id checks in at the station name at time t a customer can only be checked into one place at a time we also want to implement a checkout function which returns void and takes an integer id takes a string station name and an integer t which represents the timestamp a customer with a card id equal to id checks out from the station name at time t we want to also implement a function called get average time which is going to return a double which takes a string state start station and a string end station and what we want to do is return the average time it takes to travel from start station to end station the average time is computed from all the previous traveling times from start station to end station that happened directly meaning a check-in at start station meaning a check-in at start station meaning a check-in at start station followed by a check out from end station the time it takes to travel from start station to end station may be different from the time it takes to travel from the end station to start station there will be at least one customer that has traveled from start station to end station before get average time is called you may assume all calls to the check-in and checkout methods are check-in and checkout methods are check-in and checkout methods are consistent if a customer checks in at time t one then checks out at time t two then t one will always be less than t two and all events will occur in chronological order okay so we read the question prompt and that was quite a mouthful let's think about how we might want to approach this problem and look at you know what our algorithm might look like okay we read the quiet long question prompt and now it's time to figure out what we actually want to do so i've summarized essentially what this question is asking us for into you know these three lines so we want to implement the underground system class and it's going to have that check in function that checkout function and it's going to have a get average time function so we know that the get average time function is you know going to be providing us with a start station and an end station and it wants to know the average time and obviously we want to do this in as quick a manner as possible we don't want to be crunching numbers every time this get average time gets called because if it's a potentially uh costly operation we could run into some sort of um you know like exp not exponential but quadratic runtime complexity if you know calling this function takes big o of n time and we're calling it n times then we can get into really nasty uh you know run times which we don't want to do so we want to optimize our get average time such that you know we can just access the data on the fly so the way that we want to do this is that we're going to maintain a dictionary whose keys is going to be you know this start station uh it's going to be a tuple sorry start station and end station and what we're going to do is we want to maintain as the value some sort of data structure which is going to represent the you know journey count so journeys and then we're going to say you know total time for this uh particular journey uh so total time and the reason that we want to do this is that whenever you know they pass us a start station end station we can simply look up the tuple with those two pairs and then get the journeys and the total time and then to get the average remember that to calculate the average we're simply going to take the you know total time and we're going to divide it by the journeys and the reason that i choose to do journeys sorry total time in journeys to calculate it like this instead of just storing the average directly is because i don't remember off the top of my head the formula for updating an average with a new um you know with a new value right whereas i know exactly how to calculate the average if i have the total time in journeys most likely unless you paid you know very a lot of attention in your statistics class if you even took one will you remember the formula for updating an average with a new value um you know it's not exactly intuitive and in the high pressure interview situation if you don't remember this then you're basically screwed so i just prefer to store it this way uh instead of just trying to just compute the average so you can return it like immediately so there is a little bit of cost so you do have to calculate this but this way like if you don't remember the average then you can just get it from first principles so this part is simple right but you know how are we going to track the number of journeys and the total time well it's quite simple we know that we have you know a check-in and a checkout have you know a check-in and a checkout have you know a check-in and a checkout function so we need to somehow use this data to update our start and end here so what i propose that we do is we maintain a journey dictionary so this is our metrics dictionary storing you know the values for get average time but we're still going to have to keep track of active journeys right so what i propose is that we're going to keep a dictionary which maps you know a station so we'll say uh sorry not station we're going to say for a user so like an id this is going to map uh you know any active journey that they're currently on so you know where they tapped into the network at so some start station and some you know timestamp and we'll call this timestamp one so every time someone checks in we're gonna put their you know id and their start time and the state uh and sorry the start station and the timestamp they checked in at into this dictionary then when they check out um we know that someone has to check out after they've checked in right they can't check out before checking in so we know that they will have an entry in this dictionary when the checkout is called because you know the problem statement basically told us that we can be guaranteed the input will be valid we don't have to worry about someone trying to check out before they've checked in anyway they check out and we know that their id is going to be in here so what we can do is we now have you know our pair here right we now know where they started and the checkout function will tell us where they ended so now we'll have this pair start end and what we can do is we can compute the difference because this you know this timestamp is going to represent when they checked out so we'll call it timestamp two and we'll say you know the difference is going to be the time taken right uh for that particular journey so what we can then do is we can add this time taken to you know our key here in the metrics dictionary and you know we'll add it to this value here so we'll add you know add it to that value and then we can add one to the journeys right because we've just made a new journey and we can simply uh increase our journeys count here and we're going to do that for every check-in and check-out pair that we get check-in and check-out pair that we get check-in and check-out pair that we get now remember that when we check out what we need to do is you know if someone makes another journey for that id then they're going to have an um you know something in here and we don't want to be overriding keys we just want to get rid of um someone's data as soon as they check out so when they check out we're actually going to wipe them from this dictionary to prevent the size from getting too big we could you know if someone just makes one journey if a lot of people do that then this dictionary can get really large and you know it could potentially you know cause us to run out of memory so what we want to do is when someone checks out wipe their key from this dictionary and then that way we can keep the dictionary size small and then when they check in again then we'll just add it and then every time they check out we just simply wipe it so that way this dictionary will only be holding active journeys right um where like a journey it's in progress and that's basically the approach that we want to solve uh this question with right we want to you know use this active journeys to keep track of you know a journey and then when they check out we're going to use the data you know the difference between the time stamp that they checked out at and the time stamp they started at and we can append that to the data that we have for that metric so that way when we call get average time we can do it in constant time or we just have to fetch the entry from the dictionary and then just compute the average and return that which is going to be a constant time as opposed to if we just stored all the journeys and then we had to crunch them on the fly every time we asked for get average time which would obviously you know be a big o of n operation and we don't want to do that so uh what we want to do is that approach now let's go into the code editor and put this into code i'll see you there we're back in the code editor let's write the code remember that we said that we're going to be working with two dictionaries to actually solve our problems so let's define those now so remember we're going to say one is going to keep track of the active journey so we're going to say self.journey dictionary is just going to self.journey dictionary is just going to self.journey dictionary is just going to be an empty dictionary and we're going to say self.metric to say self.metric to say self.metric dictionary is going to be another empty dictionary so let's handle the check-in so let's handle the check-in so let's handle the check-in so what do we want to do when we check in well it's quite simple we just want to put into our journey dictionary the id is the key and a tuple representing the station name and the time stamp they checked in at as the value so all we have to do is say self dot journey dictionary oops of id is going to be equal to tuple with the station name and timestamp and this is a you know a function that returns none so we don't actually have to return anything we can just return after we've done that okay so now it's time for the checkout and remember uh we don't have to worry about someone trying to check out before they've checked in so we can always assume that our input here is going to be valid so what do we want to do well we need to calculate the difference between the time they checked out and the time they checked in so we can update our you know metric dictionary with the correct you know journey time for that particular you know start station end station pair so let's grab the values out of the dictionary of what station they started at and what time they started at so we're going to say start station and start time is going to equal to self dot journey dictionary oops for that particular id so we fetch that data and now remember we want to get ri we want only this journey dictionary to store active journey so someone's checked out which means that their journey is no longer active they're out of the underground system we don't have to worry about them anymore so we can simply delete that key from the journey dictionary and remember you know even though you don't have to do this the reason that we do it is because we want to keep our memory costs down we don't want to be storing people who are already out of the system if a lot of people just make one-off journeys and people just make one-off journeys and people just make one-off journeys and they're not like active people that are constantly using the system then our journey dictionary is going to grow in size and we could potentially run out of memory so this is like a little you know implementation detail that you'll want to do and your interviewer might press you'd be like well you know what happens if the journey dick gets too big and it blows up what can we do then so you know we want to get rid of this key for that reason so we're going to say delete self.journeydictionary for that id so self.journeydictionary for that id so self.journeydictionary for that id so we're going to wipe that id from the dictionary so we're not storing that in memory anymore now what we want to do is we want to update our metric dictionary with basically the time for this um you know start station end station combo now it may be the case that this particular journey was the first time it was ever seen so what we want to do in this case is check whether or not that journey has been made before and if it is then we can simply increment you know the values for that journey otherwise we actually have to add it to the dictionary so we're going to say if start station uh station name which i guess represents the end station here um in self.metric dick so basically if that in self.metric dick so basically if that in self.metric dick so basically if that journey has been made before then we just want to increment the total journeys and we want to increment the you know total travel time for that particular um pair uh in our dictionary so we're going to say self.metric dictionary to say self.metric dictionary to say self.metric dictionary and the key remember will be the start station and the end station which is again station name here and you know we're going to be storing it in the format of it's going to be um you know total journeys so it's going to be a list here total journeys and then total travel time so the first the zeroth index will be the total journeys and the first index will be the total travel time so we want to increment the you know total journeys by one because we've just made a new journey and then we want to append or increment sorry the total travel time by the you know travel time we had so we're going to again increment that value for the pair here and this time it's the first index and this time we want to add the difference between the current time in checkout which is our checkout time so t minus our you know start time for the journey start time and that difference is going to be the time that our journey took so we're going to add that to the total travel time okay so that's the case when we've made that journey before if not this is going to be the first journey so we can simply initialize our you know metric dictionary for that pair so we're going to say start station and station name and what we're gonna do is we're gonna initialize it so we've never seen it before which means that this was the first journey so there's one journey made and the total travel time is just gonna be t minus the start time and that's all we have to do and remember this function is returning none so we would just return at the end of it here now all we have to do is implement the get travel time or the average time so we can easily look this up from our dictionary so we're going to say the you know journey count and the total journey time is going to equal to what so self.metric dictionary for our co our so self.metric dictionary for our co our so self.metric dictionary for our co our pair here so we're going to say for our start station end station pair whoops so we're going to extract those values from the dictionary and remember we need to calculate the average now so all we want to do is simply return the total journey time oops journey time divided by the journey count and that will return us the average right because the total time spent traveling divided by the total amount of journeys will be the average amount of time per journey so this is going to be how you solve this problem let's submit it hopefully we haven't made a bug somewhere because there is a bunch of things okay cool so this function sorry we solved the question and let's think about the time and space complexity well the time complexity is going to be big o of one why is that well check in all we're doing is adding a key to a dictionary which we know happens in constant time so our check-in happens in constant time so our check-in happens in constant time so our check-in function is big o of one check out what are we doing we're getting a key from a value from a dictionary which is going to be constant time we're deleting a key from a dictionary which is also constant time and then we're you know checking to see if something exists in a dictionary again this is constant time and then we are simply either setting a key in a dictionary still constant time or incrementing you know a value for a key which again is going to happen in constant time so every operation in checkout still happens in big o of one time and then for the get average time you know these values are just uh look up by a key into a dictionary which is big o of one and then computing this is also going to be big o of one computation so our time complexity is actually big o of one for every single operation here uh in our class what about the space complexity well we're storing two dictionaries so let's think about you know the possible um you know sorry what is it gonna be the possible space here so we know that the journey dictionary will be tracking all active journeys so we can think about this as having big o of p space where p is the number of like total active journeys at any one point and what the metric dictionary is storing is it's storing all the you know start station end station um combinations so if we had s stations then you know there's times s minus one um you know pairs here that we could work with uh so that you know that'll be the worst case that we'd be storing here so obviously this is going to be asymptotically just s squared so that would be what our um uh metric dictionary could be storing so basically all the possible combinations of two start and end stations so that means our space complexity is going to be big o of p plus big o uh sorry plus uh s squared so that's going to be this base complexity here where p is going to be from this journey dictionary and represents the you know number of current active journeys at any point in time and then the metric journey is going to be all the possible combinations of start and end stations where if we have s stations then we would have s squared possible combinations here um so that's going to be your time and space complexity hopefully you enjoyed this problem hopefully it was helpful for you if you are you know preparing for a bloomberg interview you know there's a good chance you're probably going to see this question because it's their number one ask question so they quite like this one a lot uh if you did enjoy the video please leave a like comment subscribe if there's any other videos or topics that you'd like me to make content on please let me know in the comments section below i'd be more than happy to make those for you just let me know what you want to see and i'll get back to you otherwise happy coding bye
Design Underground System
count-servers-that-communicate
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the `UndergroundSystem` class: * `void checkIn(int id, string stationName, int t)` * A customer with a card ID equal to `id`, checks in at the station `stationName` at time `t`. * A customer can only be checked into one place at a time. * `void checkOut(int id, string stationName, int t)` * A customer with a card ID equal to `id`, checks out from the station `stationName` at time `t`. * `double getAverageTime(string startStation, string endStation)` * Returns the average time it takes to travel from `startStation` to `endStation`. * The average time is computed from all the previous traveling times from `startStation` to `endStation` that happened **directly**, meaning a check in at `startStation` followed by a check out from `endStation`. * The time it takes to travel from `startStation` to `endStation` **may be different** from the time it takes to travel from `endStation` to `startStation`. * There will be at least one customer that has traveled from `startStation` to `endStation` before `getAverageTime` is called. You may assume all calls to the `checkIn` and `checkOut` methods are consistent. If a customer checks in at time `t1` then checks out at time `t2`, then `t1 < t2`. All events happen in chronological order. **Example 1:** **Input** \[ "UndergroundSystem ", "checkIn ", "checkIn ", "checkIn ", "checkOut ", "checkOut ", "checkOut ", "getAverageTime ", "getAverageTime ", "checkIn ", "getAverageTime ", "checkOut ", "getAverageTime "\] \[\[\],\[45, "Leyton ",3\],\[32, "Paradise ",8\],\[27, "Leyton ",10\],\[45, "Waterloo ",15\],\[27, "Waterloo ",20\],\[32, "Cambridge ",22\],\[ "Paradise ", "Cambridge "\],\[ "Leyton ", "Waterloo "\],\[10, "Leyton ",24\],\[ "Leyton ", "Waterloo "\],\[10, "Waterloo ",38\],\[ "Leyton ", "Waterloo "\]\] **Output** \[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000\] **Explanation** UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45, "Leyton ", 3); undergroundSystem.checkIn(32, "Paradise ", 8); undergroundSystem.checkIn(27, "Leyton ", 10); undergroundSystem.checkOut(45, "Waterloo ", 15); // Customer 45 "Leyton " -> "Waterloo " in 15-3 = 12 undergroundSystem.checkOut(27, "Waterloo ", 20); // Customer 27 "Leyton " -> "Waterloo " in 20-10 = 10 undergroundSystem.checkOut(32, "Cambridge ", 22); // Customer 32 "Paradise " -> "Cambridge " in 22-8 = 14 undergroundSystem.getAverageTime( "Paradise ", "Cambridge "); // return 14.00000. One trip "Paradise " -> "Cambridge ", (14) / 1 = 14 undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 11.00000. Two trips "Leyton " -> "Waterloo ", (10 + 12) / 2 = 11 undergroundSystem.checkIn(10, "Leyton ", 24); undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 11.00000 undergroundSystem.checkOut(10, "Waterloo ", 38); // Customer 10 "Leyton " -> "Waterloo " in 38-24 = 14 undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 12.00000. Three trips "Leyton " -> "Waterloo ", (10 + 12 + 14) / 3 = 12 **Example 2:** **Input** \[ "UndergroundSystem ", "checkIn ", "checkOut ", "getAverageTime ", "checkIn ", "checkOut ", "getAverageTime ", "checkIn ", "checkOut ", "getAverageTime "\] \[\[\],\[10, "Leyton ",3\],\[10, "Paradise ",8\],\[ "Leyton ", "Paradise "\],\[5, "Leyton ",10\],\[5, "Paradise ",16\],\[ "Leyton ", "Paradise "\],\[2, "Leyton ",21\],\[2, "Paradise ",30\],\[ "Leyton ", "Paradise "\]\] **Output** \[null,null,null,5.00000,null,null,5.50000,null,null,6.66667\] **Explanation** UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10, "Leyton ", 3); undergroundSystem.checkOut(10, "Paradise ", 8); // Customer 10 "Leyton " -> "Paradise " in 8-3 = 5 undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 5.00000, (5) / 1 = 5 undergroundSystem.checkIn(5, "Leyton ", 10); undergroundSystem.checkOut(5, "Paradise ", 16); // Customer 5 "Leyton " -> "Paradise " in 16-10 = 6 undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 5.50000, (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2, "Leyton ", 21); undergroundSystem.checkOut(2, "Paradise ", 30); // Customer 2 "Leyton " -> "Paradise " in 30-21 = 9 undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667 **Constraints:** * `1 <= id, t <= 106` * `1 <= stationName.length, startStation.length, endStation.length <= 10` * All strings consist of uppercase and lowercase English letters and digits. * There will be at most `2 * 104` calls **in total** to `checkIn`, `checkOut`, and `getAverageTime`. * Answers within `10-5` of the actual value will be accepted.
Store number of computer in each row and column. Count all servers that are not isolated.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix,Counting
Medium
null
1,074
hey everyone welcome back and let's write some more neat code today so today let's solve the problem number of submatrices that sum to a given Target so given this Matrix over here what exactly is a submatrix well their definition of course is going to be more complicated than it needs to be but basically it's any rectangle inside of this Matrix so this is a square but we could obviously also have this we could have this any of them so I guess the natural approach would be to get every single submatrix in here compute the sum whatever that happens to be let's say it's X then check is x equal to the Target if it is then we should take our result our count and then add one to it if it's not then we don't do anything so let's just give that a shot because surely there's no better way to solve this problem than to get every single submatrix doing that is not super easy it's not super crazy but it's not like trivial so how do we even think about a submatrix well let's define it for us as a pair of two coordinates because we know that the submatrix like let's say this is one for example it's going to have a top left corner and it's going to have a bottom right corner so we need four pointers to actually Define it you could use X and Y kind of like the problem does but that can get kind of confusing cuz with matrices X actually goes on this side and Y goes here but a lot of people will do the opposite so instead of confusing yourself I prefer to use row and column so I'm going to say Row one is going to be here that's the beginning row two is here column one here and column two here those are four pointers in this case so in other words for us to enumerate every single submatrix in the original Matrix it looks like we need four Loops because we have four pointers and that's actually not it that just tells us like what each submatrix is after that we have to go through every value in the submatrix and accumulate that and that's going to be another two for Loops nested inside those now the dimensions of this let's say are M by n cuz it's not necessarily going to be a square Matrix like this one so we need 2 pointers for this two pointers for this and then this like the inner uh two Loops that's also going to be like iterating over this entire thing which means every single row every single column so therefore it's going to be M cubed * n cubed doesn't look very be M cubed * n cubed doesn't look very be M cubed * n cubed doesn't look very efficient and I actually won't even bother coding this one up but the question is given everything I just showed you what part of this do you think would be the EAS easiest to optimize I mean we kind of have to create or at least look at every single submatrix this part doesn't look easy to optimize if it's even possible but this part accumulating the sum of a particular submatrix it might be possible to do that let's try to simplify the problem if we had a onedimensional array do you know how we might be able to like let's say we just want to compute the sum of an arbit subarray and it could be any possible subarray do you know a way we could possibly compute that in constant time well at first it looks like there's not cuz we kind of have to iterate over every element in here but we have technology we have the power of preprocessing our data what we can do is compute something called prefix sums and a prefix sum is pretty simple it just means we take every single prefix starting at the beginning of the array it's basically a subarray starting at the beginning of the array and compute the total so this would be a prefix and then we'd get both of these elements add them together and store that here so this is a prefix same thing here this would be a prefix etc now if we do that going back to the original problem to compute the sum of this prefix all we need is take the element here which tells us the total of all of these elements and remove from it The Element here which tells us the total of all of these elements that logically looks like it would give us the total of this sub rate and that's what prefix sums do can we apply that in 3D somehow let's try when we were talking about a one-dimensional array we computed the one-dimensional array we computed the one-dimensional array we computed the prefix sum starting from the beginning of the array similarly let's try to do that in this problem we know that a submatrix might start anywhere like the top left corner could be anywhere it could be here anywhere but to simplify it let's say that our top left is always going to be here and this is kind of the way we're going to do prefix sums I don't know a good word for it maybe submatrix sums that's probably the word the phrase that I'll be using throughout this problem I don't know if that's like the accurate way to say it but submatrix sums starting from just this top left corner so what that mean that would mean getting this like so far we're just doing one dimension right the prefix here and then also the prefix here so that was one dimension and going over to two Dimensions would be like this now we're Computing this and I guess I'll actually just compute it in front of you so the first row is going to be zero here and then Computing these two and the way we're going to compute the value that goes here is just by taking the original value here which is one and then adding to it the prefix sum that's over here so that is going to remain as one right now and then to compute the value here we take the prefix sum plus zero we're going to put a one here as well to compute the value here we take the original and what do you think we should add to it because remember the value that goes here should represent the sum of this and that makes it obvious we want the value up above so we take 1 + 0 and then this stays one so we take 1 + 0 and then this stays one so we take 1 + 0 and then this stays one what about over here and this is where things actually get interesting because you know I haven't even told you why we're Computing these in the first place we don't necessarily know this is going to help us so now let's actually think about this let's say we want the sum of this Matrix right here how do we get it well let's suppose we've already computed the submatrix sums let's say for example exle this value over here represents the sum of all of these elements okay how do we calculate this efficiently perhaps in constant time well we know that the value over here is going to tell us the entire sum of the input array but we don't want that do we but luckily the value stored over here tells us total of all the values over here and luckily the value over here tells us the total of all the values stored over here so what can we do can we just take this value and subtract these two values well it kind of looks like there's a problem over here doesn't it because if we try to do that we're going to end up subtracting this value twice what does that mean does this approach not work think about it for a second how could we fix that well we're literally Computing the submatrix sums we have the value that's going to go here even if it wasn't just a single value if this was a matrix we would still have all of that portion the duplicate portion is going to be stored over here so what we can say here is for this particular Matrix where R1 is here R2 is here column 1 is here and column 2 is over there so now we pretty much have shown that the submatrix sum of this particular Matrix is equal to and I'm actually going to call this total sorry because let's say we've already computed the values from this submatrix sum then to remove this coordinate over here we're simply going to say submatrix sum uh this is what I'm going to call the uh 2D grid on the right by the way it's simply going to be the row up above that's row minus one so here we say Row 1 - one at column 2 so we subtract that 1 - one at column 2 so we subtract that 1 - one at column 2 so we subtract that we also o subtract the value over here on the left so sub suum at Row 2 at column 1us one and I added a negative over here cuz we're subtracting uh these two but we're adding the value over here so sub sum at row two uh column 2 sorry I made it a little bit smaller we're running out of space so this is the portion over here this will add the whole Matrix and these two will remove this part and last we want to read the top left corner back so here we say add sub suum of Row oneus one as well as column 1 minus one so this is the formula you're going to see me using in the code explanation just to clarify the only thing that I've proven to you is if we can somehow compute the submatrix sums then we can easily compute the sum of a submatrix in constant time but how exactly do we compute these submatrix sums so far it's easy so far we got the first row that was trivial that's just prefix sums and getting this value all we had to do is just take the value up above cuz it's also kind of a one-dimensional array but also kind of a one-dimensional array but also kind of a one-dimensional array but now we finally got to the 2D portion and it's going to be pretty much the same as what I just showed you because to get the value here we're trying to compute these four values so obviously we take the one over here and put one here we take the value up above which tells us all of these two so add one again and we take the value to the left which tells us these two and so we add the one again but don't forget we want to probably remove this top left because we just added it twice cuz we added this portion and then we added this portion so that's all I'm saying here to compute a value at a coordinate like this in this array we're going to look up and look left add those and then we're going to subtract the top left we're also going to add the original value here as well so let's quickly compute this now so in our case uh we just do the 1 plus 1+ 1 we get a uh we just do the 1 plus 1+ 1 we get a uh we just do the 1 plus 1+ 1 we get a three here now to get the value here look up look to the left add the original value that's going to be 3 + 1+ original value that's going to be 3 + 1+ original value that's going to be 3 + 1+ 1 that looks like five to me but don't forget to remove top left so we end up with a four here and that four looks right to me because when you look at this array it looks like the sum is four okay here same thing look up look to the left but now we kind of realize we're probably going to need to handle the out of bound cases which isn't going to be super hard but just keep that in mind because if we're looking up left and top left we might go out of bounds now in this case the original value here is zero we add one to it we get one value to go here the original value is one we look up here so then we end up with a five don't forget to remove this so we end up here with a four the value here is zero we add eight subtract three we end up with five here does that look right five yep that looks like the sum of the entire Matrix so we did this correctly now that I've shown you all of this we can code up the solution if we can compute every submatrix in constant time the number of submatrices is m^2 time the number of submatrices is m^2 time the number of submatrices is m^2 n^2 so that's going to be the time n^2 so that's going to be the time n^2 so that's going to be the time complexity of this solution and looks like space complexity is going to be Big O of M * n let's code it up but at least O of M * n let's code it up but at least O of M * n let's code it up but at least in Python this gets time limit exceeded okay so with 2D grid problems I like to get the dimensions cuz I like to refer to them as the number of rows and the number of columns and the first thing we're going to do is compute that submatrix some 2D grid so first I'm just going to create a 2d grid of the same dimensions up above and just fill it in with all Zer and then I'm going to just Traverse over the grid so for Row in rows for column in columns now to compute the value that goes here submatrix sum at this coordinate we know at the very least we're going to add and I think we probably don't need parentheses we're going to add the original value so Matrix at row column then we want to add the Top Value then we want to add the left value and then we want to subtract the top left value sorry if that sounded confusing the way I spoke it but the way I'm going to set these variables up isn't going to be super crazy so let's say the top is going to be equal to submatrix sum and we know that's the one just up above so it's going to be Row minus1 in the same column uh but the problem is which one of these could go out of bounds probably this one row minus one we're subtracting from it so let's only do this if row is greater than zero but if it's not greater than zero let's just say the top sum is zero that's not a bad default value to put in this equation it won't change anything so we're going to do that and for left let's say it's equal to the submatrix sum in the same row but from the column we want column minus one but we're only going to do that if column is greater than zero otherwise we'll set this to zero and lastly we want top left and that's going to be submatrix sum at row minus one as well as column minus one so either of these could become negative and we could say if row and column are greater than zero but a slightly shortcut is just taking the minimum of both of those and checking if that's greater than zero if the minimum is equal to zero then we'll evaluate to false and then assign this to zero so this is what we're doing you don't have to do it this way you could actually write out an if statement and then put code inside of it this is just a good style I think because regardless this formula now works we don't have to like write this formula multiple times to finally actually count the number of submatrices that satisfies the condition we're going to count that in this variable and then we're going to return it now let's try to enumerate every single subarray so we can do that like this for R1 in all of the rows and for R2 in all of the rows that come after the first row so for R2 in range R1 all the way up until uh the number of rows well I guess not just after this could include this as well so I kind of misspoke and pretty much same thing with the column so for column one in range of columns and then column two will go after that column one up until the number of columns a lot of Loops so now we have our submatrix and we want to compute the sum of it we have the four app pointers so let's say the current sum is going to be equal to the sub suum ending at R2 column 2 but we know this is actually too big what do we want to do with this we want to subtract from this the top we want to subtract from this the left and then we want to read the top left back because we subtracted it twice so just like this if you look this is actually kind of the opposite of the above formula but if this is confusing to you I would just rewind back to the drawing or maybe draw it out yourself because it 100% does make sense yourself because it 100% does make sense yourself because it 100% does make sense when you actually look at a picture because remember all of these submatrix sums always start at the top left corner whereas these do not start at the top left corner that's why we have four pointers here now let's just get these three top left and then top left said that twice uh so top is going to be this it's going to be the sub sum at R1 minus1 and staying at column 2 but again we're only going to do that if r one is greater than zero otherwise let's set it to zero left is going to be the sub suum at R2 and then column one minus 1 and only if column 1 is greater than zero otherwise it's going to be zero and then top left is the easy part I guess sub sum is going to be R1 minus one and then column 1 minus one and again if minimum is greater than zero so there we go we got the current sum of this submatrix but what do we do with it well if it's exactly equal the target then let's increment this result whoops had a typo this should be sub suum but you see that this solution actually gets time limit exceeded so let's see if we can optimize it okay welcome to the seventh layer of hell where we're going to try to optimize this one and I'll just tell you that it's going to be really hard without the background knowledge of leak code 560 so if you want to go watch that video you can but I'll try to review the important part right now it's basically this same problem except with one dimension suppose the question that we're actually trying to ask is how many subarrays in this array sum up to some particular total value some Target well in an array there are N squared subarrays like n starting from the beginning and then n starting from here etc there's going to be a lot of subarrays so for us to even get the sum of each particular subarray even if we do it in constant time we still have n s subarrays how can we possibly solve this problem more efficiently well let's reframe the problem there is some Target value we're looking for let's say here let's iterate over this array just a single time and every time we land at a position like this one let's ask how many subay ending at this position some up to the Target so how many sub arays would that be it'd be possibly this one and possibly this one how many of these guys sum up to the Target well how can we possibly make that more efficient don't we have to look at every single subarray think about the math for a second let's say the value at this position is occur let's say we also have something we're keeping track of called the current sum which tells us the total of all the values that we've seen up until this point now there's something really clever that we can do we can have a hashmap where for every single prefix sum we keep track of how many times we've seen prefix sum with that particular sum so just assume that we have this assume that we have up until this point we've computed every prefix sum this prefix sum and this prefix sum now we're going to take a shortcut we're going to compute the current sum minus the target value that we're looking for current sum minus Target what does that tell us it gives us let's say a value that I'm going to call the diff at first you might think I got this equation wrong at first you might think shouldn't we take the Target and subtract from it the current sum no because what the diff represents is this is the value that we need to remove from the current sum to make the current sum equal to the Target so if I were to write out that equation just to prove the algebra to you I'm saying current sum minus the diff is equal to the Target and if we rearrange this and solve for the diff we're going to get diff equals current sum minus Target so that's the diff we're looking for what do we remove from the current sum to make it equal to the Target and the reason for that is because if we happen to have a 500 IQ and we were able to come up with the idea that we should count the prefix sums like this then by the time we get here we know do we have any prefix sums that we can remove such that this subarray is equal to the Target and not only do we know how many prefix sums we have let's say it's somehow possible that removing that prefix sum makes this equal to the Target let's say it's also possible that removing this prefix sum makes it equal to the Target and that would probably only be the case if both of these are zero and maybe this value here is like five and the target is also five but that's the idea we're doing this in one calculation we are Computing all of the subarrays ending at this position such that it's equal to the Target that's not simple to understand it's even harder to come up with but that's the idea that we use with one dimension we optimize n^2 use with one dimension we optimize n^2 use with one dimension we optimize n^2 down to Big O of n so can we do the same thing with this and the answer is yes let me show you how oh and by the way when we initialize that prefix sum count that like hash map we're always going to initialize it mapping the key 0 2 1 and the reason is cuz that's kind of like a base case let me quickly show you an example of why we would do that suppose Target is equal to 5 suppose this array the first value is equal to five so now five is equal to our current sum we take current sum minus the target which gives us a diff of Zer so now to our result we want to add how many prefix sums have we seen so far with a diff of zero if our hash map is empty we're not going to end up adding anything to the result it's always going to stay zero that's why we initialize it like I said and also as we are iterating through this array every time we compute a current sum at the end of that iteration we're going to add that current sum as a prefix sum to the hashmap I was talking about now let's jump in to this when we had a single array instead of us looking at every single possible subarray which would need two nested for loops and also two pointers right one left pointer and one right pointer to tell us the boundaries of the array we actually just used one pointer when we were talking about the optimization right now and that optimization told us the ending of the subarray similarly we're going to do the same thing in two Dimensions we're still going to have two pointers for Row one and row two I'm actually going to put them here for the example I'm going to show you but we're going to have just a single pointer for the column and that's going to tell us where that submatrix ends suppose we're doing that here so when we start we're going to initialize a hashmap and this hashmap is going to map refix sums to their respective counts in this case it's more of like a prefix submatrix or whatever you want to call it at this point but you get the idea so right now we're over here and we're actually going to be mainly iterating over this Matrix so I'll actually be mostly on this side so we want to know right now the current sum tells us this how do we get this well we know that the value over here tells us this entire thing but we want just this so what we're going to do is take this value and remove from it that value so right now our current sum is going to be equal to one it's going to be just this and by the way I didn't show it sorry the hashmap will be initialized with zero mapped to one so far at least now to compute the diff I'm going to take current sum and subtract from it the target let's say that the target is equal to zero so current sum minus the target is going to be one we check is one in the hash map no it's not so we're done with this submatrix does not sum up to the Target well this submatrix sorry these are the sums this is the original submatrix so it doesn't sum up to the Target now let's move on before we move on though we do take that sum which was one and then map it to the count which is now going to be one as well next we're over here our column pointer is going to be shifted over here we want to know at this point you might be thinking we're only going to be looking at this submatrix it's true we're looking at this submatrix but we also want to potentially consider this submatrix at the exact same time in other words we want to know given that these two rows are fixed how many submatrices ending at this column which like I said is just either this or this which one of those sums up to the Target and we can do that in constant time first compute the current sum we do that by taking once again this bottom value and subtracting this value because this value tells us uh this thing and this value tells us this thing so we get 4 minus 1 that's going to be equal to three current sum is three and that looks accurate to me when you look at the original Matrix there are three values there once again we would take current sum minus the target which remember the target was equal to zero and we would ask ourselves okay that is the sum that we need to subtract from here to make a submatrix that is equal to the Target now in this case that doesn't exist current sum which is 3 Min - 0 is 3 and three does not exist in the - 0 is 3 and three does not exist in the - 0 is 3 and three does not exist in the hashmap but let's just change the example just for a moment let's assume Target is actually equal to two so then the number that we're looking for is 3 - the number that we're looking for is 3 - the number that we're looking for is 3 - 2 which is 1 we want to know is there possibly a prefix and so far this is the only prefix we've inserted is there a prefix that sums up to one how do we know that well we would have inserted it in the hashmap it looks like the key one does exist in the hashmap and the count is equal to one so this count is what we're going to add to the result so that submatrix here this is that submatrix that sums up to one this is the current submatrix that we're at which Subs up to three if we remove move this guy then we end up with a sum of two and if two happens to be our Target then we found what we're looking for this is the idea that we are going to follow I'm not going to continue drawing this out because I don't think you want to be here all day and notice if we make this optimization which again is not easy to come up with we cut down the number of pointers from four pointers to three pointers and therefore the time complexity is going to be m^2 which complexity is going to be m^2 which complexity is going to be m^2 which let's say is the number of rows time n which is the number of columns that the big time complexity the space complexity didn't change so let's code this up now okay so I'm actually just going to take uh all this code here and remove it and then just have the column here going through all the columns and every time we get to a new pair of rows these are going to be fixed and that's when we're going to start counting for our hash map I'm going to create the hash map I'm going to call it count initially it's just going to be a hashmap a default key is just going to be mapped to zero so this will tell us for every prefix sum or submatrix sum whatever you want to call it is going to map to sum count and we're going to initialize it such that zero maps to one now for the first step which is just Computing the current sum of the submatrix defined by these pointers ending at this column that's going to be current sum is equal to the submatrix sum ending at row two and the current column that we have subtracted by the submatrix sum at Row 1 minus one remember the row that's up above at the same column and this could go negative so let's wrap this in an if statement so we can say this if Row 1 is greater than Z that's when we do that otherwise we set this to zero okay great now we compute the diff that we're looking for and remember it's kind of backwards you like expect it to be Target minus current that's how two sum works this problem is kind of the opposite of two sum so we're actually taking current sum and subtracting the Target and so this diff is what we're looking for in our hashmap if we find it in our hashmap then we want to add this to the result if we don't find it the default value with a default dict is just going to be zero so what we can say is result add to this whatever we find here either it exists and count is non zero or it's equal to zero and the last step of this don't forget we want to actually be updating this count as we go as we compute every current sum we want to update the count so we can say count for this current sum or a prefix sum whatever you want to call it is now incremented by one oh my Lord this is not an easy problem this might be one of the hardest I've done in a while I'm going to run the code and it looks like it works and it's about as efficient as you can get if you struggled with this problem please don't feel bad consider checking out n code. there's a lot of resources on there that I think can help you if you found the helpful please like And subscribe and I'll see you soon
Number of Submatrices That Sum to Target
high-five
Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target. A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`. Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`. **Example 1:** **Input:** matrix = \[\[0,1,0\],\[1,1,1\],\[0,1,0\]\], target = 0 **Output:** 4 **Explanation:** The four 1x1 submatrices that only contain 0. **Example 2:** **Input:** matrix = \[\[1,-1\],\[-1,1\]\], target = 0 **Output:** 5 **Explanation:** The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. **Example 3:** **Input:** matrix = \[\[904\]\], target = 0 **Output:** 0 **Constraints:** * `1 <= matrix.length <= 100` * `1 <= matrix[0].length <= 100` * `-1000 <= matrix[i] <= 1000` * `-10^8 <= target <= 10^8`
How can we solve the problem if we have just one student? Given an student sort their grades and get the top 5 average. Generalize the idea to do it for many students.
Array,Hash Table,Sorting
Easy
null
1,970
hey everybody this is Larry I don't even know if I know how to set this up anymore but it is the last day I think yeah of the June nickel day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem I will be doing this or um I don't know right I mean I did a two-month treatment we're still here so two-month treatment we're still here so two-month treatment we're still here so yeah uh we'll be doing it all July so hit the like button hit the Subscribe button and all those other buttons today's Farm is and oh yeah and you can see I'm back in New York if I would post up some uh belated drone videos just because man I have a lot of good ones I think so we'll see anyway today's Farm is 1970 last day where you can still cross so guys there's one base binary Matrix with zero represent line and one represents water itself because okay so we're gonna choose the last day okay and these are the day effects okay um hmm let's see right uh so that's the number of total cells and it has two by two at least okay uh let's see okay so now it goes um so I think from top to bottom by only walking you can up down left right okay I feel like I missed this in some problems recently where I confuse the traveling directions I just want to make sure I think this is basically um and diagonal up down left right I think this is basically um you know this is one of those problems where you're trying to ask almost the opposite where um you're trying to figure out how to you know from top to bottom but maybe the way that you cannot go from top to bottom is if there's a river or whatever you want to call it a body of water that connects from left to the right then that means that you're blocked off and you cannot um go right um and with that I think you can do um uh what you gonna call it uh Union fine uh destroying set Union or this yeah uh data structure to kind of calculate that am I right and then with that you can simulate one cell at a time I think that should be okay let me give that a try then right uh yeah so first we have to do the union fine stuff so I'm just going to put it in this in a set uh or maybe um no let's just put it a sec yeah and then you know just a fine operation for a cell um so I'm still just setting this up hopefully this should be cool to go to you fine times okay right someone like this right something like that anyways would you find a x a y u b y and then parents of viewers it would be someone like that should be good enough and then yeah and then we just kind of uh for so basically and we want to add maybe like a left one right so left is to go to zero right is equal to one this is just the enum lazy number uh so we set this pair wins think about you should do pounds I don't know right all right so then now we can do something like four i x y and enumerate cells uh yeah um now if x is equal to Z oh no if Y is equal to zero then we can we do a thing to the left right Soviet Union oh this reunion is kind of bad I guess yes and we're about to do another Union because we want to write something like uh left and X Y right something like that um maybe I'll just write it here but uh this is actually annoying hmm uh maybe I'll write just a little differently then maybe I'll do right as a um this is so hacky but this is why we have unums uh jeez does that work maybe it does I don't know what this actually does it should but maybe what advising the last one which is call minus one we Union two right that's definitely not right what is this left even and also there should be one and because apparently that's why it doesn't for an hour I think it should for an hour remember more hmm oh okay uh yeah and then otherwise we want to connect it to one of the eight adjacent cells uh water so actually we also want to do maybe a scene type thing what have I seen that at cells oops uh x y and then we do something like foreign like that right basically we're just looking at the eight directional adjacent things and then we check to see if they're in it if X and Y is in scene then we Union X Y with the nxny right um okay and then now if you find have left if you go do you find a way then we return I yeah maybe off by one but that should be okay otherwise we return just the last number right so yeah we still return I think oh I don't know if it's ioi plus one yeah let's do the link of cells right uh is that oh huh man I'm a little bit Rusty for some reason all right so that looks okay I am to be honest am I confident not really so let's give it a submit and see if I missed an edge case it looks okay so maybe I was right on this one uh yeah uh for the sake I mean I did I know that I didn't necessarily implement it that way but for the sake of argument let's just say you know these are all of One operations in that case then you can see that this is all one we do at most eight operations that are one and more of one operation so we're basically doing for every uh query we're doing all of one operation so it's O of Q um uh of Q time and spec uh and space because we have to do the union is depending on the number of cells that we've seen so far and so I've seen um so yeah uh that's all I have for this one Union fine and yeah all of Q time of two space and that's what I have uh let me know what you think stay good stay healthy stay good mental health I'll see y'all later take care bye
Last Day Where You Can Still Cross
sorting-the-sentence
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down). Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_. **Example 1:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\] **Output:** 2 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. **Example 2:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 1 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. **Example 3:** **Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\] **Output:** 3 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3. **Constraints:** * `2 <= row, col <= 2 * 104` * `4 <= row * col <= 2 * 104` * `cells.length == row * col` * `1 <= ri <= row` * `1 <= ci <= col` * All the values of `cells` are **unique**.
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
String,Sorting
Easy
2168
336
hello everyone welcome to CSE events I am Nishant here let's solved another lead code problem palindromic pair so in their worth it's telling that we have to find the pair of to a string if we will connect uh merge it we will get palindrome or Not Here example first if you will see ABCD tcba so if this true string will be merged then we will get a b c d dcba that is one palindrome so we will return the zero and one but if we will do dcba and a b c d that will give also palindrome so 1 and 0 is given now come to the third string LLS okay LLS and S is there if we keep s first of the LLS we will get S LLS so that's a concatenate so like that see the third example is showing like a and empty a string basically we will get just a but according to this problem we have to uh we have to add this empty string after the string and before the string means both we have to consider 0 1 and 1 0 okay so it's look like a big problem but it's easy only but it's good problem so let's solve it there will be three to four cases let's see first case will be like first case will be this case that if empty string is there so maybe like this it will be and it will return 0 and 1. excuse me and second it will be like this okay so it will return 0 okay all right now see the second example like this string is there we will use hashing in that we will store each and every string okay now if we reverse it if we get a string if we reverse it what we get b d c b a we will search this string in our hashing if it is there means okay fine we will take the indices of this and this we will return it these are easy only little bit tricky here what will be see here A B C D is given all right but here a this is we consider as a left okay and this string we consider as a right string okay if we reverse it what we get d c b and this one we will search is it available in our housing if yes then all right we will take it getting then second but where this in the uh this string we will keep this side like DCB a b c d then only you know it will palindrome right so don't do this mistake so what indices we will get we will keep this indices first and then we will keep this indices getting developed this now come to this next a b c b a so a b c is palindrome all right this left is right is palindrome but what about this right sorry this left we reverse it what we will get B A now we will check that this ba is available in that or not if available then all right now got it no what we are doing we are taking the right value first we are taking the left value and then we are doing the right value reversing then we are checking but in this case what we are doing we are taking the right we are checking right is palindrome or not and then left Valley we are reversing it we are checking it so truth we are going to use the preset so let's see list integer oh okay no one more list new or a okay map string we will keep a string and indices and teaser okay keep name as map name is in name is so important so don't give anything or else you will be confused it's going to be a long problem lengthy problem now third will be like set we will keep the just keep names it we will keep the length of the substring length of the each string see it's b80 bad so we will keep three okay likewise we will keep three set okay now keep value to the hashing okay so map dot put words I and I okay and in set also what we will keep in set we will keep the length of the each string so I dot length sorry for that okay now got it till here okay no problem okay so what we do now we will Traverse from starting to end what's dot length okay so now what we do so what we do here we will take the length of words I dot length of the string okay so if length is equal to 1 that this case okay if length is equal to one what we do we will check that if we will check that palindrome or not so here we will check that if this hashing is containing any empty string or not so how to check then map dot contains key if it is there then that's all now we can add it what we are going to add arrays Dot as list okay so we will add here I and indices of that inputee string okay so map dot get okay this we will add it that's all one more time will be there first we have to add the indices of empty string then I okay so if you don't know all those things if you don't know how to um develop logic and all okay I'll announce later first to see this if we got this okay we will just continue it like this Loop will be again it will start it will go to next uh element I can say yeah now check for the before checking we get the reverse badly string Rev or they can say reverse string is equal to new string Builder words I okay Dot reverse it dot to a string okay we got reverse value now we check if that this reverse value is hashing is containing or not contains map rev Str if it's there means what we do we just copy paste this if it is like this then we can get the I r a v s t r okay this two cases we have seen this two cases over these two cases over now we will see the uh that this case is this second part okay so how to do that for that we need to Loop through the hour uh okay we can take K or J whatever okay only okay we have to look through the this set okay it's okay set okay if K is equal to length what is this length then break no need to check this length okay this length why because all already we have checked this so we don't need to check for same number but if not there then we will check what we will check if palindrome is not is there or not PL i n t r we mean palindrome so what we are going to send the words I and forth see this we will take first four right and then we will take for left okay so what else we can take for left then right okay zero length minus K minus 1 y like this because I'll explain this is the maybe uh DVC is there DVC values K three is there this value is 4 is there so 4 is there no length is 4 so 4 minus 3 minus 1 what we got zero so we are just going to check for this value so this became our left substring and this become our right server string this right one we will reverse it and we will check it's there or not getting okay so this became our left one that's all now reverse string S1 you know how to reverse it right same only okay what we are going to send words I and okay it got reversed if this value is available then we will print it if not then map Dot contains key if it's there S1 it's there means that's all we will just keep reverse dot add so first where you will keep this so This value we will keep the if left no so left should come in Middle okay this value will come the last so string I hope you are getting string S1 and S1 word dot get okay zero uh length it should come so this is the hour which this is our um left so it will be right it will come here I minus not I minus I'm I comma okay comma this okay Okay so here what missed okay we have to take here we have to send the reverse string we can take this also but that's okay we will take this and in this reverse we will take the substring service string from where to where from uh from that will be the right part okay so length minus k so here we are going to send I map dot get S1 okay all right so same thing we will do for right also okay is palindrome reverse zero now we are going to send the k and length minus 1. okay this is going the reverse left okay this is going reverse left and this is going reverse right okay all right so S1 then we will take the zero this will give the right value okay this will be the right value the result dot add as list and now here what we do we will keep our make it you can make it as two to avoid the confusion then I okay that's all I guess we will check a class no problem now okay this only we are going to return right our duty return my rise result okay and we have to make one function right Boolean is parallel and ROM palindrome okay so a string as int I into Z till where we check if s dot carrot I doesn't equal to s dot guided J then we will just return the false if not then we will return the true okay here only we can increase and decrease the value so I hope that's all let's check the answer and if you are striking in building the logic then just subscribe my channel and click the notification button so I'm going to start the I am going to start the weight okay I'm going to start the array series from scratch and there we will see the um what it's it will not let me do string dot length I right yeah already so I was telling that I will be starting ah let me finish then I'll announce 45 s dot k what's problem here S2 it should be S2 okay return where we have missed okay it will be out right I don't know why did I keep uh prices we don't need actually okay nope so no motor what now whatever here all right what's dot length here we need to take length right yeah words that are a length okay and here map dot okay here come we have to check that for itself it's not taking no map dot get reverse string hope so yes all right so now run it we'll check map dot reverse and whatever now contains I and map dot get okay it should not been yeah all right sorry for diaper so map dot get doesn't is equal to oh my God it's lengthy problem so okay that's okay no issue uh return now it's all right let me submit yeah that's all guys if you are getting uh stuck in logic building and all I am going to start the new series that's I will tell the array series that will be from scratch if you are interested just uh subscribe my channel and just press the Bell or Bell icon you will get update and from there on that I will be uh explaining you from uh I can say scratch from scratch I'm going to explain each thing like why this Loop is here why that Loop is here why everything I'm going to explain from the basic so just subscribe my channel and wait for that video thanks guys thanks for watching see you soon bye
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
109
hi guys good morning uh before starting just a quick request if you guys like the videos which I have been posting or if you guys after watching the video like it then please do the like button it helps to motivate a lot if you don't then you can also press this like button it's up to you guys but yeah please take action it helps motivates a lot but yeah let's quickly move to the question it says that we need our we need to convert sorted list to a binary search tree cool we'll see everything what's the sorted list what a BST and everything firstly it says that we are given the head which means the head of the linked list of a single link list with the elements are sorted in the sending order elements are sorted in the ascending order which means that every element it goes on keep increasing cool no worries and we want to convert it into a height balance binary service tree for the binary surgery it's a tree in which left node has smaller value than the root node right nodes have the bigger value than the root node and height balance which it means is that if there are n nodes so basically the height or the level although they both are different but still in same sense they are used so basically height or level should be Max of login or basically the Seal of login you can also see that but the height should be balanced which means that if the tree becomes something like this so you have to make it something like this which means that it should be balanced right it should not go Way Beyond in one side and not another side right cool no worries now we got to know okay what's the height balanced what is a BST and all that stuff now let's see the quickly example what it says so basically we are given the link list which means that we will be pointing to this head pointer of this linked list and we want to what we need to return is the head pointer of this tree now you can easily see that okay if my request is minus 10 3 minus 3 0 5 and 6 9 which is sorted minus a minus 3 0 5 and 9 so basically if we move on to this and we want to make this BST we need to have it starting from 0 why because we need to have it balanced right so we will start from 0 which means I take this now the left part will come in the left side and the right part will come in the right side so now as 0 is the root so you can see here 0 will be right here and here it is the left and then here it is the right here it is the left here it is the right of my three and after that here is the left and here is the right of my nine so it is how the tree is formed so basically we have this root node after that we write the left of that root node and then the right of that root node after that we put after that we use this root node and then we write the left of this router and right of this root node after that we use this root node then we write the left of this root node and then the height of this Loop node it is how the tree is written cool no worries so now what we have to do is that we have to return this particular tree to our answer which means the root of that node and this special case maybe you have to put in mind that if it is null then we have to return null because we can't negatively from it if the root is null so we can just simply return a null now one thing we saw that we have to the linked list from the but the root node will be that mid of that linked list which is so the head of the root node basically the head of the tree or the rooting of the tree will be the middle of the link list right we saw right here right because it needs to be balanced so the root node of the tree will always be the mid of the linked list okay we got to know one thing okay the root node it needs to be the mid of this linked list so we need to find the mid of the linked list now so now the question became okay find the middle of the link list so to find the middle of the linked list we have two options one very standard option you just iterate on this whole linked list find the length of this linked list and then make the length by two and then again iterate on this linked list up till the N by 2 length and then find the root element okay we are trading two times on this linked list complexity will be two into n although it's n but still it sounds more right there's a better option right here we use a slow in the first pointer slow pointer moves one step at a time and pass pointer moves twice as fast as a slow pointer what will happen is when the fast would have reached the end slow would be at the mid because they both are moving not in the same speed but the fast is moving twice as fast as slow so basically as the fast would have reached end my slope would have been at the mid because the speed is twice so it indicates that we can just have one iteration have slow and fast pointers and I can just have one iteration and my slow would land at the mid index itself and I don't need to do multiple iterations and it's just above n by 2 because I'm just iterating on the half of the list kind of right still it's open but still we have reduced one iteration all together so it's a better method we will use this method although the standard question to find them into the linked list it's a standard question but yeah we thought okay what we need in this question it is to find the middle of the linked list which is actually the root node of the tree cool now we have one thing okay we can find them another link list let's see firstly how we'll find it suppose my slow and the fast is pointing at one then my fast slow moves one step and my fast moves two steps so slow will be here and fast will be here now slow moves One Step fast moves two steps slow will be here fast will be here slow moves One Step fast moves two step slow is here fast is there now you can say okay again let's move slow but you can easily see that past next is a null so it means that it cannot move because null next will never happen so ultimately it cannot move here so they both have to stop here it may have happened that maybe fast would have landed at the end it's for sure hack can happen but it's never the case that okay anything can go beyond this so now our slow has landed at the location which is actually the mid and we said that the mid will be the root and hold so every time I can pretty sure only see that okay I can find the mid of the linked list which means that I can find the root of any portion of the linked list cool so basically with this slow I have pointed to the link mid and it's the most optimal way now we are we have reached out slow which is actually the root now okay you find the root how about the left part and the right part it's pretty simple right the left part itself is the left sub tree and the right part itself is the right sub tree so just if you're standing at the slow ride which is actually a root node now you have to move your logic to the left part and to the right part so for that you need to have some other pointers also so let's take very standard start and end pointers which actually points to the start and end of the array why it is needed because you find slow and fast cool no worries but now you have to shift to the left subtree in the right subtree for shifting to the left subtree let's say you want to shift to the left sub tree you can just have the particular question right here for that you know the slow cool but if you never knew the start right so just Mark anything as a start for sure it's easy for you guys now you can know this pointer by slow of little next right but how about you need to make sure okay you have something in the end so just have let's say it's null so you just have this thing okay my left subtree is from start to slow and my right subter is from slow next which means after just after slow up till my end cool with this help I can just iterate on my left and right subtree recursively how let's see firstly we saw what is root cool no worries we saw what was slow and was rude we got the route we are happy now we need to find actually we need to attach this particular element to for this we need to find the left subtree cool recursive we will find what's the left subtree so basically our slow will be pointing here cool now it is the new list which means the start and end will be like here again this two and fast will move slow and fast will move again and ultimately slow will Point here and fast will Point here right let's change the color yeah let's take it white so basically now ultimately my slow and fast is half rested for the left subtree ways to have listed it is the so the 2 will be the root we can see easily here 2 is the root now again for this two I need to find the left and the right subtree let's take this as a left sub tree and right sub tree start and end will for sure be the Saturn of this particular list cool no worries now as it is the root it is a Leicester tree I just again made it okay let's have start an end I moved by slow and fast and as fast next to next is null for sure I cannot move so it is the root now if it is the root what will happen is that I just pointed as a root it is you can see it is the root and if again I have to go then I can easily say okay see I just have it as a left subtree and write subtree but if it is one then certain end points here so I can just return another because you can easily see that below this is actually a null so you can easily see that how I did and what I did right now if I go back what would happen was if it was a left subtree if it was the left subtree then I just iterated on the left part which means that I have this two then I just found one what about the other part it is with this part so it is the right sub tree of two which is you can find with the help of three and four so it is just a start it is the end it start and uh slow and fast pointer Square fast pointer stands here so it is the root so basically and same I can do for the other half also it is the right half so it will just break down to slow and fast slow will point to the root ultimately again in The Next Step I'll just have it break down to start to slow and slow plus one which is slow next to end it is this left part of this particular root node and it is the right part of this root note with this help you can easily see that what I did I basically had a slow in the fast pointer I just wear ever slow Lance it's a root my root left will point to whatsoever my left subtree will bring me an answer and my root right will point to whatever my right subtree will bring me the answer and my right left subtree will recursively make its own tree and my right subtree will recursively make its own tree which means that if I have this list and whatever route I have find I just attach my left subtree root mode with it and write subtree root nodes With It ultimately my left subtree will itself make its own tree by its own self my right Supreme itself make its own tree by its own self and that's what I wanted my work is done by recursion cool no worries you can easily see by this R actually tree is made because here I will just attach my root node with the result whatsoever the left part will return and it's actually returning this particular root mode itself which is two here I will attach my root node with the result of 6 which is just the right subtree root node and with this help and they both my two will have a left part as one right part as three which is actually a Creator itself because once left part is null once right partitional three is left what is null three is right part is not so basically everything is being made required by recursion we just choose root node and we just choose okay left part make it right equation right part make it by recursion and it's the same thing what's happening so it is the main function here firstly base case as you can easily see that it was a base case in that problem I just have this base case now I just had the start and end because ultimately at every step I just need to know start and write with this help I can actually find slow and fast so I just point it by start and my and in then what will happen is at every point I just initialized my start and end and also a base condition that okay if massage is equal to n so I need to return null why it is because here as you can easily see start and end was equal sorry if it would have gone here at this base case where one was remaining so start and end were equal which means it is returning null which means that if one is here so it will return these two which is null because it's the leaf node right so it is a base case now I initialize my start and end pointer I just moved my pass pointer until it is not equal to end right so that my flow would have reached the mid with this help my slow and fast have reached to the correct location which is slow pointing at the mid and that's what I wanted because slow at Mid is nothing but my root head root or head anything you can say so slow is actually at my mid location of the linked list which is actually what the head of the linked list head of the tree so with this I got the head of the tree now it's just a part of recursion that okay I'll just call the left part which is start to slow and the right path which is slow next to end and my recursion will take care of everything of just finding and attaching the root node with the left Roots left and it is roots right and ultimately I need to return the head because I need to return the root node of this linked list of this tree I hope that you guys liked and enjoyed the proper intuition how we reached how we find why we thought of finding the mid and how we thought of finding the mid because of that slow and fast it's never that okay we need we had two options we can choose any two options we choose the optimal options so ultimately the complexity of this problem is O of n log n because for every login levels as I said as it's a high balance binary surgery so the number of levels will be login but at every like login levels to find the mid I am iterating on this whole list kind of you can say n by 2 but still it's off in login so basically and for finding that okay what's the mid what's the root I'm just iterating on this whole list but I'm doing the same process for every login levels thus you can easily see that its complexities in login and space extra space although to make the tree I just use a tree node every time I made it as you can if you see I made a new node but it's not the extra space we have used is zero so yeah that's the problem which we had I hope that you guys liked it if you guys enjoyed the like button it helps me a lot there goodbye take care I adopt it I don't know
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
209
Hello gas welcome to me YouTube channel, so today we are going to solve problem 209 minimum size sanctuary, so what is this question about, I have been given a target and this is given, so I have to extract such a thing from it. Whose less is less, give him greater and equal, you should be the target and he should be the minimum, who is all the best, Sir Sabir will come out in it, if you have to remove the minimum in the morning, then this is the question, then how can it be done and it is also written here. Follow up, first I have to figure out the solution of witch time, then any number will be formed from one side, see if it is bigger than 7, then now if we do it from two sides, then from two sides, you are three, one, you are three. Five four two three then three four three is the last one, it is possible to make 7 from it, so we will directly return two sizes, whatever we reduce is four three, is n't it 7, so it is possible from 2 sides, see sir, give two out of that. We will see the maximum. We are making two-sided Sabri with two sizes. Now it will also come out even. We will making two-sided Sabri with two sizes. Now it will also come out even. We will making two-sided Sabri with two sizes. Now it will also come out even. We will see the maximum from it. Yes, then making it from two sides is possible if it is greater than the target. Equal, you have gone 2s, increase it like this. It is possible to make, now this is what we are doing, now we are doing linearly, we are looking from one, then we are looking from you, we are looking from three, we are looking at force, well, we also applied binary search to that. We can because if this is so much then it is so much that if any length is taken in between then it is of kar length if kar length is the target which is your very big a is the target which is and the target is 7 and given and ma Take, how much is the maximum I am getting, can it be reduced, yes see, like I have to remove the window size, what will I do to remove the Windows One thing is that if we take out all of two sizes, then this will be your time complex N square, we will come out in front of all three, two, five and three, two-five, so if we want more of two sides, and three, two-five, so if we want more of two sides, and three, two-five, so if we want more of two sides, then we can do this and but the answer which is behind. If we remove that then we will make mines What is it, we reduce the same by one, that is, take the window size from one and the last whole means as much as the size can be, which is the window side and if this is the window side then now make it less. If you try then now the range will be less then hey he will make mid mines one and if it was not possible that means there were two like here for two see one size window see lake na tu aaye one toh one hai one three hai one One is one, you are then four is 3x also did not make 7, so now what we did was we added the window size plus that yes we will make it bigger than that, why are we doing this here because see here it is written in the constant that The element inside the name is positive, one to 10, you give it to the power of four. If it is not positive, then no relief, they do not do this because it can be plus or minus B, so we are doing it here because it is positive here. What has happened is that yes, if we move forward then only plus will come because if we add positive number then only plus will come, brother, that is why we will meet you guys and make plus one that yes, it is not less than that now, so now increase it by one window size and check it. But we are getting it, mother, we got it on this, so we are seeing it decreasing the window size, now what are they doing, it is simple, this is a sliding window, calculate it in the evening, then when the window side is taken out on the size, like the window size here. Thana window size, take it out on this window size, we are taking out the maximum on this window, okay, we are reducing the one that is strawberry on this side, we are taking out its head in the morning and then from there, we have to take out its maximum. That is, from this and from the maximum, check in the last which is the maximum, if give greater, the target is greater, give equal, you mean to make possible, this is the key in this and the second one, what is there in this, one thing, this one is just a side sliding window that now it is doing sum plus. Is k pe and if equal tu jo size k a is going then we are just going to have the same one, this one is here we are doing i plus, we will do i plus, so what will we do before that, we will subtract the i before that, this is the answer. If you are there, then you will be removed. If it was -235, then now we will mine it. We will mine it. Then in the was -235, then now we will mine it. We will mine it. Then in the was -235, then now we will mine it. We will mine it. Then in the next window, the sum of these two will be calculated. Then we will mine it. If it was 3 2 5, then how much will it become. Three and then it will be plus. Next, we will do plus again, here K plus is happening at the bottom, so now it will be equal, just ahead of that, we will keep fixing this window, if it is not coming, then take a look at a sliding window, now that is the last one. What will happen in the second one? Yes, then take this in the second one, now take this as an example, now from the same sliding window will be installed in this also, now we will keep doing it, so is there any benefit, the evening will increase or the window size will also increase, I want a minimum that it will go up to four. What will happen i1 and j1 will reach i1 will reach j1 and how much will be four sum four will become four this one at the back will be mined from the same sliding window one will be reduced now till we remove it till we give greater then 4. They are just decreasing and till the time there is four, its answer is also being calculated because give greater is equal to four means give greater is equal to target and if you want the answer not till the target then just do the same if your greater give is equal to target. So we are going to do mines and add plus to it and we are also going to calculate the answer in this because the valid answer is greater give equal, you have to do some calculation and that's it till the time we are doing the last, the very last value. Because the advantage of this is that if we see now, here the positive value is even bigger, that is the advantage, otherwise I want the minimum, so we will go till the very last, till the time it gives greater, you will also keep calculating the answer. These and the same is doing the same in this and is doing the same and the k plus is doing and if here we have come here we have mother, I have gone to your end maps means there was no such target no one was less that was greater than equal. If you are the target then you have come here for any length of morning, it means nothing is possible, hence the return from here will be made zero, it is written here, see brother-in-law, if all returns are zero, then there will see brother-in-law, if all returns are zero, then there will see brother-in-law, if all returns are zero, then there will be no one, then no, not here. It must have come inside this, we give greater equal, you are inside the target and if it comes, we will see, then this one here will blow it, now it has become zero, now your target has become big, but then it will come down, give greater equal, you are four and the target is before, so now This one for target, this one for four, so both are being made, one size of one side is possible, then this will also be stored in answer one, ok, see you in the next video, please like and subscribe. me channel
Minimum Size Subarray Sum
minimum-size-subarray-sum
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead. **Example 1:** **Input:** target = 7, nums = \[2,3,1,2,4,3\] **Output:** 2 **Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint. **Example 2:** **Input:** target = 4, nums = \[1,4,4\] **Output:** 1 **Example 3:** **Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= target <= 109` * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
null
Array,Binary Search,Sliding Window,Prefix Sum
Medium
76,325,718,1776,2211,2329
447
children myself startups are short and today we are going to discuss a lead code problem or 447 that is number of Boom ranks it is basically a medium level of problem so let us uh discuss it so the problem says that you are given n points in the plane that are all distinct where points of I equal to x i y i so basically it is saying that is there is an array with a name of points and at each index of that particular array there will be a list which consists of two elements that is x i or y i or you can say it as there will be a x coordinate or y coordinate of that particular Point okay so let us read the next part of that question so here it is again a boomerang is a tuple of points uh I J K such that the distance between I and k i and J equals the distance between I and K the order of the Tuple matters so what that means actually okay so let me explain you here so here you can see let's say we have three points I J and K so basically these will be called a boomerang basically three points will be called as a boomerang if and only if the distance between the ith means the point one point uh I point to the J point will be equal to the distance between I and K okay here I J K is basically a point which having two coordinates X and Y so each i j k have two coordinates a X and Y and the value will be different okay so basically what is what the mom rank is the distance between I to J will be equal to the I to K there is one more thing here we have to notice that is if we have I J K and the other one we have I K and G so these two will be considered as two boom ranks not a single Boomerang why because it is mentioned here the order of the Tuple matters okay means igk is called one Boomerang but if we Shuffle the values of other elements other than the pivot element here the pivotal element is I because we are checking the distance of other element from I so if we change the distance of other elements from this I or if we Shuffle the position of other elements let's say here J K and here KJ so these will become a new boom lengths okay so these will be these both will be counters different boom ranks so the total count will become 2. okay so let us see the example cases what is given here and we have to return the number of Boom Rings basically in discussion okay let us see the example here in the example there is a list given 0 1 0 2 0 so we have to uh the output written is 2 basically it means there are two movements how it will be to let's say uh let's find the distance between 0 1 0 that will be one let's find the distance between 0 and 2 0 so that will be 2. okay so the distance between the these point to this point is one and from this point to despite this two so it cannot be the boomerang okay so let us make the ith Point as one comma zero okay from I one comma 0 let's check the distance of 0 comma 0 that will be 1 from 1 comma zero let's check the distance of two comma zero that is uh also one so basically if I make a i Point as 1 comma 0 then it will become one boomerang okay so here you can see if 1 comma 0 is the ith value means ith index here you can see the first one was ith okay if it is the ith uh point then J and K then the other points we can make a 1 comma zero and two comma zero as a boomerang okay and I also told you that Z comma K and K comma J if I shuffle the both the position then it will become a new wave so here you can see Zero comma zero two comma 0 and 2 comma zero and zero comma zero basically we Shuffle the position so it will become two boom line okay so that's why the answer is 2 if I check the case of 2 comma 0 so the distance of 2 comma 0 and 0 comma zero is basically to the distance of 2 comma zero and one comma 0 is basically one so the distance are not same so basically it can't make a boomerang so let us come on to this case if we check the distance of 1 comma 1 to 2 comma Tom or two comma two so here you can see it will be unroot uh two minus 1 basically uh it will be under root two if we check uh the distance of 1 comma one with three comma 3 it will be 2 and root 2 okay basically that will not be equal similar to the case for the three comma 3 if we check uh if we make I point as two comma two and check the other distance let's say from 2 comma 2 the distance of 1 comma 1 that will be what that will be under root 2 similarly let's check the distance of 3 comma 3 from 2 comma 2 that will also be on root 2 so both the distance are same if we make 2 comma 2 as the ith point so there will be two cases two comma two one comma one three comma three and we Shuffle the J and K point that is 2 comma 2 3 comma 3 and 1 comma 1 so basically there are three Boomerang sorry two boomerang next example that is 1 comma 1. here you can see there is here it is only one point given so we can't make a boomerang with only one point okay so that's why the answer is zero okay so let's see the constraint so constant is given that and the value of n can goes up to 500 and the point size length is equal to X Y can go from minus 10 to the power 4 to plus 10 to the power 4. okay let us move on to the solution uh to me uh took uh just to make some intuition let us think it from the Scratch sorry okay so um what uh like just think it from the sketch if I want to uh just find this three point uh in which one is the pivot point or you can say the ith uh from one we say the I point and from that point the two uh the other two points distance should be the same so what we can do as per the code okay so we can uh make we can use some for Loop okay so what it will do this is the our first for Loop so it is to uh fix the ith Point okay whatever that is from what we are seeing the distance okay we are seeing the distance from ith point to J and ith 0.2 distance from ith point to J and ith 0.2 distance from ith point to J and ith 0.2 K so that is fixed by this first Loop okay then let's see here you can see let's say the our the ith point is P1 and we check uh we uh fix this point P1 now we are checking the distance of P1 with P2 and let's say the distance is 8. okay n now what I will do I will find the third point which will be having the same uh distance okay so what I will do I will check it let's say the P4 have the same distance with P1 that is 8. okay so this is the first case now what I will do I will choose the second point that is from P1 to I will choose the second point that is P3 and I will check the distance let's say it is 4 then what I will do I will see what are the points having the distance 4 from P1 let's say P5 have the distance okay I will check and see let's say P5 have the same distance from V1 okay so basically this is the scenario how it is working so the first Loop is fixing the ith element okay so this is the first Loop now we are iterating over the second element that is P2 P3 in this case so for that we want for loop again so that is the second for Loop that second for Loop is for what fixing the second element and for fixing the second element we find some distance uh let's in this case here we find the distance 8 and as per this distance we find the other third element that have the same distance from this P1 okay so that is uh for that to find the third element we need to go through or you can say we need to iterate with the use of the third Loop okay so here you can see we are moving over three Loops okay and three Loops that basically iterate over the whole length let's say the length of an array is n so it will iterate Over N basically it will go n times it will also go in time so the time complexity will become so high that will go so the time complexity will become n and uh Inner Loop and then that also have inner loop so the time complexity will become n to the power 3 basically n Cube so these time complexities too much High because we have a inputs of 15 or sorry 500 basically the array length we have 500 so the 500 to the power and Cube sorry the 500 to the power 3 will become so high okay so it will be uh so costly uh algorithm to find a number of Boom links so let us uh simplify it okay so what we can do to simplify it let's think over it okay so let me clear this first okay so now here uh till this uh what we discussed what Boomerang actually is now let us discuss what we can do to solve this in a much easy way or a simpler way okay so for that what we can do we can use hash map or you can say in Python a dictionary okay so what we will do we will fix some point okay we will fix some point and we will find the distance of other points with respect to that point okay let's say here are three points i j and k okay what I will do I will fix the first point and I will find the distance of K distance of J okay let's say they are uh one two three four five elements so what I will do from the first point there are five points basically this point represent X Y coordinates okay so what I will do I will find the distance of this and when I am finding the distance I will maintain a map okay so what I will do I will check that is there element with the same distance is present or not if there is no this no element with that distance then it's okay then just create new entry and put the value as 1 because we found one element okay here in the example here you can see the upper example you can see from P1 to P2 let's say our fixed point is this okay this is our a fixed point okay and from the fixed point we are finding the distance to P2 basically if we found it as 8 so what I will do I will make an entry of 8 and a value 1. okay now uh we will check the distance of P1 to P3 okay what we will found we found the uh distance of P1 to P3 is 4 and we have that particular one point having the distance 4 from P1 so we will make an entry four and the value 1. okay now uh now the uh in the third distance that is from P1 to P4 so what the distance of P1 to P4 that is 8 so what I will see I can see in uh what I can see in the map that 8 is already present so what I will do I will just increase that means I found two elements means uh the one is there means I already have one element with a distance set and I found on another element so what I will do I will just increase that is from the uh from the previous number of uh elements on with the same distance we found one more element so I will just increase the count so I will make it as 2. so that means we have two elements at a distance of 8 from a point P1 okay which is that uh that is P2 and P4 let's go move on to the next one that is P5 okay so what's the distance of P5 from that of P1 that is basically 4 okay so what I will do I will see in the map and I found that 4 is already present and uh the value is one so what I will do I just found a new element which also have a distance 4 so I will increase the count by one so basically what it does is it just we just counted the elements with the same you can say uh distance let's say I make one more element here and name it as P6 and the distance of P1 to P6 is you can say let's say three okay so what I will make it here I will make an another entry because no one is there with a distance 3 so I'll make another entry with a value of 3 and assign a value of 1. okay now I have to find the boom ring so basically the keys are representing the distance and the uh values are representing number of points number of points with that distance okay so basically this is the stuff so uh so now we can see how we can find a boom rank from this particular map okay so let's let me tell you how we can do that so uh let's say for a boom link We own as we know from the question for a boom line we have three points that is i j and k okay so I just made only this map is only for a particular Point P1 so what I am doing here I am telling you how many boom links can be made if I face the point P1 okay so here you can see from P1 uh from P1 that is uh distance at a distance of 8 there are two points okay so this I is basically P1 and from P1 there are two points what are the points P2 and P4 which are at a distance of 8 so I will make let's say I can I will make this as P2 and this as P3 okay but as I told you earlier the order of the Tuple matters so it can be possible that it is P3 and it is P2 okay so basically there are two boomerangs one is P1 P2 B3 other is P1 P3 P2 so this is the two ohm length at a distance of 8 okay similarly I can make a same again that is I J and K okay now if I check I am checking it for the distance of 4 so this element is P1 here the J is what here the J is P3 and P5 okay let's say this is for the first time it is P3 and it is sorry uh it is P3 and it is P5 foreign it can be possible it is P5 and it is P3 as it is mentioned order matters Okay so uh so there are two boomerangs how it can be two the first one is P1 P3 V5 the second one is P1 P5 and P3 so there are two boom links from this okay uh there is uh one more uh distance we have in our list uh in our map that is of three okay so let's take that case also so there will be three points i j K okay so the ith one is what it will be P1 and the jth one is what uh the jth one is they are one point so the one point is P6 okay so that is P6 but what about K we don't have any point uh at a distance of three uh to be putted on K okay and we know a boomerang will only made when we have three points and that should be with a certain criteria that I J distance will be equal to ik distance but here we not have three points we only have two points so we can't make a boomerang from it okay so we will not consider this there are zero Boomerang from this okay at a distance of 3 and there are two boom ranks at the distance of four there are two Boomers at a distance of eight okay so uh this is uh like how the stuffs are going on let me uh so let me also explain you uh first example using the same how the answer is coming so here they are three point zero one zero two zero okay so I will make it for the one zero only 1 comma 0 Let's make the map so we have to make the map for all like zero comma zero one comma zero two comma zero we have to make the map for all let's let me make the for also it will be clear okay so from zero comma zero the distance of one comma zero okay will be what let's say we are taking 0 comma zero that means basically the value of I is uh zero comma zero now we have to find the value of J and K okay so what our approach is saying we will go to each point and we will find the distance of that particular point and we will put uh the count how many points are coming on to the same distance from our ith Point okay so what we will do I will go to the ith that is from 0 comma 0 I will check the distance of 1 comma 0 so that will basically one okay so from I uh zero comma 0 the distance that is 1 there is a element 1 means there is one Element okay now check from 0 comma 0 the distance of 2 comma 0 okay so that will be 2 so from 0 comma 0 at a distance of 2 there is also one element so this is basically the map or if I see how many Boomerang can make or make from it so as I told you earlier I J K so I is basically 0 comma 0 in this case Okay J if I take J for the distance of 1 okay so there is only one point at the distance of point and if I put it on J then there is no point uh there is no point to put it on a k so which also have the distance of 1 from I so as I told you earlier there should be at least three points so we can make a boomerang from it at a distance of one so let's check the booming of zoo we can make a boom link uh from is zero comma zero at a distance of 2 or not okay so if uh there is one point at distance of two let's say I put it on Z so there is no point remaining to put it on okay so we can't also we can to also make a boomerang from this also okay so uh so there is no boom ring from point I uh zero comma zero okay so let's take then another Point okay so that another point is what 1 comma zero one comma zero so we will similarly make the map okay so that map basically consists a key as a distance and a value has a number of points having the same distance from one comma zero okay so from 1 comma zero the distance of zero comma zero is what that is one okay so the distance one for the distance one we found one point okay so now check the distance of uh from 1 comma 0 to distance of 2 comma 0 that will also be 1 okay so that if that will also be 1 so we don't have like we will check there is on already a point with a distance of one so we will increase the count so the count will become 2 so basically what uh this making us a sense is there is a element okay there are two points at a distance of one so this is showing the distance this is showing a number of points okay so there are two points at a distance of one from I or you can say ith point or you can say the value of i as 1 comma zero okay so now uh there is no point remaining so to uh let us know how many Boomerang we can make it from here i j K okay let uh the value of I is here the value of I is 1 comma 0 okay so from 1 comma 0 we have two points at the distance of one okay let's say the first point we may place it here the first one let's say 0 comma zero okay if I play 0 comma 0 here then for K I have the point 2 comma 0. okay so this is the first boom link one comma zero two comma Zero from one comma zero two comma zero the distance is one from one comma zero two comma zero the distance is also one okay it can be also possible so this is become the Fun Boomerang so it but still it can also be possible the value of J can be 2 comma zero and the value of K can be 0 comma 0 so it will also become a one valid Boomerang because the distance of 1 comma 0 and 2 comma 0 is 1 and the distance of 1 comma 0 1 0 comma 0 is also one so it will also become a valid Boomerang so the two Boomerang will be 1 comma zero two comma 0 and 1 comma zero two comma zero so the total sum of Boom rank will be 2 from a point I let's move on to the other point that is let's take I is equal to 2 comma 0 okay so from 2 comma 0 if we see the distance of 0 comma zero so the from 2 comma 0 the distance of 0 comma 0 will become 2 okay as per the formula uh distance between two points we found the distances to if the distance is 2 we found a one point at a distance of 2 okay now check from 2 comma 0 the distance of 1 comma zero if we check that we will found the distance of 1 comma 0 from 2 comma 0 that is one okay so we found a point at a distance of one so we have one point at a distance of two one point at a distance of t uh at a distance of one and we know for making a boomerang we need i j k that is three points if I fix this particular I as 2 comma 0 then I want two points at the same distance uh to be putted on J and K but if I see for the distance 2 we have only one point so I can put it either on J or either on K but one will remain uh unfilled so it can be make Boomerang at a distance of two if I check at a distance of one so there is also one point so I can also make uh I cannot make a boomerang with that also from a distance at a distance of 1 from 2 comma zero means there is no case to make a boom ring from 2 comma 0 or you can say fixing the value of 2 comma 0 as I so there is 0 so from the all the three points making that as fixed as the value of I and checking how many Boomerang we can make so the total count will become 0 plus 2 plus 0 that will be equal to 2 okay and that is our as per the example so let's code it uh fastly so okay so before coding let me increase the size so here uh you can see as I told you I have to fix each and every Point okay to fix each and every point I have to low power each and every point now so I will Loop over each point so from point in point for point in points I will Loop over each point and on each point what I will do I as I told you earlier I have a map like for zero comma zero I created a map of distance and a particular number of points similarly for one comma zero similarly for two comma zero so for each disc so for each point I have to have some maps so let's say I just name it as a point let's say Point map okay uh so this is the point okay so next what I have to select one point here in this case we selected 0 comma zero and then what we'll do I just uh found how much distance this uh 0 comma 0 from 1 comma 0 and 2 comma 0 and then I uh just inserted that into uh the map and increase the count as per number of elements at the same distance so the same processor we will do it here so I will found the distance of the other points okay so let us save the other point at the second point okay so let me increase it will be easy to read because the second point in points okay so what I am doing I have to find the distance so the distance formula as we basically know is X2 minus X1 square and plus uh Y 2 minus 1 y 1 square to the whole under root okay so we have to first find the distance or difference of the X2 minus X1 so let me make it easy to so basically point zero minus the second point is second Point zeroth index similarly we can do it for y by just changing the index okay so this is for y so and now we are finding the distance so distance will become uh so as per the distance formula that is under root of x square plus y Square so we will do the x square plus y Square here I am not doing the square root as We Know if I have two values x square and you can say a y square or you can say x to the power 1 by 2 or you can say x to the power unroot okay so I can square both side and cut this one by two and I can say x equal to Y similarly I am saying to find a distance from this element to this element we are using the formula under root of x 2 minus x minus k n plus Y 2 minus y square and similarly we are using the same formula so what I am doing I am squaring uh for each point so I am not considering square root for each point if you want you can use square root and import the Met library but I just want to decrease the operational cost so that's why I am doing this so it will be much easy okay so in the next step what we can do uh firstly I will check is that is there any element in our dictionary or you can say in our map that is we made it uh that is we created here is there any element already present at the same distance so I will check if the element not in this uh not in that particular Point map dictionary or you can point map then what we will do I will create an element okay with the distance of what we found that is this and I place the initial value as 0 okay then what I will do if the element is present if the distance or you can say the key as whatever the distance we find is present in the point map if not if that is not present then I will create that key and put the value initial as 0 then what I will do whatever the value is whether we are checking the second time here you can see we are checking the second time so you increase the value by 2 1 okay so similarly what you will do here we will whatever the value of this we will increase that by 1. okay now here we can see we will move on uh here we can what we will do we have to find for how many Boomerang we made from that okay here we you can see I just uh me uh go through I just uh help you to go through a particular uh map and found how many Boomerang we can make okay so here you can see for key comma well basically value in point to map to dot items so basically what it is doing it is basically giving us the key and value pair and I am storing the key in key value in well okay so what I will do okay there is one more one thing we needed we need result here okay so what it or you can say result as count okay so what it will do it will just count how many boomerangs are there okay so what I will do plus equal to okay here is one more interesting concept that let's say um there are uh okay at a distance of 2 for any element let's say I at a distance of 2 there are four elements okay so that what that means I J K so the first point will be I and from the Four Points let's say the fourth point four points are a b c t Okay so it can be possible it will be a and it will be B but it can also be possible now it can be e it can be C it can be possible it can be a it can be D it can be possible it can be B it can be C so there are number of combinations you can make from this four okay so as for the permutation combination we know if we have two uh two spaces this is the first this is the second so if we have two spaces and we have some certain amounts of items then we can find how uh like how many possible number of uh permutations of that okay so for two points we can see uh if we want to fill two points then we can say for the first point I can make four choices that is I can put either A B C or D and for the next one I will remain with 4 minus 1 that is three choices because I use the one here okay so I have four choices here three choices here so uh the total permutation will become four into three that is 12 so there are 12 number of ways to put values here so they are that will become 12 boomerangs because there are 12 different combination with I you can make similarly you can see we can make this and this so there we are making two combinations so we are saying two boom length so similarly we are making 12 combinations so we are saying 12 boom ranks okay so what we can conclude it here so whatever the number of possible outcomes we have okay whatever the number of possible points we have to fill it on the place of J and K so to find the boom link what we can say uh the number of points we can we have let's say the number of points we can fill is K okay so the number of points we can fill K into K minus 1. similarly you can see the here the number of points is 4 so it is 4 into 4 minus 1 that is 3 so this is basically how we conclude it uh number of Boom links as per the number of points we have uh to fill at that particular two points okay so basically what it will come it will valve or you can say if you are going as per the variable I took there so you can take it as K that will be K into K minus 1 okay so it what it will do it will just calculate all the number of Boom links for that particular ith value and it will just add it into the count so for each ith value whatever the number of boomerang we are finding we are just increa adding in and adding it into the count and uh at the end what we will do we'll just return count okay so let's test it for the test cases foreign okay so let's test it for the test cases so here you can see it is passed so let me submit it so here you can see it is passed with a 98.15 uh percent less memory than other 98.15 uh percent less memory than other 98.15 uh percent less memory than other than 72.98 speed then as compared to than 72.98 speed then as compared to than 72.98 speed then as compared to that of others so here it is all about that number of Boom links problem so we'll meet in other video with other delete good problem or some other coding platform interesting prop oh so this is all about uh number of boomerang problem we will meet in other video with some interesting problem so this is all about lead code uh so this is all about uh number of Boom rank problem we will meet in next video with some interesting this is all about number of Boom rank problem uh we will meet in next video with interesting uh this is all about number of boomerang problem we will meet in next video with other interesting problems thank you
Number of Boomerangs
number-of-boomerangs
You are given `n` `points` in the plane that are all **distinct**, where `points[i] = [xi, yi]`. A **boomerang** is a tuple of points `(i, j, k)` such that the distance between `i` and `j` equals the distance between `i` and `k` **(the order of the tuple matters)**. Return _the number of boomerangs_. **Example 1:** **Input:** points = \[\[0,0\],\[1,0\],\[2,0\]\] **Output:** 2 **Explanation:** The two boomerangs are \[\[1,0\],\[0,0\],\[2,0\]\] and \[\[1,0\],\[2,0\],\[0,0\]\]. **Example 2:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 2 **Example 3:** **Input:** points = \[\[1,1\]\] **Output:** 0 **Constraints:** * `n == points.length` * `1 <= n <= 500` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the points are **unique**.
null
Array,Hash Table,Math
Medium
356
174
hey everyone today we're going over dungeon game so the way this game works is i'm going to start in the upper left hand corner i can move either right or down and my goal is to get to this corner where the princess is and these numbers are basically telling me as soon as i enter this room this is the amount of health that i'm going to gain or lose so if it's a negative number well i'll lose two health and then if it's a positive number like this one then i will gain one health and the question is asking what is the minimum amount of health that i need to start with such that i can make it successfully to this corner where the princess is and basically i will die as soon as my health is less than one so as an example let's say we're entering this square here if i have zero health well i'll basically die immediately because my health will be less than one however if i have three health i can enter this room successfully because i will have health one remaining after i enter this room so let's take a look at how the initial example provided works if we have a health of seven initially so we enter this room we're left at five health then five minus three now we have two health then we enter this room we have five health and for this room then we have six health and for this room and we have one health and that means that we have successfully reached the princess and we win the game now let's say the health had been six well then we would have four health upon entering this room then one health then four health then five health but once i enter this room i will have zero health which means that i will die and lose the game hopefully the structure of this maze or this dungeon here reminds you of using a dp solution so the equation that we're trying to solve is at each room what is the minimum amount of health that i need to enter the room and then the second part of the equation is well there are two ways to enter each room and which path should i take a look at how to fill in our dp grid here so if we look at our destination that's saying we will lose five points of health as soon as we enter this room right and the only way that i can survive entering this room is if i have health greater than or equal to six right if i have five units of health if i enter this room then i'll have zero units but the problem states that we need at least one unit of health to survive entering a room so i will go ahead and fill this in as six bottom row if i want to enter this room i'm going to gain 30 points of health and that's way more than this negative 5 i'm going to lose right just remember that the problem said the minimum amount of health that i need to enter a room is one unit so the minimum value that we'll ever put in this dp array is going to be one similarly here i'm going to gain 10 units of health won't need that much and i can just put a one here alls we're going to look at are along this right wall here and these ones are a little bit easier to think through because there's only one way to get to this cell which is the cell above it right so this room is saying as soon as i enter i'm going to gain one unit of health and if we look below it this is saying that i need six units to be able to enter successfully right so if i had five units initially and then i gain this one unit of health then on my next turn i'm able to enter this room successfully that's why this value is a five and if this value is saying that i'm going to gain three units of health and i know that i need five units to be able to successfully reach the princess from this cell then i just need two units of health right so let's walk through this if i have two units here then i'll gain three and i'll have five enter this room five and then i'll gain one then i have six units and then i'm able to successfully enter this room because six units minus five is still greater than zero here as well now let's fill in this middle square here so we're going to lose 10 points of health as soon as we enter right but we know that the next two options on where to go well one of them only requires one unit of health and one of them requires five units of health so i'm going to want to go to the one that requires less right so if we think about what this value needs to be well if i have 11 units of health and then i lose 10 i'll be able to survive entering this room and then i can successfully make it onto the next room which only requires one unit of health really for this cell i'm going to lose 5 units of health as soon as i enter so i'll need at least six health right and once i have six health i lose five i'll be left with one unit of health but luckily i only need one unit of health to enter this room so that's why this value is going to be a six now when i look at this cell i see that the next path that i want to go to is going to be this cell because it only requires two units of health so if i start with five units of health then once i lose my three units i will have two units of health and i can successfully make it to this room here and finally this cell i'm gonna lose two units of health initially and the next cell that requires a lesser amount of energy is going to be this one and it requires five units of health so that's why i need to start with seven units of health here so we see that the minimum amount of health required is going to be seven and the path we're going to take is seven five two five six so here i've typed out the process that we just ran on this dp matrix to fill it in notice that each of these statements always take the max of one and some other expression and this is because if you think about the problem statement it says that we always need a minimum health one to enter a cell that is really important to understanding this question and the reason that this value could ever be negative is in a case where the cell has positive and we wouldn't want to say oh well i only need negative 29 health to enter this room because i'm going to gain 30 right because your health always needs to be positive so when we looked at the bottom row we only had to look at the number directly to the right of the current cell so let's represent it as i j plus one and for the right column we only needed them to look at the number that was right below us and that is dp of i plus one j and for the rest of the grid well there was a decision that we had to make here which of the two cells to the bottom or to the right has a lesser cost which is the min here and then we subtract off the cost here so as an example let's say we're on the cell this negative 10 well what is the minimum between 5 and 1 it's going to be 1 right and then 1 minus negative 10 gives me 11. so what is a max of 1 and 11 that is 11. we'll use these equations to fill in the grid from bottom right to top left and the question is asking what is the initial health that we need well that's represented by this value at dp of zero so here's how the code looks one thing that i'm doing to save a little bit of space is instead of dedicating a separate dp matrix i'm just reusing the original dungeon matrix that was provided to us so what we're doing is we're starting from the bottom right corner as indicated by this iteration pattern and this statement is just saying okay if we're at the bottom right corner we'll initialize it to the value that we decided on earlier now this is saying well if we're on the bottom row we just need to check the cell to the right of us if we're on the right column i just need to check the cell directly below me otherwise i make the decision is the bottom or the right cell the one with the lower cost and i subtract the cost of the current cell that i'm on and take the max with one and finally i return the initial cost which is at 0 and if i submit the code we see that it is accepted thanks for watching
Dungeon Game
dungeon-game
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step. Return _the knight's minimum initial health so that he can rescue the princess_. **Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. **Example 1:** **Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\] **Output:** 7 **Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. **Example 2:** **Input:** dungeon = \[\[0\]\] **Output:** 1 **Constraints:** * `m == dungeon.length` * `n == dungeon[i].length` * `1 <= m, n <= 200` * `-1000 <= dungeon[i][j] <= 1000`
null
Array,Dynamic Programming,Matrix
Hard
62,64,741,2354
17
let's do leak Code 17 letter combinations of a phone number together it's going to be really easy it's going to be really fun given a string containing digits from 2 to 9 inclusive return all possible letter combinations that the number could represent return the answer in any order as an example you can see you have two is set to ABC three is set to DF and so on and so forth I hope you're familiar with this if not you're probably an iPad kid and you've never seen this before in your life but wait you see this on iPads never mind as an example we have digits equals 2 3 and our output will be letters from 2 first so a c and then D EF proceeding so we have a d AE AF as you can see this is from two this is from three and so on and so forth we need to create this keyboard here that represents all of the different like the different combinations that we can have and it Maps each number to the letters that are associated with it let's get started and you might be like oh Connie I think it's a decision tree you are correct we are going to go very deeply into how to convert said decision tree into code cuz I feel like that's really important and I've been kind of skipping over it I got a drawing pad so I'll show you how to do this we are first going to start out in our decision tree with absolutely nothing so an empty string and from this empty string we want to get the three different combinations that you can get for the letter two so we're going to use the example 2 three Okay so this first level here right we start at index zero which is two this first level here we want to get all letters associated with two which is a b and c and on this first level it has to be either a b or c and it can't be anything from index one or the number three or the letters d EF so how do we go about doing this actually quite simple from here from an empty string we want to add in the first letter of two which will be a so we can do empty string plus a and that gives us string a so how do we get from here to just string B alone this is what we're going to do we are going to need to use backtracking right and we need to go from a back to an empty string so in order to do this we've combined an empty string plus a to get a so we can say our current is currently equal to empty string plus a which is also equal to a and for that in particular we can remove a from our string so how are we going to do this we'll do current and you can slice it and remove the last character in it once you remove the last character in it we can set our new current to equal our empty string we can repeat the process and go empty string plus b and that gets us B okay great so how do we do this with C it's the same thing we need to remove B from the equation and then go here to C it is empty string plus C and that is how we get C all right great now let's keep going so from a we now have to call our function again and go over an index to index 1 or 3 and for three we have DF so for that first call we can do a plus d and that will get us a d but if we want to go back now that we have D let's do the next combination for a which will be a e so we do empty or we not empty string anymore but now we're doing the current string that we have which is a plus e and we get a e and we do so by removing D from our string a and when we remove it we can get it back and we can do this by doing once again our current string is equal to a d and then we can say current is equal to current and we'll slice it so we remove that last character so it's everything in the string except for the last character and then from there we can add an e and we can continue down and we can do the same process for the last letter here which is a f we can do this for B and C as well so we'll get b d b e b f that's a b c d c e CF and these are all nine combinations that we are using here in our output so it makes I hope that conversion helps kind of give a little bit more context on how to do this basically when it comes to backtracking you add in whatever you need to add in and then you keep going down the path so you would call the function again so typically I call it backtrack and then you remove what you just added in and so we know we are done when our length of our current string is the same as our digits so in this case there's two here and there's two here in terms of like how many characters are in it and so we know we can add that into finally our final list which will be an empty list initially We'll add in a we add in AE etc until we get to CF so let's code this I cheated somebody in the discussions actually posted the dictionary for us well we didn't actually have to code that part out but you would have to code this out if you're doing an interview you can also see that they gave us the edge case for example two which is just an empty string and it returns nothing and say if the length of dig digits I don't know why it capitalized there if the length of digits is equal to zero we can just return an empty list otherwise we're going to have all combos which is equal to our empty list which was what we'll return at the end from here we want to have our backtrack function we'll call it death backtrack we'll say current or we can say curve to continue on with what I had which is our current path and then we want to have the index that we're looking at and from this backtrack function we need to check and say if the length of current equal to the length of digits then that's when we want to add it to all combos which means we hit the last like path part and we say all combos that append and we're going to append current and we'll return out of that otherwise what we want to do is we want to iterate through keyboards but we want to iterate through this value of keyboards so we'll say four in uh keyboards and we want to look at the current index that we're at so it will be digits index so digits index will be let's say it's index zero digits is 2 three and in that case we'll get two back and we'll get this so we'll be iterating a b and c so from here we'll say for C and keyboard digits index you need to add in to our current string so it's CER Cur plus equals c so we add it in then we can backtrack again and for the backtrack we can go current and then we want to do index plus one cuz that gets us down to the next level and the next level will be three and then we want to remove it so in order to do that we do current cur1 slicing as I spoke about earlier and now we want to backtrack so we want to start out with an empty string as we spoke about earlier and we want to start at index zero so every time we go through we've added in the new character that we're looking at within the particular digits that we want and we actually increment our index by one and we'll iterate through in this case this is iterating through the value of the current digit we are looking at okay so we can run it all three cases are accepted submit first time submitting yay and we did it let me know if you want to see more leak code problems
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. **Example 1:** **Input:** digits = "23 " **Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\] **Example 2:** **Input:** digits = " " **Output:** \[\] **Example 3:** **Input:** digits = "2 " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `0 <= digits.length <= 4` * `digits[i]` is a digit in the range `['2', '9']`.
null
Hash Table,String,Backtracking
Medium
22,39,401
338
hey everyone today we are going to substitute for the question counting bits so you are given integer n return array answer of ranks n plus 1 such that for each I answer I is the number of ones in the binary representation of I so let's see the example so we should check example two so n equal 5 output is zero one two so that's because uh um finally the presentation of zero is zero right so one is one and that 2 is like a zero one zero right something like that so that's why uh so there is only one uh one in the binary representation so that's why output is one here right so 3 is Omega 0 1 right and there are two one in the binary representation so that's why output is 2. so 4 is Omega one zero so that's why I output this one and the five is a one zero one so that's why there are two one so that's why I had to put these two before I start the my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let me explain with this example so you see the yeah Japanese but I think you can guess so this is a decimal and this is a binary representation so to solve a discussion I use a dynamic programming so how can we apply dynamic programming to this question so let's look at the from 0 to 3 and uh from fold to seven so did you realize that so these are like a repeating work so okay from four to seven so let's delete this one and then look at the um two numbers that's almost right and so four is at 0 and there so look at the zero here zero right and look at the five and the zero one and then let's go back to one so zero one and one zero so let's go back to two zero one and then let's see the seven one and then let's go back to three one right so that's why uh these are actually repeating work so every time we count the number of one and then use the counting later so let's look at the from 0 to 7 pass us oops zero two seven passes and eight to um 16. so yeah these two are also repeating work so eight is a one zero and if we delete like a d have this one and zero is uh so let's go back to zero and the zero one so let's go back to um one so one right and uh next one zero 100 101 110 and then 100 11 and 100 aw and then um we go to next um like a unit digit one more important thing is that so somebody wondering so when we are like I'll be doing four and seven we go back to um with four right so when we are four go back to zero and we when we are five we go back to one right but uh when we are like I'll be doing eight and uh 15. we have to go back to eight right so move back to eight and the pointing zero we are nine I'll go back to one like this so to solve this question um we should know when we go to next digit so that's simple just a 2 4 8. 16. and the next is 32. so yeah I think you can guess like a two multiply two is four right and there are four multiply two is eight right and eight multiply two is sixteen right so look at the um two so two when we are two so we go to next visit right and then multiply two and I look at four so binary representation like I go to next digit right and the four multiply two eight and I look at eight so binary is a one zero so seven is a one so when we are eight we go to next digit and uh let's look at the 16. so from 8 to 15 so we use it like a full digits right here but from 16 so we go to next digit and use five digit here so that's why when we already take a 2 4 8 16 this kind of weed is this kind of number so we changed that like a number as like a subtraction number so I'll show you how to write a code reader and then so we can solve like a like what how many numbers we should go back yeah so that is a basic idea to solve discretion so with that being said let's get into the code okay so let's write the code first of all interest DP list with interest to be zero multiply n Plus 1. and then so let's say subtraction number start with one and then start looping for I in length and the one two and plus one so y start from one because uh decimal zero is obviously zero so we don't have to care about a zero because we interested to be zero and then if subtraction number multiply two equal index number and then update subtraction number with current index number after that update DP list equal DB minus DBI minus subtraction number plus one so y plus one so um this one actually comes from the most significant digit so let's look at the from four to seven so in the previous section first of all I did it's a third digit from light so this one and then uh we go back to um like a minus four so when we are four go back to zero when we are five go back to one so that's because um from 0 to 3 so we use a two digit right so that's why this DP list has number of one in the two digit right so from four um we use a like a subtle digit right so that's why this DPS doesn't have a like a solid digit number so that's why um every time we need a like a plus one for like the most significant digit here in this case uh SAR digit from right so that's why we need a plus one and then after that just return DP list yeah so let me submit it looks good and the time complexity of this solution should be order of n because uh we iterate through um from like a 1 to n and a performing constant time operation within each iteration so that's y order of N and the space complexity is also order of n because we create a DP list to store the count for each number so that's why time space complexity also order of n yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
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
4
all right so okay the element of two sorted arrays so they give us uh array one and array two these are both sorted and they want the fifth element in the amongst these two arrays that are sorted so for example if we put those two arrays together and we had some final sorted array the fifth element would be one two three four and five so this would be the fifth element here which would be six so we return six okay so let's talk about how we're going to do this so what we're gonna do is we're gonna partition our arrays in a way where we find the k smallest elements and once we have our case small elements we can just return the kth element so for example let's pretend that i partition my let's pretty much have two arrays here so this is one array and this is my larger array and i want to partition this first array let's say i take one element from here that means and if k equals five i have to take four elements from the other array because this would give me five elements and what i'm claiming here is that these are my five smallest elements amongst these two arrays and uh now we need to actually check are these my five smallest elements because uh if they're not then we have the wrong partitioning and we're going to keep looking for we're going to correct our partitioning until we get the correct one so uh what we got to ask okay well is everything inside a partition smaller than everything outside the partition because if there's something smaller that is outside the partition that means we have the wrong partition we don't have the k smallest elements so is this one less than this three well it'll always be so everything on the left in the same within the same array everything on the left is always going to be less than everything on the right because this is a sorted array right so everything here will always be less than everything on the right because this is sorted but what we need to check is across the two arrays so what we need to do is like check if is this one less than this 12 here yes it is but this is 9 this 9 is greater than this three which means we don't have the smallest elements in our partition in this case we don't have the five smallest elements in our partition because we found something outside the partition that is actually smaller than what we have inside the partition so what we're gonna do is we need to get rid of this nine so let's just say i decrease this partition by one if i decrease this partition by one that means i have to increase the other partition by one right because we want five elements here so uh now we ask ourselves the same question do we have the five smallest elements well is this three less than this nine it is this eight less than this five no which means we found something outside our partition that is smaller than what's inside the partition so we don't have the five smallest elements of the case smallest elements in our partition so uh we're going to decrease this partition by one and increase this partition by one and now is this five less than this eight it is this four less than the seven it trying to have the seven uh yeah so four is less than seven so yeah when we check like in an x like when we check if it's less than or equal then we uh confirm that we have the five smallest elements of the k smallest elements because everything inside the partition is less than or equal to everything outside the partition okay and once you have the correct partitioning so once we find so we just essentially found the five smallest elements for the k smallest element so once we did that all we got to do is look at the greatest number in these two partitions so it's either got to be this number or this number and because again this is sorted and the greatest number must be the one furthest to the right in both these partitions and we should take the maximum of the two so in this case we compare the five to the four the five is bigger so that must mean that five if we have the five smallest elements and that is our biggest number in those five smallest elements that must mean that 5 is our k element that we're looking for um so give me a second okay so um let's talk about how we're actually going to efficiently find uh the correct partitioning so what we're going to do is we're going to binary search for the correct partitioning so right the way i did it right now is i did it linearly but we're going to binary search for it so let's i'm just going to get into the code because i feel like if i don't want to overload you guys like all this information and i think it's better if i just like walk through the code and just do examples and for every line that's not immediately obvious so uh what we're going to do is let's call this out i'm going to leave this here in case i need it again i want let's try to guarantee i want to guarantee that array 2 is my biggest array because that'll make the logic easier so what i'm going to check is if array 1 is bigger than array 2 then let's just swap the parameters so i'm going to do i'm just going to call kth element again but i'm going to call it i'm going to flip the arguments okay uh so we're not actually going to use array 2. don't lengthen array 1. they originally were like m and n but that's so confusing when you're like actually typing out codes i just did away with them but anyway uh we're all we are gonna use array two and array one okay and this k here just wanted to make that clear so all i did was if array one is bigger than array two then swap array two and array one in the within the parameters though okay so uh now let's talk about uh the range of our binary search because it requires a little bit of thought so uh let's start with our low in our binary search we have a low we have a high and then you know we have a midpoint in a binary search so for our low this is going to be i have to use an example for this let's say so i have 10 elements here you can count them you can pause the video and count them if you want but there are 10 elements here you can take my word for it there's 10 elements there and there's some elements in there i don't care what that number is but let's say there's 10 here right there's 10 here let's say k in this case is equal to 12. if k is 12 notice that 12 this k here is bigger than the number of elements i have here so what that means is we need at least two elements from the smaller array so uh for example let's say i mean i'm going to let me kind of soft prove why so let's say i partition the first array like this where i take nothing out of the first array if i take nothing from the first array well i mean i have to take as much as i can from the other array so i'd have to partition it like this but if we look at our partition here we only have 10 elements but we want 12. so what we actually need to do is we need at least two elements from this other array so what we're going to do is say low equals math.max low equals math.max low equals math.max of array2.length because the rate 2 is our array2.length because the rate 2 is our array2.length because the rate 2 is our bigger array and we're going to do k minus that and let's say that say k is smaller than array2.length array2.length array2.length we're going to set this to zero and we actually want this we want so low is going to be an index so like inclusive so if 12 says 12 and this is 10 12 minus 10 is 2 but we that would mean that we want it to be at index 1 because right we have index 0 and index 1 that would be 2 elements so we're going to do is we're going to subtract 1 here because this would give us index 1 right 12 minus 10 is 2 minus 1 gives us index 1. okay cool so uh and if this is some negative number then we just set it to zero index zero okay and for the high this was going to be okay this is actually a really easy one so let's say k here it's like k is two right if i just want the second smallest element or the second element between these two sorted arrays well if i know this is my smallest array right well if k is two i want i can only take at most two elements from this i can't take i can't partition it like this because this would be four elements here right and k is only two so k can be at most two here and then if i say i took two elements from this first array well that would just mean that i partitioned this first array like this where i take nothing from this one and i take two from this one so uh yes what we're gonna say is i equals the math dot min of k and the length of the array so uh for example if k is bigger than the array length then we just want the array length as our upper bound for our binary search okay so um i think that covers are low and high pretty well so now we're going to just binary search almost done guys so while low is less than high uh what do we need to do we need well we need our midpoint right i'm going to call this let's see what should i call this um i'll call this partition index so this is my midpoint in this thing um now this is a hardware one to actually come up with but you know let's stick with mid whatever it's a low plus and i'm gonna explain what this mid represents with an example in a second um so we're gonna do low plus high minus low divided by two in case there's energy overflow because why not um this is our midpoint and now what does this midpoint actually represent so let's just copy paste this down here let's pretend that this is my low so l for low and let's pretend that this is my high out here this is so high is exclusive right um that's why i put it outside the array and low is inclusive and let's just say it's zero so our mid so let's see what how many else we have here we have one two three four five six seven so seven divided by uh two is what is that three yeah so that would be three in integer division so that'd be index three so zero one two three so our midpoint is going to be here okay what this represents is the last index in our partition so whatever our midpoint is you could think of like the bar that separates our array uh as being like in between so this is just midpoint is just the last it's just the index of the last element in the partition that we're choosing okay and let's say that um let's just say i had one that's what's a good way to do this uh let's go with a four here um and then we'll just put some a bunch of extra numbers okay so i just want to show you what the binary search is going to look like so uh let's say this is my bigger array here and this is my smaller array and this is how we're starting out right where i choose four elements from here and let's just say that k in this case equals six so if i chose four elements here that means i'm gonna partition the other array like this to where i take two elements from here and then i'm going to ask myself is this 7 less than this 5 and i'm going to ask myself if this 4 less than this 20 so i need these four values here so that i can compare them which means i actually need this index here right so uh i need um so how do i get this index this is just going to be this is dependent on k right so let's just call this mid 2. so if we call this guy m2 mid 2 whatever um this is going to be equal to k minus mid so let's see so in this case k is 6 so if k is 6 minus our midpoint which this would be let's see 0 1 2 3 this would be index 3 so this gives us 3 here but what we want is index one here because it's index zero this is index one right if i put this actually write out indexes if k is six and this guy right here is index three i'm going to put some numbers just to be really freaking really clear of k right so six minus three is three so we actually need to decrement by two here to get us that index one for the midpoint for that other midpoint in the other array um so i know that it looks kind of gross in the example but if you just work through it on your own you do a little bit like a little bit of quick math you'll see that you have to subtract two here to get the correct index okay so now what we're gonna do is let me get rid of this is uh in the way so we need to get those four values right like so that we can compare them so um let's just call this l1 so uh you know what let me i don't want to confuse you guys my variable names so i'm going to really quickly explain what they are before i even type them so let's say i have this partition and i have this partition this is going to be my l1 value this is going to be l2 and i'm just calling l for left so like the left in array one so this is gonna be this five l2 will be this eight and we'll just call this r1 and r2 here so for this seven and this nine okay i'll leave that there for a second so anyway um l1 is just going to be r1 of the midpoint right because we said that this was m and l2 just going to be r2 of mid 2. okay cool so uh now and then what we actually need to do is um this mid 2 here this could technically be like negative 1 because um what if we took every say we took everything from the first array and we take nothing from the second array uh we need to make sure that this mid 2 is in bounds so if mid 2 is greater or equal to 0 okay then we're good but if it's less than 0 we're going to set this to we want to set it to a value that will just make the comparison valid all right it'll make the comparison um yeah it'll make it valid so we're going to say integer min value because this is the left and when we compare this left to the right we're just going to check if the min value is smaller than whatever's on the right and this will just be true okay so now uh let's do r1 equals array one this is going to be so r1 is just gonna be one index past or it'll just be m plus one right because this is index m and that l one is this value here so we just want m plus one uh for this index here or for r to get the value of r one so uh let's do that m plus one but it could be out of bounds so we gotta check if m plus one is less than array one dot length then this is going to be okay but if it's out of bounds we're just gonna set r1 to some value that makes the comparison valid so we're going to do integer dot max value okay and now we just need to do r2 so r2 this is going to be one or our mid oh did i do m plus one this would be mid plus one and that should be mid plus one as well okay sorry so uh r2 this should just be mid two plus one right and we're going to do the same thing if mid 2 plus 1 is less than r2 dot length then we can go ahead and grab it so mid 2 plus 1 and we do the same thing where we just head to the max value all right so now that we have our four values we just need to compare them so i'm gonna go ahead and leave this here just so we can you just have something to refer to so we're gonna check if l1 is less than or equal to r2 and l2 is less than or equal to r1 then we can go ahead and return r one or we sorry we can go ahead and return the maximum because remember so like now that we've so this means that we found we have a valid we found our correct partitioning basically because whatever's on the left of our partition is less than or equal to something on the right to the other arrays right partition and everything in the left of the second array and the left partition everything in the second array is left partition is greater than is less than or equal to the first array's right partition so we basically found a valid partition so now we need to return the maximum of these two numbers here so uh we're going to do math.max of so uh we're going to do math.max of so uh we're going to do math.max of l1 and l2 okay now if uh l let's say that l1 is greater than r2 so if l1 is greater than r2 this means that we need to so that means we need to decrease the partition for l1 so we're going to say mid or sorry high equals mid because we need if the left half has some number that is greater than if the first array has a number that's greater then we need to decrease that partition in that lower in that smaller array so we're going to say hi equals mid and otherwise this means that l 2 is greater than r1 which means we actually need to decrease the we need to decrease the partition of the bigger array and increase the partition of our smaller array so we're going to say low equals mid uh plus one okay and i think we're good um that will handle the binary search so now we're we have one line of code left so let's say that we that low ends up equaling high if low equals high at some point we get out of this loop without ever finding a valid partition what that means because this low remember uh or sorry this mid represents the index so let me just copy an example here so remember that this if say we partition this first array like this and this mid here this represents uh the index of the of uh our of the last thing in our left partition but in the case where we don't take anything from this array so for example let's say that we had say we had an array of like all nines actually let's just leave it like that and then we had some other and then our other array our bigger array let's say it had all once then and let's just say that k equals i don't know two or something well we'd end up the correct partition would be this so m our midpoint will end up equaling say negative 1 because we're never going to take something out of this so in that case we're gonna return r2 of k minus one whoa okay my computer just like bugged out okay i'm just going to finish this um yeah sorry this would be k minus one because we're just basically if we never find a valid index here so in case we if we never find a valid midpoint then that means that we just have to take everything from our bigger array and because k is one base we just subtract one so we do r return array two k minus one okay now i'm going to run this take out i don't know why my computer is doing that um super sorry i don't know what i hit uh i'm gonna run it and see what happens all right so i got the right output let's submit it holy cow i've coded it right on the first try okay um well i've coded this before but i didn't think it's kind of hard to code this correctly the first like anyway uh yeah so this the time complexity of this ends up being um big o of the minimum or sorry big o of the log of the minimum of uh array one or array two so let me just type it out so you guys can see it so time is going to be big o of the of log of the minimum of array1.length and array2.length of array1.length and array2.length of array1.length and array2.length i'm going to fix my computer after this because we're only binary search so we do the minimum here because we're binary searching on the smaller array which will just be uh one of these two right so um yeah that's 10 complexity and then space is just o of one yes we don't use any extra space so it's open all right sorry guys so that was rough i don't know why my computer booked out at the very end there but um yeah hopefully this helps you give it a thumbs up if you want and you can subscribe cool bye
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
118
Yes, hello, this is Gary Niel, a child developer. The problem we will solve today is problem number 118, Pascal's Triangle. A score is given for laughing too much, and it is a problem that returns the first laughing too much of the Pascal Triangle. The Pascal Triangle is the Pascal Triangle shown in the tif below. This is a picture showing what it is. Each number is the sum of the two numbers right above it. I think it will be easier to understand if you look at it as a picture, but the first base case is one, then 1 one, and now 1. It's 2 days, but now you can think of it as bringing the sum of the two adjacent numbers on the upper layer. Like this, like this. 4 Let's solve this. I also solved this using Jegi. Let me write the base case first. If the loss you entered is 1, you can do m like this. If you look here, you can see that the return value is a two-dimensional array of numbers. you look here, you can see that the return value is a two-dimensional array of numbers. you look here, you can see that the return value is a two-dimensional array of numbers. 6 I was a little confused, so it would have been a little easier if I had just listed the number corresponding to the ship. I was a little confused at the time, and I'm going to create something called an item. Here, I'm going to call the channel's eat function, minus Norm Ross's teeth. I wanted to know the Pascal triangle of the step, so I called this function because I need to know the upper layer. So I'll just call the upper layer the last. I 'll call it the last list. This last listen is a double array containing 2 items. 'll call it the last list. This last listen is a double array containing 2 items. 'll call it the last list. This last listen is a double array containing 2 items. So, we can get the last element from Items. This is also an array, so I will start with this array. So, since we are in the second company, we need to move the value in the array and put the value we created by rotating the phone into the array. Therefore, we declare an array in advance. We will put it one by one in an array called 1s. First, if the child is 0, just put 1 in ms. Every year, it starts with 10,000 at the beginning. Every year, it starts with 10,000 at the beginning. Every year, it starts with 10,000 at the beginning. So, put it in, or When it is not a work, it is like this from here to the end. These parts are 1 - 2 rather than the present and the rest list among the est list children in s. 1 - 2 rather than the present and the rest list among the est list children in s. When it's zero, I'll just put it in, and when it's achieved, I'll push the value added to myself and the previous elements. Then, when it's me, I'll add it to the previous step and push it, and when it's me again, I'll come to the ground and push it. Then, it will be made up to this point in a little bit like this. And when all the treasures are gone, just put it in the scalpel once more and this first floor will be created. But since we are right in the hall where the items are now, if the four sides are 3, the e side is 1. There is a way to obtain the Pascal triangle of the level. That is why we create a key at the end of the current level that we have created in this item line. We push this part to this item and return the items. 4 Orr has appeared. This Let Eye is 0. I need to do this, but I can't get the form. 4 I cleared customs. Let's try Summit. Now you can check that it passes normally. The Burr has now been solved with Jegi, and in order to solve the comeback more quickly, you can use a program other than Dyna. You can also solve it by adapting the programming. That's it for today's video. I'll see you in the next video. Thank you.
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
70
I say hello to Korea 003 Dragons Paris inkscape Dragon that are not Used for five minutes the Point is useless raise status and test result all This Time You can't wait for one to Sit in Harmony with English you time to talk a fast is some examples are some nice shop face it is unaware that you is expected and restored i turn to you said you Can I take to assess How stuff for Honor the West a sugar to where you can eat got What the terra woman to test a message to Write Speed ​​with as Little a message to Write Speed ​​with as Little a message to Write Speed ​​with as Little Monsters from save My Earth was Worth It Yourself for sure All My Love affair With reduced The Witch save My Earth with spades is my YouTube search it and costly r6ut one part to Victory in the world food prices low just too good to see What can you since Twitter vietsub Show pku City population the countries with some of the business partners with constant search you keep down the number to reduce memory use the solution is you spell it out work it and report to becoming Who else is nestled in stomach and just due to AIDS It is the season testament Vietsub completed The correct number one of Which is essential Words I toy Popin first serve our customers to see from prince fiery Soul is the last month in a more speakers with a little research is number one take to practice first Mission is to love and has another sta Compact City Because we drink some personal I speak some practice is of work or dry cues and something you eat and solve and like to Sit Michelin will come And Dance Sport watch IS strange
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
473
That a hello everyone welcome defeat in zurich challenge desperation superintendent has indicated in there which where is elementary subscribe now list code on mexico is 478 so let's prana wise question answer can be giving raw painters length mark point to find out where it's possible to Do Subscribe Now Subscribe And The Information Subscribe Absolutely Total Quality Of Mid Day Meal Subscribe Hotspot Mission Mein Bhi Possible However Did Not Divisible By 4 You Can More Models Of 14th Breaking Dawn Is Mirwaiz Subscribe 0 That Now Comes The Questions Were The Parameter and Uses for Ninth Check Effigy 225 With All the Given Celebration Not Being Planted Will Start From The Video then subscribe to the As Do That And For The Bad Ones Sign At This Will Find The Parameter By Four Volume Solve Them Are Universally Equal To per withdrawal subscribe that is similar to a this is what we do you will signup particular inter and to side and pray the meaning of clans Video subscribe across all possibilities that and will continue this process and crush the evening input and when school president and equation That I Trade Swabs Interval Setting Off Side S Wonderland Side S2 Take Inside And Outside Support This Consumer Is Number And Operated From Dashwant Land In Wave And Continued For The Meaning Of The Word Meaning Subscribe To That Similarly You Will Do It A Cross All The Four Cases Will Shine Number To Students Names subscribe and subscribe the Channel Please subscribe our I Hope You Guys Like This Is Simple Banquet - Used In Fear Not Be Banquet - Used In Fear Not Be Banquet - Used In Fear Not Be Remembered For Watching Video That Building Subscribe To Main Belt Match Schedule Fixed According Fast And Everything With Crystal clear app the report in the district check weather the length of these target vihar visarjan charted plain for water subscribe download websites security parameters of liquid form and what we will do subscribe elementary mid are their per meter models ko is note equal tubelight means shop Thomas Quite Afton Want To Purchase Return Gifts Otherwise You Travel Template Suicide Of Destroy But Does Not Support Anarchy Turner Road Will Leave Aside And Subscribe Channel Subscribe Our Videos Must Subscribe And Cyber ​​Attack Subscribe To Subscribe And Cyber ​​Attack Subscribe To Subscribe And Cyber ​​Attack Subscribe To Jo Vo Time Volume Songs Driver Breaking Condition Is Aa Consumer All Marksheet Means Sexual Check Weather Decide S One More Subscribe Like This That Is Country Daily Don True Otherwise Return Policy So They Both End In A Gift To All The Side Of Subscribe Current Baalveer With A Boy Also Iodine Reduce On Subscribe Button 10 Side Bryan Adams White Consuming The Matrix And Involve Website Plus One Side And Widening And Strengthening The Subscribe The Amazing Subscribe To That Akshay Want The Time Complexity Of This Approach The Time Complexity Studio Order Of Four Wrist Per And Technology Yr Urgent Meeting All Possibilities For Website This Is Not Amelioration What Do You Can Start Been Quoted That Will Helps Reduce Weight Back Tracking Roots David So Difficult Can You Help Improve The Time Taken For Competition 120 B R S.No 120 B R S.No 120 B R S.No Ki And Expression Hain Akshar I Hope You Like To Days Session's Pimples Letter Like Share &amp; Subscribe Pimples Letter Like Share &amp; Subscribe Pimples Letter Like Share &amp; Subscribe Channel Thanks For Watching Dandruff Birthday Hai Hua Hai
Matchsticks to Square
matchsticks-to-square
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this square and `false` otherwise. **Example 1:** **Input:** matchsticks = \[1,1,2,2,2\] **Output:** true **Explanation:** You can form a square with length 2, one side of the square came two sticks with length 1. **Example 2:** **Input:** matchsticks = \[3,3,3,3,4\] **Output:** false **Explanation:** You cannot find a way to form a square with all the matchsticks. **Constraints:** * `1 <= matchsticks.length <= 15` * `1 <= matchsticks[i] <= 108`
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands!
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
null
452
Hello, so welcome to week five of our weekly lead code challenge. We have finally come to our last week, so let's move towards the solution. Yes, so let's start with our question number 73. Question number 73 is ours. Minimum number of arrows to burst balloons Ax plane means 2D plane basically and you are given their coordinates, we do not care about In those balloons i.e. on the wall from below, In those balloons i.e. on the wall from below, In those balloons i.e. on the wall from below, I have to tell in how many minimum number of arrows I can burst all the balloons provided that the arrow will keep traveling upwards and we can use any number of arrows, there is no limit, just an example. Let us understand the question, what are you going to say, the example is 10 16 2817 12, so the example is 10 16 28 s and 7 12. Okay, in what manner are the balloons attached? The balloons are attached in such a manner that a balloon is attached here. Suppose a balloon. There is a balloon attached here, there is a coordinate or coordinate here, basically we don't have any meaning, in this way there are some balloons attached, so if I shoot an arrow from here, it will bust this one too, an arrow will bust this one too. If I hit from here, it will bust this one too. But if I hit this arrow a little from here instead of here, then this one will also bust. This one will also bust and this one will also bust. Okay, so in two arrows. All these balls will go bust, I had given an example of what to do, that is, what is basically expected, it is correct in the question, now I have understood, what am I not doing, I am sorting it basically, in a way, that What would be the method, I will sort it by the second element instead of the first element, I will understand how to do that, we will apply the Comparator function on static, I will sort it by the second element, if we sort by the second element, then we will get end The point will be known basically where the balloon is, now we will see it basically on a map by mapping it a bit rough, then we will understand better. Now first let us write the sorting, then how will it be done in sorting, this will be one balloon from one to six, the other balloon will be two. The third balloon will be from 7 to 12 and the fourth balloon will be from 10 to 16. In this way we have sorted it. It is fine according to the latter, now just map it on the X-ray plane. If we is fine according to the latter, now just map it on the X-ray plane. If we is fine according to the latter, now just map it on the X-ray plane. If we see, this is my xva plane 0 T Th then F 6 to 7 8 Na 10 11 12 13 14 15 and 16 Okay, the first balloon is mine, it is so wide from one to six, which is the second balloon, isn't it mine? The third balloon is so wide from 2 to 8, it is so wide from 1 to 12, okay, and the fourth balloon of mine is so wide from 10 to 16, okay, what should I do? In this, arrows have to be shot in such a manner that if all these balls burst together then this burst happens simultaneously, meaning if it happens in at least one arrow then I can burst multiple balls simultaneously, then when will they burst together, when will they overlap? When they are overlapping, they will burst together, even if they are done just at the point, but if they are overlapping, they will burst, so in the non-overlapping burst, so in the non-overlapping burst, so in the non-overlapping intervals, we had understood a little hint of this here. And you will understand, okay, what I do in the beginning, I accept my arrow, the first arrow, which is not mine, should come here, at its end point, I keep in mind that the second number According to, that is, if we have sorted according to the last point of the range, then the second balloon will always be either equal to it or it will be bigger than the first balloon, it will always be the last point, so it will be at the back, okay first. We should not be concerned with the point, we should definitely mean with the last point, how far we can hit simultaneously, so I will keep the arrow here at the beginning, the arrow is placed here and here at least one arrow will have to be hit. Initially I will keep the count at one so that at least one arrow will hit, brother, I have understood this much, okay, now what will I do, exactly, I will assume that I shot an arrow beyond this, okay, I shot a row on this. Arrow has broken this one has burst the balloon, so we have kept one count in the beginning because it has been placed last, so this one is definitely going to burst, okay, so one, we have kept the other one in the count. What will happen if my if kept the other one in the count. What will happen if my points of I0 i.e. whichever point i.e. my points of I0 i.e. whichever point i.e. my points of I0 i.e. whichever point i.e. my first point of the second balloon, if it goes outside this arrow of mine, then I need an extra arrow? Otherwise, I will not need an extra arrow. If my starting point of the next balloon is outside this arrow, then I will need an extra arrow. Otherwise, it will not be needed. So for now the count is only one because Its point of zero, point of i0, whatever it is smaller than the point of my arrow, so this balloon will also burst from this arrow, now we move to the third balloon, then the third one. This point of the balloon is outside my arrow, it is outside my arrow, so what I do is that I place the arrow on the last point of this balloon, that is, the second arrow should go from my 12, this place is fine. Okay, let's go to this place, so now there is one more arrow, so it becomes 1 point, that is, for now the count is two, so this one has burst from this arrow, okay, now let's go to the next one, then see this point, now my current Where the arrow is now, is it bigger than where the arrow is currently, isn't it smaller? Is it 10 and here? And here at 12, the arrow is smaller than this, so that means this arrow will bust this one and will also bust this one. If it is ok then there is no need for more new arrows. According to this, I have to complete it completely. So, if there were four balloons would have burst in two of my arrows. If there were more balloons, then according to that, our arrows would have changed and we would have no concern with the axis. Is it not kept anywhere? Infending points dot begin points dot end and one more, we will create a Comparator function, we will sort from the Comparator, let's create this function, we will make this function static bool Comparator and what will be given to it, we will sort the points dot begin. What has been done is this vector of int, that is, it will have two vectors. Comparator will have two vectors, so let's say r of int, let's take the first point by reference and the second vector will come as vector of int by reference as the second point. Okay, one point will come and two points will be compared to both of them, first point and second point will be compared and then I will say that if you want to sort according to the person with a p of 1 second then fp1 if less than s off. 1 is according to the second person, then return true from here, otherwise return false. Okay, my Comparator function has been created, according to this, it will be sorted according to my second point. Okay, no tension, now I have selected its size. I have taken out the points, do not take out the dot size, use it directly, there is no problem and initially I have placed the arrow on my points of Rowan, okay, initially where have I placed the arrow, on the last point of the first person. Point of zero is on one and the count has been kept as 'Eve' because on one and the count has been kept as 'Eve' because on one and the count has been kept as 'Eve' because initially my count will be one arrow is going on because if I have placed it on the points then now one arrow is going on, okay so I have kept the count on one. In the beginning, now I said that when you have used zero guy, then come start from eve, go to lesson A, come plus, what work has to be done that if the points of i0, points of a zero, whatever is there, it should be greater than my arrow. If the arrow is ahead of the last point where it is placed, then points of zero i.e. the first point of the balloon, then i.e. the first point of the balloon, then i.e. the first point of the balloon, then what will I do? I will move the arrow forward by one point, on the points of the first balloon, then go to the last point, ok. And if you are moving, that is, one or more arrows are being used, then the count plus becomes plus. It is okay that this much work has to be done, only in these scenarios the count plus will be plus, otherwise all the balloons that are bursting. There is bursting are bursting. There is no problem, so much work has been done, what to do after this, nothing else, we will count the returns, the matter is over, there is only one question, run it and see, one turn is done, accept and submit, let's see, one turn is done, yes, submit. Very good, yes, I hope you guys have understood the solution very well, just a few more days of hard work, four weeks have gone very smooth, just this is the last week, some questions and then our DSA is almost complete. It will go well and with this then our interviews will also be cleared well. All the very best. I hope you clear your interviews very soon and we will have a party with you again. Bye
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
1,356
yo what is going on it is wednesday april 27 2022 uh april is winding down like a fastball pitcher's pitch um i don't know that was a random analogy um but you're not here for the random analogies you're at uh welcome to coding with chef and uh thanks for watching my video uh please like and subscribe and comment in the link below yeah and just let me know how i'm doing okay so um yeah i'm here today to do lead code problem 1356 sort integers by the number of one bits okay cool so this should actually be a pretty easy problem um the only thing is that um i'm gonna be doing this in java and i'll let you know in a second what the issue with that is but you know it's one of the complaints about why people don't like java and like other languages don't have constraints certain constraints that java has but anyway let's get to it you're giving an integer array r like the pirates how to sort the integer in the array in this ascending order by the number of ones and their binary representation and in case of two or more integers have the same number of ones you have to sort them in ascending order return the array after sorting it okay so basically you sort the number of array the number of you sort these numbers based on their one bits okay so the number of ones um so basically should be easy each element each this is the decimal representation of each element so i'm gonna convert it to the ones representation uh right so you have one then you have this is just basically binary arithmetic then you have three i'm sorry three and in case you just you don't know how to do this conversion um go back to school no i'm kidding um this is pretty easy right and uh seven equals i believe um let's see uh this is 97 is 1 and 8 is 1 0. okay so basically you have to sort this like this okay um zero one so this one and two have one bit right just take a look at the answer here one and two of one bit three has two bits four has one bit five six seven eight has one bit so the numbers if these all have one bit a zero comes first because it has zero bits right one has one bit we'll group them together one has one bit two has one bit and eight has uh four has one bit and eight has one big so those that's pretty much the ordering of the first numbers then the next numbers have bits um two so three has two bits four has two bits as the three is two bits five has two bits and six has two bits so the numbers they are three five and six and then finally seven has the most bits seven has more bits than eight just don't get confused with that and this is your final ordering okay so algorithmically how do we do this okay so uh i'm gonna since i'm doing this in java i'm gonna have to do something normally you would do something to use you would if i'd want to sort using the ill inbuilt sorting function i'd do something like this right and that would just sort the numbers um but since i have a custom criteria which i have to sort via using a comparator you'll see what i mean in a minute and you know how to all uh write a comparator now if someone knows a way around this using more a more modern java nicety that would be great another nice rule i have a way around it but another the way around it that involves using the custom comparator on the array sort function that would be great and there probably is so um forgive me if i'm not you know up to the speed on that so i'm going to write my custom comparator what is my custom comparator doing my custom comparator is just comparing the number of ones on each and if remember the comparator returns negative one and positive one right if the vowel is not equal to zero turn vowel that means if it's the when it's equal to zero that means the two things are equal have an equal number of ones if they don't have an equal number of ones then we just return a minus b which is basically saying return the number of ones that has uh return whichever has the larger number of uh which is whatever whichever is in sorted order from smallest to largest to smallest and larger one okay that's what that's saying so and then at that point all i would have to do is return r right you'd think that's it and of course you need to write your ones function so uh in ones and num and total zero while num greater than zero total plus equals so this is called a bit shift operator uh this is well this is basically using bit shift uh and for those are not who are not familiar this is the bit shift operator below this is saying shift the bits to the right turn total shift the bits to the right one by one so if i have um one oh one right then this becomes one o one and you could put a zero here if you just if you want it's not necessary then this becomes zero one o zero finally okay so basically i'm taking off this bit here on each iteration right um because i'm moving these bits to the right okay and whatever these bits happen to be okay um i'm just being like oh okay well this is the bit that i'm going to take okay um right let's just make sure this is right yes okay sometimes you can get a little squirrely and then this becomes one zero one and so on okay and then all the way down to zero so and i'm count just counting that and summing it whenever it's true and how do i determine it's true i do an and of this first bit with the one because an end in one and one is equal to one and zero is equal to zero and one is equal to zero so it will extract the number of ones okay so now if i was to run this we'll see what i mean okay and not int if you probably were distracted by that the whole time so see this there's no custom comparator for this okay so in the interest of brett like in the interest of brevity i'm going to keep this comparator but i'm going to do something else here priority queue is basically another way of sorting but there's extra space involved now if i used another language i wouldn't need to do this okay but let's just say for now i'm going to use java okay so replace my priority q now in i equals 0 i have to put the elements of my array into my priority queue and that length plus eq dot a r i and then so now everything's added to my priority key and this just in case you're wondering is o and log n order the same with arrays just sorting the array so they're both oh and log n operations okay so i'm adding elements to my array and i equals zero while not pq is empty a-r-r-i a-r-r-i a-r-r-i equals um let's see you cannot infer arguments for priority queue uh you don't need this arr here that would be nice but you don't need to do that and let's just make sure cannot find symbol this should be num and there you go accept it and there you go okay and it's slow because part of the reason well is because you know you can never really tell right uh the same code submitted twice but it's also because this shifting is uh o of n of the number of bits right um and it's complete operation is completely dominated and log and uh but this and but this is n log and if this is you know this log n bits i guess login operations or log b operations you can almost think of this as o of n log b right you know any because that's this one's operation is occurring within inside this comparison okay so um yeah that's it if you like this video like subscribe and do all that good stuff uh thanks for watching and i'll see you around oh by the way the discussion for this video i posted it as usual on the code uh so discussions for this problem you can check it out and yeah thanks
Sort Integers by The Number of 1 Bits
minimum-number-of-moves-to-make-palindrome
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr = \[0,1,2,3,4,5,6,7,8\] **Output:** \[0,1,2,4,8,3,5,6,7\] **Explantion:** \[0\] is the only integer with 0 bits. \[1,2,4,8\] all have 1 bit. \[3,5,6\] have 2 bits. \[7\] has 3 bits. The sorted array by bits is \[0,1,2,4,8,3,5,6,7\] **Example 2:** **Input:** arr = \[1024,512,256,128,64,32,16,8,4,2,1\] **Output:** \[1,2,4,8,16,32,64,128,256,512,1024\] **Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order. **Constraints:** * `1 <= arr.length <= 500` * `0 <= arr[i] <= 104`
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Two Pointers,String,Greedy,Binary Indexed Tree
Hard
1437
501
okay so in this question we're given the binary search tree and we want to find all the modes the element that occurs the most frequently in the binary search tree so how do we do this they have a follow-up how do we do this they have a follow-up how do we do this they have a follow-up could you do it without any extra space but that doesn't really make sense because if all the nodes are distinct you'll be returning all the nodes so that's all n space complexity so even if i use a map that's still o of n space so this isn't this doesn't really make sense what they want you to try to do is do it in order traversal of the tree so if you do a dfs on the node and then you do a dfs on the left child of the node and then the device on the right side of the node you in order traversal is if you say for example you have some list and you don't want to push back ends value here that's pre-order traversal this is that's pre-order traversal this is that's pre-order traversal this is inorder traversal and this is post audit reversal inaudible gives you a sorted list for binary search tree and the reason for that is because of the definition is that the left child node is always less than or equal to the parent node sometimes they it's strictly less than but in this case it's less than or equal to and the right child is always greater than or equal to the parent note so if i do all the lefts first that means i that means when i get to here i'm at the lowest possible element because when i keep going left i keep going down i keep decreasing um the node value until i get to the lowest low note value and then i slowly go creep back up using these dfs rights we can think of it like that so if so you can reduce the problem to like finding the mode of a sorted list essentially but then you still have to return all the values that have the same frequency which could be up to all nodes so it's still space complexity of n so it's really this you can do this but uh a map would be easier to implement and have the space same space complexity so let's just use an unordered map to count the frequencies of and a dfs to on the tree node so dfs like i talked about you want to do on the left and the right also has a base condition of actually i hate how in depth indents well hey um but if the node is equal to null pointer or i could say if n if not n then return um this will be the right this would be okay so i'm doing in order traverse so that means i want to be in between the dfss and just do like of whatever the n's value is increment that by one okay so that's how i count the frequencies now i just want to go through and find the max frequency and then go through it again to find the to just add to some answer and return that's some answer whatever has the max frequency and just return that so to find the max frequency i would have to go through and so there's this way of going through this is a arrange for loop so i'm going through all of frequency and whatever p is actually going to be uh std pair so you can access the key value doing first um like that or and you can value the access the value using second so if so i want to find the max f and max f should be initialized to something and say you know max f is equal to the max of itself and whatever p the second is so okay that and then i could do go through all of it again except this time i actually want to push back to the answer if um if p dot second is equal to max f computer first push it back and then return answer on order map needs two template parameters dfs needs a return type of void and wrong answer okay great let's see i didn't i forgot to call dfs oh fruit okay there we go there's always a hiccup
Find Mode in Binary Search Tree
find-mode-in-binary-search-tree
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. * The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,null,2,2\] **Output:** \[2\] **Example 2:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` **Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
98
124
hey what's up guys Nick white here and you take encoding stuff on to what you need to check the description for all my information I do a bunch of stuff on my patreon if you want to support me I'd really appreciate that and then yeah reach out to me on discord it's a good place for that and I'm doing a problem today based on someone in my discord recommendation so you know you can ask me to do problems in the hair too and I'll you know try and get to all of them so we're doing this one is what I was sent today a binary tree maximum path sum so the problem is a hard problem so you might have to bear with me it might be a little bit longer than usual but I just did it and it wasn't too difficult like lines of code wise it's pretty easy it's almost really like a medium level difficulty it's just the concepts a little bit difficult so let's just get into it binary tree maximum some path given a non empty binary tree find the maximum path sum and if you guys recall what binary is its base to number system where you have zeros and ones binary tree means that there's two leaves there's no more than two leaves per node so if you look here like there's gonna be two leaf nodes at each level though the level doesn't have to be completely filled it's not a complete binary tree but there's not gonna be like three leaves per node or whatever like that so for this problem a path is defined as any sequence this is so this is the important part for this problem a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent/child connections tree along the parent/child connections tree along the parent/child connections okay so some starting node not and also the path must contain at least one node so the path must be at least one node and does not need to go through the root okay so we don't need to use the root and if we look at these examples it is any nodes has to be at least and it is it just has to travel along a path connecting parent and children notes so it could start at node two and go up to one then three it cannot go from 1 to 2 then 3 or 1 to 3 then 2 it has to travel a path using these little parent connection bars here for example in this one we also have negative numbers these nodes can have values that are negative and that's why this is a little bit more difficult than usual so in this case we wouldn't want it to be like the negative 10 2015 7 because we could just say no we don't want the negative 10 and then boom 2015 27 so there you go how do we do this so if there were all positive numbers and we wanted to find a path from the root to a leaf then I think we did that one before and you just kind of traverse on the left and right sides you keep a maximum variable and that's pretty much it you'll come out with the right answer in this problem we're going to do it recursively but the only difference is we're gonna be traversing this tree but we need to keep track we are gonna keep a maximum variable so we're returning the maximum path sum so let's just call it max path sum and we'll initialize it to a negative like you do with maximum variable so we'll say max path sum is equal to integer dot min value right and we're also gonna use a helper method so our helper method will be called path sum so it'll just be you know the current path sum and it will take in a note great and we'll be updating this max in our helper method and in the end we'll be returning the max we'll pass in our root node to our helper method so we'll call path sum on a root and this is where the fun begins in by phone I mean you know thinking I guess which I don't even know what I'm saying I'm just in my head a little bit I guess so each node has a value a left node and a right note right and then we know it's a binary tree so what we're gonna want to do is well first of all if the node is annul we're gonna return zero because like for example if we were just given a null node and we passed that in as the root there's no path sum there so we just return zero that's fine what we want to do is we want to check the left and right subtrees recursively traversal a recursive traversal down the left and right subtrees you and we'll keep these values using left and right variables so left will be you know math max of 0 will pass in 0 and then the recursive call on the left node out left I think we have an extra parenthesis and write will be the max of 0 and no dot right and these values are going to return the path sum for that particular for this particular node down the left and right keeps going it's kind of like a current path so I guess I would say we will return the max top Matt math dot max of the left or right depending on which one's greater in the current node value so I mean I just got to show you the let's just coat it out and then I'll explain everything because I just got to show you they have a great solution so like diagrams and stuff like that so what we're gonna do is we're going to update the max each time Max is going to be equal to left math dot max of the current Max and then left plus rights plus no double there we go this is the solution and what we're gonna do is we're going to look at I'm gonna we're going to show you how this works just so you understand first of all let's simplify the problem and implement a function called whatever which takes the note as an argument computes the maximum contribution that this node it and one of its sub trees could add so that's what this method is doing path some one of its sub trees because for example if we have ten we can if this was the path we were gonna do it we're going 10 2015 we can't do 10 2015 and seven we can't do negative ten nine twenty it's it has to just be it has to be like a straight forward path like you can't visit and then go backwards there's no backtracking allowed here it's just you it's just connected nodes so you could go for example like you can go in this direction it doesn't matter what direction you go in but you can't you know go multiple directions so if I'm going down I can't go left and then go up you know what I mean it has to be the constant flow no back going backwards first of all let's apply the problem in other words the maximum gain it could have including the node in one of its trees okay so what they're saying is let's look at this at a recursive level you pass in the root and you keep recursing on the left and right sides these two lines right here the left and rights integer variables that are going to return the path sum these two calls if you guys know our recursion works the you won't get to these lines until you're at the leaf nodes right because it's gonna go it calls this left call then it goes recursive call then it calls the left again and again until you're at the left most node right and that would happen you pass in the root you go here you pass in the root it recursive on the Left it passes in this nine or curses on the Left that's a null value so it returns zero and then you're back to the previous call so it recurs is on the right it returns zero and you're on that nine you're gonna check the max path sum with the Left plus right plus node Val the left + plus right plus node Val the left + plus right plus node Val the left + right me being zero because nines left and right or zero the current max path sum is negative whatever the integer min Bell and then the current node value so nine so obviously it'll get updated to nine because zero plus nine is better than integer time min value and then we return the max of the left or right plus the node value which is just nine so what that returns to is then tens left value so it's all this giant recursive call here where the max path sum is kind of just this trick tricky cool variable to help us calculate the max path sum and kind of feeds off these little recursive calls here and these it's confusing because you have all this recursion happening beforehand and then it goes like level it's going a level forward and backwards and getting confusing but like once this has a value to return I guess then it'll return to a previous call the max path some can then use these variables because they will have values when something's getting returned from a previous call to calculate the max and you could see here they give you examples like max from node nine is going to be nine so it gets updated fifteen there's no children seven so the leaf nodes just like their max paths is just if it was just the singular nodes it would just be the values right from node twenty though what we're seeing is we're getting a max we're updating the max with the Left plus right plus node dot Val so that's why the maximum is going to be fifteen twenty and seven you know what I mean so which is thirty five plus seven which is 42 so you know how do we know not to include negative values well the negative values don't get included because we're only updating the max when it's greater and if we added this negative ten when we recurse the recursive calls keep going up you know it'll be 2015 and seven that max gets updated and eventually it all just becomes you know the right variable of the negative ten up here then we check the right plus the left which is you know negative ten plus the right side plus nine is it's not as big is you know this little combo right here so you just have to you know it kind of goes the maximum czar getting calculated from the bottom level to that route basically because the recursive calls go boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom boo-boom all the way down to the leafs and then the maximum values get calculated through sub trees going upwards and until you get to the root and it's just really it's bright I think I've explained it pretty well I mean there's a you keep the integer Max value so they don't get updated when you start adding smaller values or negative values if you've got your max they're not going to it's not going to get updated you know you already found it and you're just returning the left and right I already explained that too just because left or right just because you know I mean this solutions really good I think you guys should go through it I mean it's pretty good so like they give you everything honestly I under this is how I understood everything Maxim is the smallest integer you set it up there right we set Maksim to the smallest integer you call your recursive method to calculate the left and right subtrees right then you want to check to continue or remain continue a new path or remain on the old path by calculating I mean they're variable names I didn't like that much so I changed them a little bit but yeah you calculate left right and node Val and you see if it's better than what we already have and then you update it if you don't want to include things that are smaller I mean I don't know how many other ways I could say this I mean want to make sure I'm clear cuz it is a hard problem for a recursion return the max gain and the node one of the zeros whatever and then we have this little thing I mean this thing like I watched this and I understood it perfectly right you call this method work Mars is called path so there's this max gain you pass in the root right it does all these recursive calls it does left first so it goes to the leftmost first hits nine and Inez no children so we just get a returned value of nine because left and riders in euro plus nine then you got 20 keeps recursing on the left now because you called it you called the right but then the left is the next line and the left has no value so you got the 15 it updates maximum gets updated to 15 because now we have found something better 7 doesn't update it because it's smaller than 15 is so far our best viable path right now then we break up to the 20 finally out of those bottom level recursive calls and we see ok the left + right + the node value is 20 + 15 left + right + the node value is 20 + 15 left + right + the node value is 20 + 15 + 7 we have a maximum of 42 and then it + 7 we have a maximum of 42 and then it + 7 we have a maximum of 42 and then it recursive to the top level but it's negative and we check against the max and it's less so we don't update it you know it's I think that's pretty much it I don't know what else you need explained to you let me know if you guys have a difficult time I think I traced it pretty well but I could see this being a medium problem honestly it's not too difficult there's immediate there's a couple medium problems on here that look like they should be hard and this should be medium I mean look it's not that many lines they gave you a great solution I think it's a little tricky to understand at first but I like what I look through it a few times I understand it perfectly now and I mean let me know if you still don't get it I mean I think I don't know what else I could do I really couldn't do anything else to explain it to you like just watch this diagram a few times look through the discussion trying to understand what they're saying time and space complexity we got linear for time because you're traversing all the nodes but space they say log of n that is wrong actually because worst case is actually because it could the tree could be set up so it could be worst case and the EC this person says it right here should be open but um you know what look explain why we return you know node + left of right you know node + left of right you know node + left of right you know they got a bunch of stuff in here check out the discussion like this he'll just say what I said though you know I've laid it out pretty carefully so maybe go back and listen thank you guys for watching I really appreciate you guys thank you shout out to whoever suggested this Atlee in the discord please join the discord guys and I will see you guys in the next one alright see ya
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. The **path sum** of a path is the sum of the node's values in the path. Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 6 **Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. **Example 2:** **Input:** root = \[-10,9,20,null,null,15,7\] **Output:** 42 **Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-1000 <= Node.val <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
112,129,666,687,1492
980
welcome to september's elite code challenge today's problem is unique paths three on two dimensional grid there are four types of squares one represents the starting square two represents the ending square zero represents empty squares that we can walk over and negative one represents obstacles that we cannot walk over now we return the number of four directional walks so that means our robot can go up down left or right from the starting square to the ending square that walk over every non-obstacle square exactly once every non-obstacle square exactly once every non-obstacle square exactly once wow so that is not going to be an easy question because we need to just forget about the dp solution because of this four dimensional or i should say four directional walk it's gonna be very difficult to think of a way that we could cumulatively iterate and sum up paths in order so instead let's just think about how we could do this recursively first and see if that might work um so what i'm going to do here is let's first copy paste this and go over every square go over all the data that we need let's start with that okay so we need to first figure out where we're starting from right where are we starting where are we ending and in order to figure out have we walked over every single empty square possible in this grid we also need to probably store the number of empty squares so rather than trying to record the path we'll just record how many empty squares have we traveled and if the number of empty squares equals how many squares we've traveled so far in our recur in our recursion that means we've walked over every single empty square okay so what we think we're going to do is we probably have to have some sort of visited set right because we don't want to have any infinite loops occurring we need to make sure that we're not going to go over the same square again and how do we make sure that we're going to go through paths without ever repeating a path well one way you could do that is to do a depth first search right so we'll go that first search route and we'll use this visited set in order to track our path that we've been through so far and then we'll pop off the visit set and backtrack we'll do a backtracking algorithm to make sure that we don't repeat past again or we don't not go through paths that we should in other sort of branches okay so this is going to be a doozy all right um let's start with initializing the m which will just be the length of the grid and the n which equals the length of the grid zero now a couple things we want to get are the starting ending and number of empty squares right so let's initial um let's initialize with starting row starting column ending row and ending column and all these start with zero and we don't actually need to initialize this but just to visualize better we'll do that and we'll also have empty squares so we'll just call that and what will that be we'll start with zero okay so first we'll go through and store all these variables so for r in range of m and four column in range of n we'll have to check a couple things if grid r c if it equals what one then we know that it's the starting square right so if it equals one then let's make this starting r and starting column equal to the r and c else if the grid is equal to uh the ending one which is what two then we're going to make our end row and end column equal to r and c finally if grid rc equals zero then let's increase our empty squares so now we have all the variables that we think we need we have the starting the ending and the number of these squares traveled all right so now let's write our depth for search definition that first search and we'll pass in the row the column the visited set as well as the number of empty squares we've traveled so far so i'm going to call that walk and this is going to count up how many squares we've traveled so far and this way we could say all right well if our r is equal to the end r and c is equal to n c well then we should end our recursion but let's check hey does the walk equal empty plus one because we need to make sure to count for account for the final square which is going to be two right so if that is the case then we will increase our output and say we found a path and finally was returned out of here so i'm going to make this a self variable to make sure that it's not gonna become a local variable and some will consider that cheating but hey it's my solution so all right so now we wanna do our deferred search well a couple things we're going to make sure that is the case we want to make sure that r and c are in balance right so 0 equals so r has to be greater or equal to 0 or less than m and same with the column needs to be greater or equal to zero or less than n and let's make sure it's not an obstacle say grid rc is not equal to uh negative one and finally we haven't visited before so rc this tuple not in visited okay so now that we can say okay we've met all our constraints we will add it to our set we'll say add our set rc and we walk um we're gonna backtrack after we're finished here say remove but what do we need to do now we have to call our recursion right and we'll say for let's say i x1 okay let's just say i j in let's do our four directions that we can go so we can go um left we can go right we can go up and we can go down we're going to travel all this make sure that we call our debt first search and r plus let's see i guess it doesn't really matter r plus i c plus j so this will be the path that we're going to travel we're going to say that's the visit set and we're going to add one to the walk to make sure that we count it up after that we backtrack here and that should be it now let's call our deafer search what we call in there well first we want to pass in the starting row the starting column the visit set i guess we'll initialize that up here the walk which will just be zero and if we did this right we should just return our self.output at the end so let's test self.output at the end so let's test self.output at the end so let's test this make sure that i didn't make any typos all right so it looks like it's working let's go and submit that and accepted so naturally this is way different than unique paths one and two um we had to go with recursion it's time complexity wise a lot more i think it's going to be an m squared times n squared solution uh but considering that we only have a max length of 20. i suppose that's fine for this one could we do better possibly but um but i have to say this is already a pretty complex solution so if there's a dp solution out there let me know um i haven't researched yet but this was my solution and it did work so i was quite proud of that alright so thanks for watching my channel and remember do not trust me i know nothing
Unique Paths III
find-the-shortest-superstring
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Array,String,Dynamic Programming,Bit Manipulation,Bitmask
Hard
null
1,706
daily challenge I hope I maintain consistency across the whole month and let's get started okay today's question seems like an interesting one where will the ball fall Okay so normally I don't read the question I just try to look at the diagram and then test cases and I try to figure the question out so let's try to do that so I guess the question means we have a 2d grid and then each cell has values 1 or -1 values 1 or -1 values 1 or -1 means you know going right and minus one means going left and we leave balls we throw balls on top of each and every column and then we need to know which out of which column that ball will come out and if a ball gets stuck between the wall then we need to return minus one and the if we have a wedge like this like if you have V shape existed then the ball would come and still you'll get stuck here it won't be able to go any further yeah so that's the question you can read the question more and the constraints are pretty weak so we are free to do anything we want as long as it's not exponential or factorial range time complexity uh as that as the constraints are you know a little weak maybe we can try just simulating what the problem wants us to do we can start from this point then maybe we can go down I mean we can do what they asked us to do I think that should work let me see I'll create a function called as Excel which would have two parameters X and Y the coordinates of the ball where X is the row number and Y would be the column number so I'll quickly have the number of rows and number of columns it helps a lot you know instead of writing the whole length of grid thing you can just use n comma m and thank you so when do we get stuck when we go on to the left of zeroth column or on to the right of M minus one column so we can do that so if Y is less than 0 or Y is located or equals to m in that case we return minus 1. and when we when do we come out when we go below the N minus 1 row right so if x is equals to n minus 1 then we may return the column name and apart from that there are uh apart from that then let's enumerate the possibilities of left and right so if rate of x Come Away if it is equals to 1 then we need to check if it forms this kind of deadly wedge like if we here if you see here the value is one then it would form a wedge if the value adjacent to it has a value of -1 right -1 right -1 right so I will quickly have a check for that so if the column next to it is not if not is not exceeding our bounds like if we are here then it's there is no reason searching uh going out with us going to the right because there is there isn't any cell on to the right in that case this less than M okay and if it is and if its value is in that case it would form a fetch so in that case I would return a minus one else I would go I will propagate so if I am here and if I get a value of 1 then I would go to the right of the bottom column hope you understand so in that case I would go there and return whatever I'm getting from that you know it's kind of recursion uh so the row number would be X Plus 1 and column number would be y plus one because we are going to the right and you know similarly uh the same for minus one instead of Y plus 1 we need to check from y minus 1 we handle both the cases I think there wouldn't be anything else here so it will just return because it you know we know that every cell is either one or minus one so yeah can just return because it would never reach this then we can and then we can so we got this function at cell function what it does is if given that I start from X comma Y in this grid if I throw a ball at X comma y where would it land would it go we will go on to the right or would it go on to the left or would it come out oh I think we forgot the wall case so if we hit a wall if or if you go if it hitting a wall is you know it is synonymous to saying that we went out of bounds of this grid so we could add that condition as well again we could add that condition at the start we could start here if oh I think we have this condition sorry we already handled that condition we already handled that wall condition I'm sorry so what is this function at cell function so add cell function is it'll tell us what would eventually happen to a ball thrown at the position X comma y so we are initially throwing balls at these positions like we are throwing them at zero one zero two zero three zero four and zero five and then we need to return their consequences so let's do just that now this is left comprehension I left these in Python or I could have done or I could have used any for loop as well I hope it works oh no it's not working so why am I getting -1 here why let me keep bucket what's happening to XCOM y and instead of looking at the whole thing I'll just looked at first impress that's what that's why we're getting the wrong answer okay so I'm zero I'm at zero then I came to one then I went to 2 and then there I hit the fetch so I made some mistake in this condition Maybe sorry yeah so you know on to the left we need for the boundary check we should not check it with M we should check it with you know zero it is greater than or equals to zero I'm sorry whatever what was even thinking oh yeah but I'm still getting minus one and here it would be one right if I have a left going cell then I need to check that if it is 100 okay what I'm going to get 2 here I'm gonna see what I'm getting no I'm getting a two instead of one why is that let us divide it okay levels so deficit 0 and then I came to 1 and then I went to two and then I went to three one and then I went to four two zero one two okay so actually we need to get we need okay so actually we need to get the position of the column when we get out of this bound so instead of putting n minus 1 here we have to put n I should really start reading the question okay I think it is working this is where it is working fine let me check let me remove this comment out this debug statement same let's try again I don't want to buy a premium I'm broke okay so the example test cases are passing but I'm not sure can't see any other mistake I made but maybe these days I'm getting a lot of wrong answers and what would be the time complexity this so you know this loop I mean this function it's type it's a recursion recursive function and each function would invoke itself at most n times n number of rows times because we have because at each recursion we are increasing the number of rows by one and when the number of rows reaches n I'm just returning it so for each X comma y for each um in the worst case I would recurse for the number of rows times and that I am doing for each and every column so that would be M into n so it should be able to come in our bounds of n equals to 100 yeah so yeah today's video wasn't very good there were a lot of mistakes I made so we had to debug and apart from that I hope to maintain consistency across this November no Miss November I would call it yeah bye see you tomorrow
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
1
welcome back everybody this is the solution to lee code problem number one twosome in golang let's jump right into it so a quick description of the problem we will have a slice of nums which will just be some arbitrary list of numbers says two seven three four this one is just of length four and we will also be given a target in this example let's just use nine so now what we need to return is another slice of the indices from num that equal nine okay so if our target is nine then the two indexes that add up to nine will be two and seven here two and seven so those indices would be zero and one so then what we would want to return is a slice with zero and one in it okay so some additional parameters you cannot use the same number twice so what that means let's say that we had three and four and three here and our target was six we wouldn't be able to use zero here like if we just use this twice so we cannot do that what we would actually want to return is zero two so that's not using the zero indice twice okay so second consideration for this problem is that we can be assured that there will always be at least one answer so we don't have to deal with the case where the array the slice that we're given and go doesn't have the numbers so let's use an example of zero one two and the target being four we don't have to deal with this case we can always be assured that there will be an answer now as with most programming interview questions the first thing you should really ask yourself is well how can i brute force this and the brute force for this is actually pretty simple what we're going to be doing is iterating over both slices and then checking for the target and then we can simply return that target if it exists after iterating both so let's implement that real quick and go what that looks like is we can do a four call this left and range we're going to be ranging over the numbers and then that's our first iteration so that's just going to go through all the numbers the first time and then we can do it a second time we'll call this right range nums and then that will go through the second time now notice the complexity here this should obviously be a n squared complexity because we're doing an iteration on every iteration so this is a square complexity so then in here is really where the magic happens we can do if left plus right equals target then we're going to return a new slice of ins with left and right now that gets us pretty much all the way there but remember the caveat we cannot use the same number twice so let's throw a quick end in here where i does not equal j let's give that a quick run and i forgot sort of the base casing go we need to return nil now remember this is that other caveat just return nothing since there will always be an answer returning nil here isn't what i would consider good programming practice but for the sake of leak code this is fine this gets us to the solution let's give this a quick run again bro that is the wrong answer we need the indices not the actual numbers so notice here that i was returning the actual numbers which was two and seven that equal nine we actually need those indices which is zero and one so let's return that again and huge success there it is ladies and gentlemen so again notice that this is the square complexity this is the brute force solution and in most interviews if you can get to the brute force the first thing you want to start thinking about is optimization how can we make this better so we can leave this nil case here this is pretty much going to be true no matter what but what we can start to think about is a much better solution using a hashmap so what this is going to look like is we're going to create a hashmap we're going to iterate the numbers and we're going to add complements to the hashmap now this is a little different than some other approaches that you may have seen we're actually going to be adding the complementary number from the target to the map to then access later to return the correct number as we iterate this gives us the ability to iterate just one time through the numbers so let's actually implement that so this hash map is going to look like this and go we need to make a new map so we call that map this is going to be a map of integers that map to other integers and then we're going to iterate the numbers so for those numbers in the range of numbers and again this is very similar to the previous solution but we're just iterating one time and using that memory cache to find the complementary number so let's implement that first thing we're going to do is we're actually going to check if the current number is in the map which means we found the complement and we can return the indice that's been stored in the hashmap so hashmap and we're gonna do an access with that number and then in go this usually looks like this if okay we are going to return the new slice so this gets us most of the way there but we're missing the chunk where we actually need to store the complement numbers so let's actually do that down here outside of the if catch where we access the hashmap we take the target minus the number we're looking at and again this is the complement to the target and inside of that complement we're going to store the current index that we're at okay this looks fine let's give this a quick run see where we're at and we got there okay let's give this a submit just to make sure i had it right and it's been accepted awesome all right let's close this so we can see all this code in its glory this is the optimized solution for using a hash map with just a single iteration so with just that single iteration this gets us to o and time where n is the length of the array so maybe let's use that example again just to make this super clear because i think understanding the whole complement side of it is really important so let's say that our slice of numbers is two seven three and four and our target is nine when we first go through this right here what we're going to be looking at is two at index zero so when we get to this bottom part what actually gets stored in the hash map is going to be seven notice this target minus num here so we can actually put that in this complement here so target is nine minus two and that indice that gets stored in there is zero so then inevitably on the next iteration really when we make it to seven we're going to look at that and we're gonna say does the hash map have seven and it does that returns zero from right here so we can return the indices that we're at here which is one and the one that is stored in the hash map at zero so right here where we're storing that complement to two inside of the hash map is where all this magic happens gives us really clean solution where we just have to iterate one time and apparently that runs in zero milliseconds and is faster than a hundred percent of go answers woohoo we did it super fast thank you ladies and gentlemen for watching i hope this was useful like comment subscribe for more of these videos and i will catch you guys next time peace you
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
920
Hello everyone, welcome to me channel, we are going to do video number 55 and in the big part of its playlist, you will know the system of DP. If you want to study carefully, then listen to it, more videos are going to come, okay and hope the question is 1920 hard mark. Yes, but literally, I will show you such examples which will make this question very simple and all you have to do is what the problem has been told, you will not have to put any extra brain but you will have to pay attention to one or two things which we will clear from the examples. If you take it then it will definitely be easy and you will be able to write the code yourself. The name of the question is Number of Music Playlist. It is okay. It has not been asked by Meta but I doubt because this question can be Spotify or like this. You must have Spotify or like this. You must have Spotify or like this. You must have asked the company but I am not sure, I just know that Meta asked this question, okay let's move ahead, understand the question, it is said in the question that you have a unique songs and different songs because of your mother. These are A B C Di and Sohan, these are your songs, they are unique, all are different songs, you want to listen to the goal songs, you have to listen to the goal number of songs during your journey, the trip that is going to happen in your plane, you want to listen to the goal number of If you want to listen to a song, then look here, note is written that it is necessarily different. Now, it is not necessary that all the songs in your playlist should be different, some may be repeated, okay, then avoid board, we will create a playlist so that's it. Now look, pay attention, this is a very important part, okay, let's take mother, now look, let's take mother, let's think like this, let's take mother, but you have planned that you will sing five songs during your trip, so brother, you have three units of songs. And you have heard 5 songs in the whole trip, so now you will have to repeat some song, you will have to listen to the first song and the second song will be over because you only have three, now you will have to repeat it because you are on a plane, what do you need? If it is okay to listen to five songs, then which one can be repeated, I am trying to understand that this is the point, now a song can be completed only then, like Maa, if you can repeat Jab A, Jab Is A and Next Jo. A has been played the last time you played and what I am going to play now, between these two I have played the number of songs I have played. If the value of this number plate was two then look, I can play A here. I am again because look, there are two songs between this A and this A. Okay, now mother, let's go like this that if the value of k was three, then ABC is given. Okay, sorry, I have played whereas in the question, what did you say k=3? This means that we will have to play at least three say k=3? This means that we will have to play at least three say k=3? This means that we will have to play at least three songs. Okay, it is clear till now, so in the last question you have been asked, you have to say that life is a goal and return is the number of possible playlist dates that you can create. Tell us how many such songs. You can make a playlist which follows these two criteria, okay, I will do exactly the same and you will immediately understand its prediction, I will try to make you understand with an example. Okay, now let's build intuition and understand the story. How will we approach this, okay, our entire focus will be on this, you write the code yourself. Option one, what is the option, what will you do with your playlist, okay and what is the second option, you don't have any option, okay attorney life time you. Do you have the options Player Unique Song and Player Sound? Okay, that means the number of playlists I can get from this strategy and the number of player lists I can get from this strategy will add up to both and the total number of playlists will be calculated. First, let me explain option one to you. Okay, what was your option one? Option one. Play, let me tell you one thing. I am talking to the office. You will have to pay attention to one thing, how many songs have you added currently? Goal number of songs. Okay, so I am also writing the count of unique, how many unique phones, why do you have to keep track of it because remember it was said in the question that whatever playlist you make, you should play all the unique songs at least once. You will have to play either ABC after that, A after that B, after that or so on, we will have to play all the unique songs once and now remember in the question it is said that you have total n unique songs at least once. You will have to play, okay, your goal has also become rich because you had five, your goal is okay and you have played every unique song once, see ABC, it has been played once, okay and let's take it. Tu Tha To, whatever song will be repeated, it will be repeated after two songs, like Maa Lekh A, I had repeated it. Look here, if it is repeated after two songs, then we have followed all the factors. Okay, so if we look at it, we have We have to pay attention to these two variables. What many people do is that they directly say that we will take these two variables, but you should also tell me, brother, why have we taken these two variables, why do we need to keep track of these two, okay? So it must be clear to you from here, okay, it's great, now let's see how we solve it with these two variables and you will know that in the beginning you have not played any song and have not even created anything when The song is zero and the count unique is also zero, okay, this thing is clearly visible to me, now let's move ahead, okay, so my recursive tomorrow is something like this, I am not able to see it yet, okay, now look, pay attention when Remember this option one, what happened in option one was that I have played a unique song, okay, I played a unique song, what does it mean that we take the result variable mother, keep it at zero, now keep it at zero, okay, so now one. If I have played a song and it is unique, then I have played one song, so I will have to keep an account of it, so the count of songs plus one is that I have played one song, later I will see that the count becomes equal to the song goal. So I will stop there because I have to play the total goal number, okay and science, I have played option one in option one, is there a unique song, so will the unique song ever be added to the account, I will add the account of unique plus one, both plus one. Pay attention, whatever comes, we will add it to the result. Result plus this is equal. This is fine. But pay attention to one thing. Total number, how many unique songs do we have. Total number, how many unique functions, how many unique songs have you played now? How many unique songs are there, how many remaining unique songs are there, how many unique songs are there, what does this mean that you can choose any one unique song and play it, you could have played it here, so how many options do you have, Unicorn? You could have played it and after that you could have solved that he will bring it for me, understand what I am saying that there were other unique songs in the total number and till now you have played two unique songs, okay and who are those three mothers? Let's take Added it to your result, then what did you do with this and said that no, A can also be heard, so if you are solving it three times tomorrow, then multiply it three times, it is better than this, okay, so I am saying the same thing here. What will I do, here we have one extra thing, what we have to do is that the solution which we are doing tomorrow, look at N - total unique N doing tomorrow, look at N - total unique N doing tomorrow, look at N - total unique N and how many blocks we have done so far, count the unique songs played, we will multiply by this, why is this so? We are doing that also, understand why it is multiplying because we have so many options, remember the unique function, option one is going on, if any one of them has to choose each one and give it to everyone, then from so many possible options, unique song Chunni. For that, we multiplied it like this, it is okay, it is clear till now, we will add it to the result plus it is equal, you are the most important and the most two part of this question, this one was actually okay, it must be clear to you. This is the second step, it is clear till now, my option one is also completed, it was so simple, think, option one, mine is also completed, okay, now coming here in the last, you are okay, very well, now I am coming, option you. But ok option tu par option tu make current account song kya tha count song tha na current you have heard so many songs you have played one song now you have to do it so it must be a plus one because you are playing one song Right and you are already replaying a single plate song, that is, if you are replaying, you are not playing a unique song, your count as unique will remain the same because you are replaying, there is no unique song in the market, so the count is unique plus one. Add it will not happen, option one will have counting plus one because there we had played a unique song, here we are not playing a unique song, we are replaying any song, it is okay and whatever happens with this strategy, I will do it tomorrow in the function. From the solution given, it will bring for me whatever playlist can be made with this strategy, go for me and I will also add this in the result, I will add the result plus this equal, but there is something missing here also, what do you remember? There was something like this here too and there is something missing here too, okay let's see, we will do that also, we did not pay attention to one thing here that brother, we are replaying a rape song, so we did not pay attention to it. Did you say anything else that you can repeat a song only when you say ' you can repeat a song only when you say ' you can repeat a song only when you say ' A B C Hai', 'A' can be repeated only when ' A B C Hai', 'A' can be repeated only when ' A B C Hai', 'A' can be repeated only when ' A' was played last time and 'A' is A' was played last time and 'A' is A' was played last time and 'A' is being played now. There should be a distance of songs between the two, at least they have been played, it is okay, so we have not paid attention to it till now, okay, so they see, let us understand it from an example, look at the example of ours. I have a total of three unique songs and how many total goals do I have to listen to a total of 10 songs, I have to add 10 songs in a playlist, I have given the value of two, okay, so I have made a playlist and let's see you. I have three unique songs A Bear C So I played A Okay So I played B Its still okay C Played Still okay But I have to add total 10 songs in my playlist Okay so far only three songs If I have added it, then it is obvious that I will have to repeat it. Now look at the song, that is, now neither will I have to add a repeated song here nor will I have to add a repeated song here, so now tell me yourself which one can be repeated, can you repeat C and what not? Because now if you put C then there should be two sounds between this C and this C. Why two because that means it is not in our option, we cannot play it because look there is only one song in between, we want two songs so choose A. If you can choose then look here i.e. here i.e. here i.e. which song should be played at this position, how many options were there, poor guy, there was only one option and who was that option A, there was only one option, poor guy, it was A, so I chose A here. I have played it is clear till now, okay, let's move on to the playlist, even after this I will have to reply to some song and I do n't have a unique song, otherwise I can reply to anyone and you will play it now, if there is no gap in between, then A. Can't do B, can do B, there are songs of K, that is, who can play B, only B was there, okay, so I am writing one thing, notice how many option A is there, one for repetition every time. Only option A has been there, last time there was only A and for this position there was only B, every time there has been only one option A, let's play B, after that look, here B can be played, new one can play C. So, if there are two songs in between, then both of them cannot be played. There is still only one option. So you see, there is only one option to play every time, one option is only one valid option. Now let's take another example. This is golden, I am fine, I am making a playlist, played A very well, played B, learn, played, after this, who can they play, we will have to replay because we have to make a total of 10 songs, okay, now see whom to play. Can you play C here? Not at all because there should be a song between C and C. The key value of K is one. This time it is okay, so here I write a question mark, what will C come here? No A can be A can So how many valid options do I have here? There are two valid options. You are looking at me now. Now pay attention to one thing. Relate this. When you have to replay a song, how many options do you have? Relate it, look how here, look, we were repeating A, do you know why it happened, I had a total of three unique songs, okay, so here's A, okay child, just one, this one mantra unique What a unique song you played, one two three mines one ho, you played it here and if you played it here then how did you get two options, three mines one, if the mines are ok then my option is tu ka, the expression I had written here is solved. It has not changed because I have replied, no one has played, what do we have to do here, as many possible unique songs, sorry, as many possible options as I had, we will multiply by the one we could have replied to, here I will explain it separately, this is also very simple. First of all, when the solve function was there were only two variables in it, count songs, how many songs have you listened to, have you added them to your playlist and account, how many unique songs have you listened to. Okay, so look at the base. What will happen is very logical, you remember how many total songs you had to listen to each player, for this the goal number of songs, then if the count songs is equal to the goal, it means your playlist is complete, because you have to listen to the goal number of songs. If you were adding, then the playlist has been added, so one playlist has been created, okay, that playlist will be valid only when all the unique songs should have been played at least once, then how many unique songs should you have played, less and play more. There should be songs, okay, only then that playlist is valid, so now I have a playlist ready, and if it is not so, then what will I do, I will make the return zero, how many unique songs do we have, how many uniforms have we played and played, which is also what to do. At least you had to click on all the unique songs once, you were maintaining this account as unique, so I was maintaining it so that I can check this at the last and relax. This is very important with the base. Okay, I actually missed this but later I understood, so I added it again. Okay, and yes, before doing the court, let's check the time complexity, if we had not memorized it, then it would have been time compressed. Then I said, you have only two options every time, how many songs do you have to play in total, goal songs, okay, how many songs can you do in your playlist, goal number of songs, you will have two options to select each song, right? Here for whom will this be my count of songs and for whom will this be, remember the count of was unique, it was kept for two variables, for memories, okay then how much will be the count of songs, so many seats we will visit, right? Okay, so this is done and one more thing is that I will code for C Plus, now along with that I will also show you the code of Live and Java and the code of rice, I have given the link in the description, which is the code. Let's learn more about it, then there is code in both of them and I will put more code in the comment also. Okay, so let's finish its code quickly, so let's do its code quickly and do show this question to those who ask this question again and again. It is said that recension and memorization are not very important, see how good recension is, isn't it? The recension is also written in two, it is quite ok, so give us three variables, let us store them as global so that we do not have to go through the internet again and again. Goal and its k are okay and here I assign n = n and here I assign n = n and here I assign n = n goal it is equal tu goal and k = k is okay goal it is equal tu goal and k = k is okay goal it is equal tu goal and k = k is okay global variables come I don't suggest but question means to keep the code clean I make it global so that Don't have to pass again and again return unique songs. See what I said that I am going to keep a variable named result. Well, make it long because it is given in the question that big values ​​can also be obtained. Okay, so that big values ​​can also be obtained. Okay, so that big values ​​can also be obtained. Okay, so what is my first option? Tha option one's play unique song ok result plus is equal tu en mines till now how many uniforms have I played that mines because it plays ok reply song also do the same result plus is equal tu here what multiply used to do It was explained well with the example of account unique mines, okay multiply by because I have just played a song, so it must be plus one, it must be okay, we replayed the option, you are ours, this is count unique plus one, we did not do it okay. In the end, what we have to do is to return the result is clear till now and pay attention to one thing, it has been said in the question that the power should be a very big value, so the power of the tank is to be taken from nine plus seven, so I am defining here. Which stop and modal do I do, this is equal to 10 equal to you, sorry, this is fine, here I return the mode before returning the result, so here we have done the mode and sent the result. Now one thing, look at the last thing here. Low Ki N-count Low Ki N-count Low Ki N-count should not be negative, it is an obvious thing, when can you choose a unique song, when you have more unique songs, then only when you have children, that is, what does it mean that my count of unique is, right, it should. B. Lee Dene N. If there is no Lee Dene then it will become negative, is n't it right? And either consider it as if the count is a unique girl, there should be a few, it is okay, that is, mother takes it, all are played in unison, so here. You will not have any option for Unique on Chunni. Okay, there should be children, that is, counting should be done, only then you can multiply and if you do not do it again, it will become negative. Right, similarly here also. Check if you are counting unique mines, then brother, now the same thing is there, here account unique should also be taken so that it will give negative seat because we have not memorized it yet, okay and every time you have to return the result. Before returning, I will assign it here directly or I will sign it here before returning. Okay, solve this question. So look, this is Java code. This is exactly the code. Look, we have defined the global variable, defined the mode, initialized it here. Given mines one is ok and solve function done yesterday ok memories have been checked here memorization was checked there were two options done both the options returned in the last there is nothing different from everything I have told it is C plus. It will also definitely pass, I will share it with you will get the code definitely in the description link, I hope, I was able, you can help, if you have any doubt, please comment, area, tree, help, see you, gas video, thank you.
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
809
Jhal on karo ki backward scientific list ko problem 10 school regressive words and this problem yogi one two inputs one is the so friend and the most important strategically are of world records a woman you have enough to find how many words in this query words can distract Facilitation and resultant world after starting the work well in word format is the source input tax and defined as som have put his mother content owner of the country is so lets you cancer madhoganj dharmichand and 920 problem solve list years of construction dowry co constraints of pt Thomas Alva Edison Entry World Most Important Constraints 10 to 14 Championship Fennel To Regret Over Time Too Easy Was * Find Weather Any Given Every Word Easy Was * Find Weather Any Given Every Word Easy Was * Find Weather Any Given Every Word Research and Can Distract into the Sauce World and in All Districts of Difficult Words into This World Laddoo Flu Positive No Content Which Has Been Listed Should Contain Electronic And Stretch Friend Se 20 You Can Choose Group Of Ministers And It's All The Best In Objective C Disha Group Tractors You Can Do Subscribe To Bluetooth Settings Developed Country Inquiry Board Sudhir Gupta System Of Tools For This Particular Group Study in Are you can do Subscribe V0N0N0S0R0 Result needs to be greater than or equal to Subscribe Ki Kaur Sukhbir Kaur Bhi Abhi Mutu Solid Zaro Problem Lexicon Understand This Particular Point Which Contains In Various In The Distic Were Sold It Welcomes Easier For Personal Problem Solved Is Listed At Every Year In Frequency And Stable And Food Very Simple Co Records Were Sold Swayam Olive One Character And Isko * Help Us Understand Your Problem Character And Isko * Help Us Understand Your Problem Character And Isko * Help Us Understand Your Problem Will Be Amazed I Read Sunil Shetty's Example Love You Have A Reward Twitter Minister In This Column Universe 200g Universal Stand Se Controller In The Robot Boy Who Also Observed With The Superintendent Is To Obvious Reluctance Third Class Have Interest In This Should Here All Women Fight To Our Body Size One Should A Question Is Can Be Considered To Be Subscribing To See You Can We Make To Express Subscribe And Subscribe The Amazing Subscribe That Sureshwar Williams And No Sorry No Dispute 90 Example Way Triple H And According To This Content Does Not Fit Subscribe Already Subscribe 504 Subscribe to this idea You can subscribe button too to two just in case of birthday this not want the problems of years should not be considered a special Award And Finally Subscribe Button More * World Blurry Problem Solved Subscribe Now To Receive New Updates Police Looking For Example Lool Subscribe To Yesterday Morning Both Olive Observations You Have Noticed That You Need To Note This Affair Is Always Believed To Check Weather The Tarzan The Thing You Need to Know What is the Length of the to subscribe and subscribe the Channel Please subscribe this YouTube Channel and subscribe Airplane Position Solid Food Inflation and History Now Half the Fuel Let's Look at This Example Indicates a Point They All Should Support One Body And Significance Request Born Into Your Relative Vegetables Pimples Will Be Us Tomorrow Morning Anshu That Computer Length Of The Saw Your World India In Objective Vaseline Time In The Land Of Repairing Sequence Forget Character And You Can Easily Find Out Weather This Particular Sequence Chemistry To The Software For Example Subscribe Video Subscribe 10383 subscribe our Channel Please subscribe and subscribe the Channel Ko Tours Loot And Asks Lord Shiva Ko 210 This Is Possible In 1000 Scorpio Chanakya Understand You Know How To Basically Proceed With Respect To Solve This Problem Once You Release That Categories Are Comparing Equal Subscribe And You Know The Subscribe To A Novice Not Give Loans For Rich Look At How To Solve This Problem Stress Buster 24 The Invention Share Transfer subscribe our Channel and subscribe the Channel And subscribe The Amazing Character subscribe The Channel and subscribe this one Adhir Ve Khair ki force vacancy apni progress and improvement aaye and 6 yeh to aaye Vikram at the time of the person of Lord Jesus Christ 1237 more final and subscribe the Channel and subscribe 209 Om Vinod Art Once in this way you can add to marketers so and equal to three Bigg Boss-8 Spice The Equal to Better Than Bigg Boss-8 Spice The Equal to Better Than Bigg Boss-8 Spice The Equal to Better Than Additional Friend This Swimming Problem Solve a Research in Its Possible to Speak This Introduce 10000 in To-Do List Introduce 10000 in To-Do List Introduce 10000 in To-Do List Subscribe Must Subscribe Consider This Position Subscribe Do So Naturally Compare It with Jain Subodh Date Ko Exam twelfth unveils size of sleeping and studied with scientific and stir well as in this case from both in more show what we do it is will begin from the next shop comes with that and welcomes a heart this ka juice aaye 100MB college shampoo se switch one Lootere Final Hai Length Of Ko Is Vansh 153 Liye Bluetooth Subscribe To The Page That Navlesh Look At One Point Not Achieve Don't Example In Description Se Zor Tab Screen INGO And Sorry Share And Subscribe To Bijli Company History Switch C Code Too Much Land For This One Subah Se Apni Profit If Sabse Zor Shobhitam C In This Case 100 Both Are Equal Gland Of His Three Length Office 200 MB To 1MB Connected To Three Wedding Tourism And The Resulting Size Better Than And Equal To Three layer should be responsible to display accused next listen or vikram share and tree to share so let's check electronic frontier in this again is equal to help ireland the least to the length of junior hundred shoes adv1 via bank want to listen this point but problem this Result Sequence Size Will Be But Complex This Is Not Possible Video Friends That Difficult Yo Stretch Saunf Constraints And It's Not Possible To Stretch Report Volunteers Old Nagpuri Amit Va Positive Negative Example You Have For Real Life But How To Go For Solving This Problem In Real Interview of Tax Code Everywhere Link Here Description and This Video You Can Go to the Killing and Answers on Every Floor and Other Video Tutorials YouTube Able to Easily Understand This Post on
Expressive Words
preimage-size-of-factorial-zeroes-function
Sometimes people repeat letters to represent extra feeling. For example: * `"hello " -> "heeellooo "` * `"hi " -> "hiiii "` In these strings like `"heeellooo "`, we have groups of adjacent letters that are all the same: `"h "`, `"eee "`, `"ll "`, `"ooo "`. You are given a string `s` and an array of query strings `words`. A query word is **stretchy** if it can be made to be equal to `s` by any number of applications of the following extension operation: choose a group consisting of characters `c`, and add some number of characters `c` to the group so that the size of the group is **three or more**. * For example, starting with `"hello "`, we could do an extension on the group `"o "` to get `"hellooo "`, but we cannot get `"helloo "` since the group `"oo "` has a size less than three. Also, we could do another extension like `"ll " -> "lllll "` to get `"helllllooo "`. If `s = "helllllooo "`, then the query word `"hello "` would be **stretchy** because of these two extension operations: `query = "hello " -> "hellooo " -> "helllllooo " = s`. Return _the number of query strings that are **stretchy**_. **Example 1:** **Input:** s = "heeellooo ", words = \[ "hello ", "hi ", "helo "\] **Output:** 1 **Explanation:** We can extend "e " and "o " in the word "hello " to get "heeellooo ". We can't extend "helo " to get "heeellooo " because the group "ll " is not size 3 or more. **Example 2:** **Input:** s = "zzzzzyyyyy ", words = \[ "zzyy ", "zy ", "zyy "\] **Output:** 3 **Constraints:** * `1 <= s.length, words.length <= 100` * `1 <= words[i].length <= 100` * `s` and `words[i]` consist of lowercase letters.
null
Math,Binary Search
Hard
172
221
hi friends welcome back today we are going to solve a problem uh find area of largest square in matrix so we are given a binary matrix with zeros and ones and we have to find out the largest square formed by using once so for example we are given an original matrix here like which is a six by six it is a six rows and six columns and we are asked to find out what is the size like what is the area of the largest square so uh every one is counted as a square of area 1 so for example if you look at this one then this is a square of area 1 then if you look at this orange border square this is the largest square in this matrix with area 3 by 3 so the area is 3 by 3 means 9 so as you can see it's a 9 once and this is the largest square in this matrix there are some other squares with you can see like this 1 so this is a square 2 by 2 with the area 4 but this is not the largest square so we are interested in finding the largest square in the matrix uh so how can we find this actually so we are going to use a dynamic programming technique where we will create a dp array of the size same size as the original matrix so if the original matrix is 6 by 6 the dp array will also be 6 by 6 and we will keep populating the dp array from the original matrix as we traverse the original matrix so first what we are going to do is we are going to keep the first row and first column of the original matrix same in the dp array so as you can see this is the first row 0 1 right so here also it is 0 1 so we will be keeping the same as the first row and the column also same in the dp array so it is 0 1 0 right 0 1 0 so uh this column and this row we will keep same in the dp array so at the same time i will be this i will be discussing the from this diagram i will be showing you the implementation as well so here as you can see we took a dp array it is the same um row and same columns as the original matrix and we are first populating the uh first row and first column it is the same as the original matrix right and then once we are done then we will start iterating the original matrix from the index one so one cell we will start iterating so we are here so we are at this cell which is a one cell so what we are going to do how we are going to populate the dp array is we will look in three directions this upward direction this left side direction and this diagonal direction and we will get the minimum number from these three elements and we will add one to it when we see a one we will do that if we see 0 we will just keep 0 as it is as you can see 0 we see here so we kept a 0 here same but now when we see 1 we will look at this 1 0 1 so 0 is the minimum element so we will add 1 to it so it becomes 1 into the dp array so similarly if you look at this highlighted orange color you know orange color square then as you see here it is one because here like the minimum element is zero here so we kept it one uh here also we have one because we have a zero here so we kept it one here uh here it is one because we have a 0 here so 0 plus 1 is equal to 1 so for example if we are at the i and j cell here then we will see in these 3 directions right 1 2 3 so which is i minus 1 j minus 1 and i j minus 1 0 so these three elements we will look and we will take the minimum of if and we will add 1 when we are having a 1 in original matrix so for example now when uh you can see this one as a highlighted in a pink color right so when we are uh doing a dp array for this element we will see one here so we will have to add one plus one which is 2 here right so that's why we have a 2 here and the 2 it makes sense because this is a 2 by 2 matrix now right if you see this then this becomes a 2 by 2 square basically this is a 2 by 2 square that's why 2 came here and when you are looking at this green color 1 then when you look at like in the dp array when you look at the 3 directions here you see 2 right so you will add 2 plus 1 which becomes 3 because this one is a 3 by 3 square now so as you look into this highlighted this is a 3 by 3 square that's why 3 came here and that's how you know we will keep uh when we are doing the populating dp array we will keep track of the maximum value we have seen so far so maximum value we have seen is three here so um you know this is the same logic that we have discussed that we will look at the three directions these are the three directions that i was talking about so if we are in the i j column i j cell then we will look into these three um directions right i minus 1 j minus 1 and i j minus 1 and we will take the uh minimum value from that value as you can see like this mat dot minimum so i will take like minimum value into dp of ij cell and then i will also take this square length variable i created to get the maximum square length we have seen so far which is 3 in this dp array so we will capture 3 here and once we are done at the end we will just return square length into square length because if 3 is the length then the area will be 3 into 3 which is equal to 9 so that's how we will find out the largest square in the given matrix so this is the same matrix that we discussed i took it here in the example so let's give it a run and it should give us the nine as the largest area so like nine is coming as the largest square area here so it is correct so this is how we can find out the largest square in the given matrix so we will just pop we will just use a dp array of the same uh rows and columns as the original matrix and we will populate the dp array as we discussed here and we will just you know return the square length the maximum square length that we found during our uh matrix traversal and population of dp array uh so this is how we can solve the problem of finding area of largest square in matrix if you like this solution please subscribe to my channel and click on the like button and hit the bell icon so you will get the notifications for future videos thanks for watching the video
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
1,971
Hello Album So N Statement festival import in the form of number of verses and the apps in the form of day the heart should abstain from zero two and - first of all - first of all - first of all in India in today they are what they are giving every day at the age of you I love you I Love You I Don't See The First President of the Apes And A Pyun On The Heart Should Have Ended Everyone Tips Paris Connected By Its Most Dangerous And What Is Unbreakable Just Want To Say Wax Paper 10 Examples Hit The Subscribe Button And Into It's Not Have A Hai To Also Every One And Know What Is As NH-28 Sirf NH-28 Sirf NH-28 Sirf Veerwar Sirf Subscribe School Of Balbir Singh Hai To Ab Yaar K11 Start Vriksh And Attacked And Will Have To Return Proof Videos Aap Soe System Problem Statement Last Undistorted But Think How They Can Solve this problem so let's positive end with this question on 200ns problem lecture graph in the form of intent and eggs in the form of due to withdraw all currency notes and according to the problem the number of applied research in the time of the subscribe to this point 210 interruption 10 and back date me ka accident time limit for b id candidates b ki and isi gomez se list to in this time limit for a time complexity for this channel tamil mode of birth date will be doing what is the number of apps tours Subscribe subscribe to subscribe our problem without going into a timely 102 is so what we can do yes we can convert in these apps in to-do list worst thing you have to convert in such a stew that arjun singh is loot the second time aa they cant To Delhi can't apply meanwhile safe on adjacency latest co on how they can apply fat upline benefits will give us such cute that will also create another factor that is after scene shoot nod that and finally ag to advertised cnn vitamin through and for Return a recording to the scene and attacks hua tha hai to aap first will convert apps to addison apply difficult life is after all tours which will be and will I have scene and finally check the final report hai kya to absolut adjacency list having all and everyday 100 A Decade and Creative Singh Dr Hua Hai Me Novel and Updates Ad Agency List According to the Giver of This 102 Voice Mail in Kheda Two Variables and With That Means To The Amazing Connectivity Attached Hai Ujjain The Same Size Hua Hai Loot Mein Aaye The Jhaal Ka The Sun That You And E Will Total British Connect With Toys Suomi Ki Anaj Singh Celest Ki Addison C List Of You Don't Push Back Whatever Question School Staff Means Rathore Pack Video 11016 Date A Addition Celeste According To The Differences Novel Applied Benefits On This Edison to apply benefits of your first create artwork who will say in your voice mail vectorchina diet vilas tours of vinas in this world or not 207 the return of life ulta app key and size and then actor will be the number of district bihar vindhya craft and will initial Is all scene too for details were not seen that the tax interesting now after the year will post some days given due to the site and also will update scene the first to two to 200r navya writing one robert chanda why shoulder why is not mp Will keep sharing next why and avid traveler the gift of all the states connected from the start button to subscribe flash light of why I scold MP3 me cholesterol a point is hour or electronic das a valid for one more reliable data is current vertex 200 Current voters will be the student pant on hua 210su diet friend and wireless set n hai SSC list of the current tax act co start site ka sex e want to avoid traveling all the connected from the first but it will get converted to believe with you The second and taxes, do the water school to me, I am the latest from you, that star is a friend who takes pants, that Sophia is already in the second voltage, you will spoil the detractors and difficult service, that the fashion of surrender tax, a motivational short notes, of General Paul Center. So that he can listen to his voice mail operator RCM Tractor Shroud in to-do list listen to his voice mail operator RCM Tractor Shroud in to-do list listen to his voice mail operator RCM Tractor Shroud in to-do list that he unveils Taxes Simple To Vanvas Taxes Complete Exploited All Apps Once Connected Taxes Attitude And Will Start From 200 Blue Dot Com I 16 Year Lesson 108 last two years paper and attacks or not and withdraw servi turn off that and that tenth return to tests aphoto that is Sonalika brand code or gold se go form custom test in the name of loot soil test only that how you slept factors For Breast Cancer Thank you for watching my video
Find if Path Exists in Graph
incremental-memory-leak
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself. You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`. Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._ **Example 1:** **Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2 **Output:** true **Explanation:** There are two paths from vertex 0 to vertex 2: - 0 -> 1 -> 2 - 0 -> 2 **Example 2:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5 **Output:** false **Explanation:** There is no path from vertex 0 to vertex 5. **Constraints:** * `1 <= n <= 2 * 105` * `0 <= edges.length <= 2 * 105` * `edges[i].length == 2` * `0 <= ui, vi <= n - 1` * `ui != vi` * `0 <= source, destination <= n - 1` * There are no duplicate edges. * There are no self edges.
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
Simulation
Medium
null
313
Hello One Welcome Too Late To Ways Today In This Video Will Discuss About Super On Next Number Default Settings Video I Will Recommend You To Go Through Next Number I Have Made Video Aane All Give Link In Description Box Shoulder Affidavit Before Starting This Video Mota Supada Next Numbers Will Have Understood In Last Video Multiple 235 Tomorrow Morning By Train Next Numbers To Be To The Power By Three To The Power J5 Power Of J5 Exceptional For Next Numbers Sudhir 12345 Opposite They Are Coming To The Number Positive Number Give Size K Numbers Multiple Number 231 Exceptional Prime Number 40 Who Is Defined Over 8,000 Multiple Of 231 Is Defined Over 8,000 Multiple Of 231 Is Defined Over 8,000 Multiple Of 231 Subject To * Subscribe 600 2108 32bit K Supavali Number On This Side Customize Form Of Next Number In Next Number The Prime Numbers Were Defined By Default Value Super Gully Number This Customize The Prime Number Date Of Birth Multiple Of Prime Number Completely Customize Next Number Subscribe To 9996 Number Key And Difference Which Studied With Defined In France Problem Spoon Prime Number Only But When She 0.2 32bit Next Number one 0.2 32bit Next Number one 0.2 32bit Next Number one send a last video bf scene bhi program for 10th gali number veer vihar to three and 5s for next number deprive bill only to three 500 calculated next tours pain and swelling and pain in that and accordingly 235 will be seen in the last updated On Main Office Solution Next Number Vinod Confirm About Deputy Prime Numbers Egg In Super Number Will Get Off The Prime Numbers Between Multiple What Will Be Changed You To Three Inch 21 Times Of The Main Likhti Half First Will Make The Program According For Will Run The Program And Understand How It's Working Properly Number Surya Vihar To Take Prime Number And Customize Your Own Soul Will Define And Will Calculate Point Located On Three Lines Subscribe And Share Subscribe Now To Receive New Key Institute Of i2i Shift One By Which P0 Yadav England Stock Price Subscribe 2000 half hours nine will have for loop in calculating the time limit for be take maximum we will be able to make in ours android withdrawal is angio it will take next will run that equal to result of in that * Whatever that equal to result of in that * Whatever that equal to result of in that * Whatever Primes Validity Check 90 need to calculate Dest and will right to waff next day witch they have calculated to pwn in next nuvve divine of next chemin middle melted foreign I will have a good condition who is next gen is equal to next basis for tiger condition wicket to numbers Which is equal to play in numbers that I underscore introduce value up and zenith end on Instagram 10 increment 10 I will make a loop for jan19 Pondicherry that in next JP incremented by one right and will get till last first here will call in explain them end You Will Have To You Romance So Let's Say I Want To Know The Number And Different Prime Numbers Witch 237 So What Symptoms Also Program Sales For Change In That Underscored Check Online Number 40 A Good Been Reduced From That Agni Same Problem Intoxicated Note Subscript Table That Access Result In That And Skimming Online Number 8 That Units Drama Pending Superstar For Water Values ​​From Getting In Not Supposed To Be Water Values ​​From Getting In Not Supposed To Be Water Values ​​From Getting In Not Supposed To Be Up And Saw Your Right Result Dot Up And You In Next Value Flu S0 And Difficulties Solution Finally Sold In This Way YOU WILL GET NUMBER 9 TAGS PAGE 10 NUMBER ME A TAKEN PRIME TO BE 237 THIS IS MY CUSTOMIZED ROY AND ATTACHMENT LIST FORM HOUSE WITCH SELECT KNOW WHAT DO YOU WILL HURT YOU CAN RESULT IN WITCH HE HAS ONLY ONE OPTION ALI SUPER NEXT NUMBER IS BEING Produced in the number of cases will calculate for change - defined next to calculate for change - defined next to calculate for change - defined next to large number of that I have taken in the school j2me are knowledge start with default j-20 knowledge start with default j-20 knowledge start with default j-20 in hindi-10 20000 inf just point to the independence loop slipper from 0001 To 9999 Ki Bihar 20 * Price Of Silo Others Bihar 20 * Price Of Silo Others Bihar 20 * Price Of Silo Others More Than 120 To End Pages Result Sauth One Android 1.22 I Want To Value More Than 1000 Will Android 1.22 I Want To Value More Than 1000 Will Android 1.22 I Want To Value More Than 1000 Will Get To Reduce And Will Have To 2020 Ki 12000 Ayat Calculated Next Value To Bittu Not Valid Arguments And Systems Equal to one tomorrow morning inches option vansh in ix-b hai 10402 calculate the next level you for one intact ho jaaye so result schezwan sauce JB 300 123 labs ki is model next to subscribe button to 9 check weather it's not against J2 Ghruv 180 Hai Na Again Will Calculate Next Pimple Tough 081 Rains Wave * * * * 700 Bill-2009 mid-1960s Subscribe Welcome To Bill-2009 mid-1960s Subscribe Welcome To Bill-2009 mid-1960s Subscribe Welcome To Lu Ki And In Result Will Happen Next Flight Minimum Value Of 237 Dysfunction Is Broken Minimum Will Have Two Three 70 Vighna to result will have to ujjain vivid yasmin ko 251 do hai that we shape tent value from this index swift next person gautam to which is the best result bihar avwal naav ko again for pun in next will aghyayan maximum volume ko vygra mp3 mp3 mp3 That And You Will Calculate Fauj Sequel 2017 Check Out In Linux Ka Pad Viruddha Value Behave In Its One So A Result Of Inductive Will Have Two Value Stuart Broad 2000 Of Objects For You In Next CM 108 Welcome Per Four With MORE THAN 1000 WILL GET MINIMUM VALUE 100 FORESTS MONITOR US ZOR WILL BE IDED 2ND YEAR NEXT VALLEY WITH THIS WILL GIVE OO SUBSCRIPT TRACK FROM WHERE WILL YOU GO TO J2 ACE VIHAR PHASE RESULT SIGHT 151 THIS TIME 333 ABS CALCULATED FOR AAA SMALLER And for ghazi minimum value to give next day minimum value addition and support who will have given value win this alone in the ghrit volume no against will to * in the ghrit volume no against will to * in the ghrit volume no against will to * follow for change vote 2012 vihar phase no will calculate half result and crimes of two in this episode 127 IS 700 VERSUS PET SE VALUE NOVEL CHECK WEATHER THIS PRAYER IS MODERN AND MINIMUM VOLUME MINIMUM RELIEF WORKS IN NEXT 398 WAS NOT 80 ENTRY ES MOD ON SOAK* THIS CONDITION NOT LIKE IT ES MOD ON SOAK* THIS CONDITION NOT LIKE IT ES MOD ON SOAK* THIS CONDITION NOT LIKE IT IS EQUAL TO NEXT 9 SURE RESULT WILL HAPPEN NEXT MINIMUM WE WILL GET In Meanwhile They Got From One Index And Cheese 101 Rather Letter Act In Us J Web E Have One Index Face Go To IA X N Web Result For J0 Calculating Subscribe To *Tor Sainik Jaivika What 500 Isro Night *Tor Sainik Jaivika What 500 Isro Night *Tor Sainik Jaivika What 500 Isro Night Will Check Weather For Smaller Than 1000 Ashwin Next Will Get Minimum Value With This Will Keep Track Of Check 09 2012 Wave Live Video Is To-Do 3238 A6 Great Content For Ubuntu Get Minimum Balance Between Intercept Nation Needs Equal 248 12226 Condition Also Now Next Check Judo Soft Change Into Indirect Disturbance Result 80 Behave in the mid-1960s Disturbance Result 80 Behave in the mid-1960s Disturbance Result 80 Behave in the mid-1960s Minimum Balance Want to See the Results Will Have and This Picture Minimum Value is Fear noida will check from which indicate minimum value from road tax in amazon that night fruit is next nitrate which will again be person maximum value in next maximum value 1000 can take any value with highest rainfall and schools will be against the mp are like this that boat yagya Nitrate Fauj Sequel 202 And Will Check Out In Firefox For Watching This Is Equal To 029 Result Acid MP3 Set An Alarm Tenders Page 232 Twos Sex Supervisors 120 Wicked And Value Service Lose 200 To This Condition And Specific Next Vighneshwar And Schools Will It Index s01 Which Will Have Defined Up Or No Gain A Twilight Positive Vivek Roy By Which In This Case When We Have To Value Son Knowledge Point For This A Smaller Than 600 Juttu Will Find The Value Of Vid U The Victims Not At All Smaller Than Six 100 To That Don't 126 Condition And Result Will Have Next 306 Value To Work With You One Day Birbal Calculated For Ujjain Usko Changes Time Melta To Inductors Over Both Indices Will Be Intimidated By 1503 The Inflation Index To Left Side For One More Time As If You Calculate When Is Equal To 16 Super Next Number Sonth Last Hydration Next To 1000 Voice Mail Address Ko Jaaye Ajna Bhi MP list a slight ki naav farz school 2012 check out and if agri value 200 result that indicates acid is 4 * times of throat and it's two for the is 4 * times of throat and it's two for the is 4 * times of throat and it's two for the 8000 texture wicked eighth you in next nine to compare apps monitor him thrust back minutes check disturbance Subscribe Ninth Class Library System June 2012 Result Se Z 323 Li 90 This Period Amazon Not At All In The Near World That Banerjee Has Twilight Rates For J2 Pro 12.2 Next Meghnad New Dresses Value 12.2 Next Meghnad New Dresses Value 12.2 Next Meghnad New Dresses Value Raghavan Hai *Primes Of Second Experiment Value Hai *Primes Of Second Experiment Value Hai *Primes Of Second Experiment Value From Few Seconds Record With This Lesson 20 Nukes In Court Strict DJ Will Have From Contacts Result Date Of Birth Pending Cases Torch Light Bill Check Out For Window Next Number Let's Check Out Soya Oil Right Lizard Number One Will Rain Coat 7 That Aaj Bihar Calculated To That Result 210 How It Will Work For Super Next Number Was Told You Step By Step To Understand The Concepts Like It Like Share And subscribe my channel thank you
Super Ugly Number
super-ugly-number
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, primes = \[2,7,13,19\] **Output:** 32 **Explanation:** \[1,2,4,7,8,13,14,16,19,26,28,32\] is the sequence of the first 12 super ugly numbers given primes = \[2,7,13,19\]. **Example 2:** **Input:** n = 1, primes = \[2,3,5\] **Output:** 1 **Explanation:** 1 has no prime factors, therefore all of its prime factors are in the array primes = \[2,3,5\]. **Constraints:** * `1 <= n <= 105` * `1 <= primes.length <= 100` * `2 <= primes[i] <= 1000` * `primes[i]` is **guaranteed** to be a prime number. * All the values of `primes` are **unique** and sorted in **ascending order**.
null
Array,Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
264
1,970
hey everybody this is larry this is me going with q4 of the weekly contest 254 last day where you can still cross um i actually been watching a lot of horror thriller movies lately so this has a this name is very uh this name of this problem is very uh reminiscent of that really that's what it reminds me of anyway okay so hit the like button hit the subscribe button join me on discord let me know what you think about this problem and especially if you like contest problems and stuff like that come to discord uh the link is in the description and we'll talk about problems as for as long as you like there's a lot of other smart people there as well so uh they'll help you but yeah for this one um i think i actually knew how to do this immediately um the short reason is because i have i don't know if this is a lethal problem or maybe a similar problem but i did have yeah i don't know if this is a legal problem or maybe a similar problem on code force i mean there was a similar problem that i remember where it's exactly the same idea except for you're trying to get from the upper left to the uh bottom right and so i use that technique here in that so the tricky part about this problem is that you're investing the problem so what does it mean by uh so one thing is that this is also kind of interactive in that there are these cells so you have to be able to be deficient every time and here the rephrasing that i'm going to do for this problem is that instead of going from bomb to instead of asking if it is possible to go from top to bottom you ask yourself is still um a blockage from left to right um connecting right and what i mean by that is uh let me i'm gonna pull up the drawing program real quick hang on uh what i mean by that is oh did i have it up before i okay no i didn't okay yeah so basically the idea is that okay let's say you have a grid uh i'm gonna i'm not gonna draw that many things because this is hard dot right the thing is that in this problem there's a path going from top to bottom or the opposite question is when is it impossible to cross right it's impossible to cross if you fill in the water in this case in a way such that there is a connection from left to right including diagonals because you cannot go for diagonals so in this case you know let's say you know you fill this out you fill this one later um and you throw this one doesn't do anything you know you did this one you know now you connect and now there's no longer a way for you to cross so that's basically the idea you can figure out the proofs in general but oops what did i do but uh but yeah and it might not be in and in terms so that's kind of the idea about this problem um except for the additional trickiness is that you know these obstacles are there and you have to do them live right and what i mean by that is that you may all add them in weird order for example you may add them you know you might oh i could just fill in the color you may add this one and then this one this is still good this one this is oops well i didn't mean to fill on all four of it okay let's just do this one you know and then this one uh you know you keep going and now this is still no good and this one now it is no good right so you have to be able to do this live where you go okay now i can finally connect them here even though um if we go back a little bit uh you know now basically you go let's say you painted this one it does nothing except for now you can kind of see that this connects to here um let's say this one it does nothing this one does nothing and then let's say this one okay now they're connected and then this one you go out this is connected right um yeah and then eventually but that's basically the idea um okay let me get rid of this and you know we've been talking about whether there's a path from left to right and hopefully that should bring something to you um so if you're given a static map where nothing changes then you know you could do a debt first search you could do a breakfast search you could do whatever and that'll be fine right in this problem breakfast search and death research is gonna be too slow because you're gonna be adding cells and it's gonna take a while before you add enough cells if you keep on doing that for a search it's gonna do some quadratic relay you know quadratic like things and that's gonna be too slow given that we have too many cells um to be honest so i did leave out one thing that you can do and it is union fine for connected components and i'm just gonna go over now um i usually to be honest i don't like going over union fine in my videos because it is a college level course that is like really long you could spend a couple of classes on it so i'm not gonna go over all the details except to say that if you are having issues of union finding recognizing those problems work on easier problems first look up connected comm connected connective uh connected components or connectivity problems and then after those uh after you play around with how did you use union finder come back to this problem that's what i would say put it on the stack and sell bottom bombs first so that you could pop up the stack later if you will anyway so yeah so this is my general union fine i would it maybe it's a template i maybe i should put it in somewhere because i just essentially i typed this out and it took maybe a minute maybe i get saved a minute i don't know i end up solving this in about 10 minutes actually um so maybe i could save the minute um and here i have an additional key of the left and the right this is just these are just constants or placeholders maybe i should use uppercase for constants but in that case i also set up the union fine parents initialization for left and right um and here we set up the direction and the stuff that we've seen meaning that scene is the stuff that's on the rose times columns map um so yeah so i put it on scene and then now for each cell that becomes water or an obstacle uh for every cell that becomes an obstacle uh i convert it to zero based first and then i look at its neighbors and then to see if this is um if the neighbor is uh an obstacle and cn keeps track of that so it looks at the neighbors if it is an obstacle then we union them together that means that we connect them into one bob one component one connected component um and this is if this is in bounds if this is our bounce then i just do two checks one is that if this is going out bounce to the left then we union it to the left if this is uni uh our bounce to the right we union it to the right and then now we check if the left is connected to the right then that means that um and this is actually a little bit weird on the off by one is that we return t because t starts at zero that means that t is no longer good that means that you know you can think about as t plus one and then minus one because we start t at one in this case for this problem and then we of course we mark the obstacle as being done and that's pretty much it um i don't i couldn't find any assurance that uh on what the default case is so i just returned t here so i don't know if this is even true because they i couldn't find any uh yeah or whether that it is always going to be oh actually no i take it back so cells.length is equal to rows times cells.length is equal to rows times cells.length is equal to rows times columns so that means that you're always going to terminate i actually missed this during the contest so that means that you're always going to terminate because of you know the pigeonhole principle right at some point you can connect the left to the right so this actually never happens then um but yeah um so in terms of complexity uh for each cell we look at eight directions and for each of the eight directions we do one union and one fine i know that you know we can get the details of our union fine complexity but let's pretend that this is all of one ish for now so uh even though my implementation isn't quite that but yeah let's say this is 01 ish so in that case this is going to be linear in the size of the uh input which is going to be r times c so this is oops o of r times c time and in terms of space ref of r times c space because that's what we have for the union find data structure one cell in one in the parent um yeah uh you can actually even make that output sensitive but it's not worth doing it for me here um but you can uh look at that as a stretch go at home if you want to make this into output sensitive of k space uh and of k time i'm where k is the answer t maybe um and the way that you would do it is by not uh doing another way of initialization so that you basically don't initialize unless you have to so because most of the linear um cost isn't here right isn't actually this for loop so anyway um that's all i have for this one uh hit the like button hit the subscribe button join me on discord let me know what you think uh oh and you could watch me solve it live in contest next but i actually knew what i wanted to do immediately i made a couple of um mistakes on implementation that took a while you can kind of see what i did there i watch it on 2x or something but yeah i'm going to show you the top part and then now the bottom part um yeah cool that's all i have for this one let me know what you think and i will see you later uh what a silly mistake okay people already finished i got a five minute penalty on the silliness you know okay entire matrix slide top to bottom working only online cells okay this is easy i guess basically union fine let's see okay uh let's see mindfuls for a second um okay and now we have to initialize um 10 was 10 to the fourth oh but the sum okay i was worried that i was like that sounds too big but it's fine okay and then now let's just do left is equal to zero might just i think one way it doesn't really matter what the keys are and now for cells and now for xy and subs what are we doing in cells so we don't want to oh just a one index why would you want to index this okay fine yeah okay um oh let's enumerate it for opening the time what if it's always possible to do it i don't know this is good but okay it's a default but what am i doing so you insert a thing okay fine let's set stuff okay if y is equal to zero okay let's do it the other way forward i maybe i said this was easy too quickly okay if sit it's insane okay then we want to union fine yeah okay if well this is no good and this is t versus t is whatever this is very ever prone though i feel like i'm missing something silly 338 well that's not right oh no this is right maybe if one well that's what i get for saying that this is kind of easy but oh it's just retar this never becomes true because this is never true for some reason we took over here okay so maybe we do connect that but we don't connect this oh wait whoops that's right forgot a piece two one five okay two one three oh um so we're gonna do diagonals is that right trying to think whether that gives me any issues no i think we just need to do diagonals okay all right let's just write it a different way i'm writing this a little bit weird as well okay slow down now having some trouble today but okay i got it other than the typing i got it gotta double check this because i feel like i spend way too long and already potential for typo two one three okay do you want to try to give it a submit yeah let's go okay so it's silly uh yeah thanks for watching hit the like button hit the subscribe button join me on discord especially if you like these contest problems we talk about problems all the time uh of the contest type but you know come swing by uh let me know what you think i'll see you later to a good weekend to a you know mental health and i'll see you later bye
Last Day Where You Can Still Cross
sorting-the-sentence
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down). Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_. **Example 1:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\] **Output:** 2 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. **Example 2:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 1 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. **Example 3:** **Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\] **Output:** 3 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3. **Constraints:** * `2 <= row, col <= 2 * 104` * `4 <= row * col <= 2 * 104` * `cells.length == row * col` * `1 <= ri <= row` * `1 <= ci <= col` * All the values of `cells` are **unique**.
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
String,Sorting
Easy
2168
234
And listen guys suggest ubuntu in this question that is spelling of list shoulder question is liquid form for single list read through this page for 200 bluetooth subscribe to subscribe now to receive new updates reviews and this subscribe now to the subscribe that I am very Viewers Seem Free Mode Health Specification For That So Simple Message To Do Something From Various Health Benefits Delhi Into To Do Subscribe subscribe to subscribe and subscribe the Channel subscribe our Ka Pyaar Handed Di Service Portion 19 One And This Post No Report Subscribe Now To Subscribe And Subscribe The Channel Please subscribe and subscirbe 100 168 Latest List Notes And You Test People Also Got Them Bluetooth Setting Slow Reason First End Subscribe Not Video then subscribe to subscribe Vivo's Didn't subscribe till running. To-do next Didn't subscribe till running. To-do next Didn't subscribe till running. To-do next in hands of this fast of but to dancers where is from Tamil Nadu. Must subscribe this channel subscribe and subscribe the Video then subscribe to that and you know who travels paste next as loot. Slot Next So Twitter Roop Ki Navi Voter List Declare The Function At Its Function Avoid Subscribe And Subscribe The Amazing Subscribe To Hai Ya Ibadat Initial Ke Test Cases For Your Train The Results Hai Ya Soegi Phase Punjab Police Attend According 600 Editor Online Job School List In Cache Memory Subscribe First Veer Vidmate Download Vidmate Subscribe Spartan The Soviet Fus' Total Bust Report Say Soviet Fus' Total Bust Report Say Soviet Fus' Total Bust Report Say Sacred Heart And Nude Compare Buddha Values ​​Option Notes From Both Sides Values ​​Option Notes From Both Sides Values ​​Option Notes From Both Sides Sudhir And List Vitamin C Several Companies And When Things Indians Like Preaching The Middle Load Washing For subscribe
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
516
so hello coders welcome to my channel and in this video i'll be explaining the problem longest palindromic subsequence so you know this is a fairly simple problem of and what the problem asks is that i have been given a string triple b a b and i have to return the length of the longest palindromic subsequence okay so it is a fairly easy dynamic programming problem and it can be done in many ways but i will be using recursion plus memorization way because that is the easiest way to solve any dp problem so let's understand the problem first so uh in this case for example if the string is double uh sorry uh the string is triple vab okay so let's just let me change the color uh triple b a b so in this case the longest paradromic subsequence length will be four okay and that will be uh four times b okay so first of all let's discuss what a palindrome is so basically what uh what does uh subsequences you know what you guys know already know what a parent room is so in case of a subsequence is a continuous set of characters you and you can skip some characters in between for example this is a subsequence b a b is a subsequence but b a b this kind of thing is not a subsequence so if you are going ahead you always have to go ahead okay so uh to make a palindrome what my approach is going to be is that for example i'm going to use two pointers left and right okay so if i see that my left pointer and right pointer characters are same for example in this case this the first and the last character are same it means that okay whatever my palindrome is going to be like i have two characters that are equal so it means that uh the my palindromes length is going to be at least two okay now the remaining uh problem boils down to the remaining part of the string that uh how uh like what can be the maximum length of this character the other string bba which can be a palindrome okay so in this case you will see that again i will be pointing at the last characters bba and i see that okay the first and the last character is not matching okay so now what i have to do is that okay this cannot be a palindrome these two characters cannot be a part of a palindrome together so what i will do is that okay let's ignore this one for a while and write bb and then another my another choice can be let's ignore this one for a while and see what can be the best palindro uh maximum palindrome that i can get from these two strings okay so in this string i again use my left and the right pointers so my left and the right pointer are matching so it means that it will be at least for this string the at least length will be two okay and then the string will be finished and then i will return two from this string and if i uh pursue this string what will happen is that first and the last characters are not matching okay then what i will do is that okay fair enough now i have to see that what can be the longest palindrome in if i ignore first ignore this character then my remaining string can become b and if i ignore this character my remaining string can become a so you know each character individually is a palindrome for example if i write x the string is equal to x then it is a palindrome of length one okay so here uh since the length of the string is one i will return one from here and one from here out of these two the maximum one is one and now i will again return two okay so what will this two do is it will add on to this two okay so my total length will become four so you know this is the thing so it can easily be done by using recursion okay so let's code it so for what i'm going to do is that i'm going to make two pointers in l is equal to 0 int r is equal to s dot size minus 1 okay now what i will do is that i will return my i will make a function called lps that will return my length so lps will have two parameters s l and r okay so in lps string ampersand s okay string ampersand s in l into r okay so this is a dynamic programming problem you know because like you have choices in this like a recursion tree is forming and all this is happening and plus you have to some do some optimization like you have to find the maximum length okay so whenever these two things come like you have some choices and you have some optimization then it becomes uh you think you should think about dynamic programming so in recursion way uh you have to in any recursive function there are two parts of a recursive function that is the base condition and the choices okay so let's write the base conditions first so uh it as it is clear from this example that the base condition is what either the string can become empty or the string can become of one character okay so if l is greater than r okay so this means that the string is empty so for an empty string i should return 0 and if l is equal to r that means that i have to return one that is that means that the string is of one character now what are my choices so i have two choices so if s l is equal to s r then i uh let's make another variable called int length is equal to zero that will be the length of the palindromic string so length is equal to two plus lps of what s l plus 1 r minus 1 okay so as it is clear so for example in this case in the initial place the l was here and the r was here so the first and the last characters are matching so l will become l plus 1 r will become r minus 1 it means that now the i have to find the lps of this in this part that is bba okay it has become quite messy but here i think it is clear to you and what will happen if else if they are not matching then the length will become maximum of lps of s comma l plus 1 comma r comma lps of s comma l comma r minus 1 and in the end i have to return length you know so it is isn't it super obvious like what i have written here so this will uh give me the code but this will also give me time limit exceeded because you know it is a recursive function and for a recursive function like i am making two choices like per function in the worst case and that will give me a time complexity of 2 raised to power n so to optimize it what i am going to do is like i am going to make a dp table so to make a dp table you have to know how many parameters are changing per recursive call so in this problem you see string is not changing per recursive call but left and right are changing see it is becoming l plus 1 and r minus 1 and n plus 1 and are all sorts of things so let's make a 2d vector so vector of vector int dp okay and now i will assign this dp so dp dot assign sp dot assign looks like hybridization of a carbon atom dp dot assign what s dot size comma vector and s dot size comma minus 1. i am assigning it with -1 minus 1. i am assigning it with -1 minus 1. i am assigning it with -1 because like it will help me track the what sub problems i have solved you know uh once you have written the recursive code uh writing the what writing the uh optimization optimizing it memorization is very easy you have to write only three more lines the first line is the threefold lines the first line is the making the vector the second line is assigning the third line is going to be dpl r so is equal to so what this does is that uh like this table is like a big map okay where l and r are unique coordinates and so that for this unique coordinate you are like putting the what putting the value that this coordinate will give so if you have already solved this problem dplr is not equal to minus 1 then what will happen is that you just return dplr and that's the problem for you guys so you know after writing the recursive code how easy it was to memoize it as compared to the top-down memoize it as compared to the top-down memoize it as compared to the top-down way tabulation way it is 92 percent what is what happens in tabulation is that why i don't like tabulation is because you have to like think about the beginning if you see the discussions uh for example this uh i really post nice solutions so this one is a memoization is very natural you know what is happening but in tabulation you will have to do initialization part like that is that can also be derived from like memorization but you know it's just easier so if you have understood the problem please consider subscribing this channel and thanks and have a nice day
Longest Palindromic Subsequence
longest-palindromic-subsequence
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** s = "bbbab " **Output:** 4 **Explanation:** One possible longest palindromic subsequence is "bbbb ". **Example 2:** **Input:** s = "cbbd " **Output:** 2 **Explanation:** One possible longest palindromic subsequence is "bb ". **Constraints:** * `1 <= s.length <= 1000` * `s` consists only of lowercase English letters.
null
String,Dynamic Programming
Medium
5,647,730,1250,1822,1897,2130
515
hey what's up guys it's Nick white do tech encoding stuff on Google YouTube and I do every LICO problem not a ton of them up on my channel so go check those out if you want to explain to you or just to want to do them and get another everything's in the description too so this one is called fine largest value in each tree row I need a pretty self-explanatory you need to find the self-explanatory you need to find the self-explanatory you need to find the largest value in the each row of a binary tree so if we look we're gonna output an array a list of integers and we're gonna traverse this tree and get the largest value in each row so one would be the largest value because there's only one thing in the row 3 would be the largest value because it's only 3 and 2 and 3 is larger than 2 and then 9 is a large value in the last row because it's five three nine and nine is largest out of those three numbers so to do this it was pretty intuitive after doing about two other tree problems it's kind of just a basic traversal solution so we're gonna declare our output array first western integers we'll call it largest vowels because that's what we're getting the largest values in each row it's gonna be an array list and then we're gonna use a helper method so we're gonna call our helper method you can call whatever you want like DFS or whatever so it's kind of a depth-first whatever so it's kind of a depth-first whatever so it's kind of a depth-first search we're doing here in a way so we're doing a calling our helper method and we're going to pass in the root our array our largest Val's array and then the current level we're gonna keep track of the level as we go through and we're gonna check in the array in their helper method if the element that we put in at the current level is smaller than the element we're taking in I'll explain it a little bit better in a second and then we're gonna return largest Val so our method is gonna update largest Val's so our helper method is gonna be a void method right and it's gonna take in exactly what we said here so tree node our list of integers largest vowels and men are level into level so just like all these other problems if root is equal to no we're just going to return to void method so you've just returned nothing and then here's where we actually do stuff so if the level is equal to largest vowels dot size we're going to just add the roof and why do we do this largest vows add root well this means that we're given we're at a current level so if we were at level two for example and there's only two elements in there should be we're checking to see if there's we haven't even tried to put an element in at the current level yet so if we haven't put an element in the current level even if it's not the maximum element at the current level we're just gonna add anything and if and then it's gonna we're doing all these recursive calls and we're gonna visit every node anyway so if we do already have an element at the current level so this is in the other case then we're going to replace that we're gonna replace that value might not replace it with in set what set does is it takes the current index in the list and sets that value so else we already have a value at that current level and we're going to replace it with the math.max going to replace it with the math.max going to replace it with the math.max between largest vowels dot gets at that level and then root right so we're getting we're checking what's in there already and checking it against the root of this current call and if the roots value is greater we're just going to replace that value so that we have the absolute max really and then we're obviously gonna have to do our recursive calls on the left and right now it's so weird left to the left node here passing it the same stuff and we have to increase the level with each call just like all these other tree muscles it's kind of tough to explain Oakland doing an okay job so this should do everything right there what's a minute no method found for root sorry about that there we go success so yeah basically you have this largest values of integers you have this array of integers and you're doing recursive calls you're traversing every node and then at each level you're adding but you're just adding you're adding first the first node you see at a current level so if we saw two first before three we would just put two into the list and then three is gonna get seen anyway so when we see three we would see the twos already in the list and we would replace it because we would check the max between three and two three is greater than the two so we would just replace it in that list at the current level so and then your distinct remaining will level each time and doing the recursive calls on the left and right node you're visiting every node and you're getting the max at each level it's a pre it's not that bad hopefully you guys can kind of read into it a little more if you didn't understand let me know in the comments if I didn't do that good it didn't feel like I did that good at explaining this wrong but you know I'm trying so thanks for watching I have all these other videos I do a lot better than other ones but thanks for watching and check out the other ones so thanks
Find Largest Value in Each Tree Row
find-largest-value-in-each-tree-row
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**. **Example 1:** **Input:** root = \[1,3,2,5,3,null,9\] **Output:** \[1,3,9\] **Example 2:** **Input:** root = \[1,2,3\] **Output:** \[1,3\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
443
Hello my dear friend compression so what are you going to do in this question i character are will be given you as i need you compressed na ho c are you are going to compress they have given d algorithm so they told date what you need you do it You need you take string s and for d group of consecutive repeating characters in cache greater give if length is one so directly append d character and if length is greater then give what you need do it you need you add date number also ok suppose This is given you as a b c ok so in this ho me ar der 2 ar der ho me b r der ho me kar there you c ar der so like this c need tu store and also c need tu return nine characters ok So suppose date 12 be present every but what see need you do is just inserting dem in d are see need you put 12 ahead separately mens van and you shoot come separately ok and if there is only van character lets say a at date time see you Should not be right A1 Okay it should only be a so these are the small conditions that you need to take care of okay so I hope the problem is clear you are okay so you are going to approach this problem is given you are so basically C need you travel d are ok so you are traveling d are c are going you required tu pointers date it i n k n let's say they are focusing initially on d first position ok and don't told them other kind of extra space so what c Are you going to do C will be just changing D element in D are so first of all you travels what C required while loop OK so WELL I &lt; so WELL I &lt; so WELL I &lt; length of cache OK let SE is equal to D length of characters OK so because They are going to take them in times length of characters so they need you travel know what they are going to do while traversing they need de count of de similar type of elements so on this also what they required one are and also they required One Variable Date Bill Count So Initially Let Se Count Value Is One And Again Every They Are Going To Apply D Condition Will I &lt; L And What They Are Going To Do They Are Condition Will I &lt; L And What They Are Going To Do They Are Condition Will I &lt; L And What They Are Going To Do They Are Going To Compared D Near By Elements It Bill Be Like These Characters Of I = Characters of I plus Characters Of I = Characters of I plus Characters Of I = Characters of I plus one so basically what they have given they are just comparing this tu element supposes tu elements are equals tu what they bill doing first of which they are going tu increase our count by one and they are using di painter so What they bill do they also increase a/1 so initially i baj ate d increase a/1 so initially i baj ate d increase a/1 so initially i baj ate d first location no i bill come d second location ok no again what it bill do it bill check whether d characters are equal and not so every d characters are not equal A and B So It's Coming Out of This Wild Loop So Once It's Coming Out of D Wild Loop No Way Have One More When Which Was Pitting Her and I Paint Her So Basically They Need You Update Consecutive elements are what they need you do they need you update d are so what they are going you do like these cats of k = curse of i like these cats of k = curse of i like these cats of k = curse of i so initially this waluj going you be dmd every once it is dem so Know what they need to move j/1 so j+ = But they need to think of the condition if it is greater Then and if it is greater than 99 so it should be put in separate way so every also what are you going to do are going in condition ok so first of all are you going to write only when d count is greater than that I told you if A1 is there so you are not going to add and right one in D are so if count is greater than one so what are you going to do right like this four C in level of count ok so what It is going you do C are going not going you add directly S is wait C are going you add it today un string ok so C in level of C what C are going you do C are going you append care of J = C so going you append care of J = C so going you append care of J = C so initially And values ​​tu so it will tu add there and then what are you going tu do see are going tu move our k by van ok initially And values ​​tu so it will tu add there and then what are you going tu do see are going tu move our k by van ok van so what are you going a is dan nav se r on de tu it is also done ok now rest of The elements are still at the same position OK so nine what are you going to do you move forward in this are you need to increase i/1 so i plus equals you follow this once increase i/1 so i plus equals you follow this once increase i/1 so i plus equals you follow this once this is completed see when see reach d last Element What you need you do you need you return d length also so what you are going you do also D Conjunctive Elements Are Equal First of all Do Calculate D Count Once This Count Is Dan What C Are Doing C Are First Adding Date Character Than Every C Are Adding Date Number OK And If There Is A Situation Like This B12 So Level Of 12 Bill B IT BILL BE LIKE THIS SO IT BILL TAKE D CHARACTER FIRST ONE BILL BE ADDED AND THEN TU ISE GOING TO BE ADDED SO THERE ARE GOING TO BE ADDED SEPERATELY IN D ARE OK AND DEVAR IS ONE HOW TO SUPPOSE IF D LENGTH IT IS EQUAL TO ONE OK so what you can do is you can directly write like this if length of i bill se if l = 1 what you are of i bill se if l = 1 what you are of i bill se if l = 1 what you are going to do are directly return d length because they don't have to suppose if d element is given a so i told You are not going too right like this one What they would be doing They would be directly returning A and D Length of D Namaste So what is D length one Okay so I hope D Question is clear you D Approach is clear you and Every you can see I have working code and I already tested it's stable it is working absolutely fine so what they have done they have points I am trying to calculate the length for the length is equals you want to see R directly going to retain it then C are using a while loop to travel this thing every C have a count variable D are going to calculate D Similar repetitive consecutive elements once given this first of all C R going to copy D character D c are going tu copy date number once date it dan c are going tu increase i/1 end come d increase i/1 end come d increase i/1 end come d end what c are going tu do c are going tu return d length date is k like this c are going tu solve this Problem And All D Test Cases Are Going To Be Battered So I Hope D Question Is Clear To You Still If You Have Any Kind Of Confusion Do Let Me Know In D Comment Section Thank You
String Compression
string-compression
Given an array of characters `chars`, compress it using the following algorithm: Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: * If the group's length is `1`, append the character to `s`. * Otherwise, append the character followed by the group's length. The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. After you are done **modifying the input array,** return _the new length of the array_. You must write an algorithm that uses only constant extra space. **Example 1:** **Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\] **Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\] **Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ". **Example 2:** **Input:** chars = \[ "a "\] **Output:** Return 1, and the first character of the input array should be: \[ "a "\] **Explanation:** The only group is "a ", which remains uncompressed since it's a single character. **Example 3:** **Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\] **Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\]. **Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ". **Constraints:** * `1 <= chars.length <= 2000` * `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
How do you know if you are at the end of a consecutive group of characters?
Two Pointers,String
Medium
38,271,604,1241
1,247
all right so we are trying out this problem today minimum swaps to make strings equal strings as soon as 2 of equal length consisting of letters X and Y only the task is to make these two strings equal to each other you can swap any two characters that belong to different strings which means slab S1 any index attachment with any intercept of S2 it only minimum number of Subs required foreign let's look at the examples first example is X x and YY okay so x y we want to make these strings equal X and Y are not equal so it's swapping this y with this X and you do that so you get y x and here you got y axle man they become equal interesting so for x y we needed one Swap all right now other example is x y x Okay so x y comma y x so if you look at this X Y by X they are not equal what can we do uh oppose diagonal swaps will just redo the same thing so first thing that's being done is swap a same position so make it y x right so it becomes YY xx and then do another swap then it's sort of similar to this then you do swapping of this so this is X Y so you go X Y so basically the short answer is it required two swaps so X Y comma y x if this was the input you needed two slabs and third is XX comma x y x and x y well this x and x are already equal so just cancel them out and X and Y how many Subs over you do you can't reach so you cannot reach it okay now so there are two questions that comes to mind right one is whether it is possible to make the strings equal and second question is how many Subs are needed right these are two questions so first thing whether it is possible to make the strings equal so would count in the number of X and number Y in each string help in any way one thing that we can look at is we can ignore two characters which are already equal at specific indexes so for example x and then x y x we don't really care about uh this part of the string right so the characters which at the same result which are already equal you can just completely ignore those parts of the strings and then the remaining part would be then at the same index it would be either XX sorry X Y or y x and now so when I say X Y it's this X Y right X and Y vertically or y x now if the number of so basically there will be some count of x y and there will be some count of y x now uh when is it possible well one thing that we have seen is uh maybe both of them have to be equal so count of X Y should be E1 uh amount of y x should be E1 what we have seen here like if you look at just the this string X Y by X you see here uh count of X Y is 1 and counter y x is 1 but overall uh they are not so overall they are not right so it should be count of x y and count of y x either should they should both be odd or they should both be even if they're both even then uh just like uh x y and if you just get another X Y then we already saw from this example that this you can solve so if as many our two of X Y comes they will get salt similar to Y axle gets solved what if uh if there is X Y and Y X that can also get solved but if there is something like uh X x y and then y by X this is not going to be solved because so number of X Y is to number of y x is 1 right so I think the theoretical is not this is correct uh either you draw count of X Y plus y x uh should be given or you can say it can also roughly Translate to either both X Y or y x so n y x are odd or E1 right now second thing is to find how many swaps are needed again I think there are only two cases one is uh one is this case and the other is this case right so and we know that in this case just one swap verbs right uh just but in this case we need two swaps so first we'll try to do all the one Swap and then if number of X Y and Y X are odd then there will be uh one two extra slabs right that's the only thing so here's the thing so you go if X Y and Y X are T1 then you need X Y plus y x um so you want to pairs right so buy two swaps that's all If X Y and Y X are both odd well let's first Define How many pairs are there so pairs would again be X Y plus y x now let's say one and one right one plus one so okay individually so X Y by 2 plus y x by 2 now again here also we could do same because they are even they will come out the same so for similarity this one this plus the swaps the even ones and if because they were both odd one of those odd two things will again make another one plus two and if foreign then not possible right that's a simple solution so let's try and do that so uh first zero is less than length okay yes length has to be equal as well so let's do that as well if S1 Dot length is not equals to dot length you don't care and now here so oops so X Y is y x is also zero so if carrot I is not equal to speed one okay it has only we are interested and then here if S1 Dot carrot I is equals to X then you go so I'll press Plus and it has to be y x right so you know here now thank you if X Y percentile 2 is equals to YX percentile 2. that will show both or even an odd right uh if that's not the case you return minus one else you put on X Y by 2 plus y x by 2 Plus okay so now depending upon U and also X Y percent if it's ordered zero otherwise it's E1 it will be uh one uh times two right before that one here there will be another two so yeah so that's the thing now uh run example just cases and examples Works submit and it works yes it was uh a bit tricky basically it's just math you have to figure out there's only two combinations just xx and x y x this one so happens later in this two swaps is needed it's finding the count of just these and installing it just mathematically all right
Minimum Swaps to Make Strings Equal
decrease-elements-to-make-array-zigzag
You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`. Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so. **Example 1:** **Input:** s1 = "xx ", s2 = "yy " **Output:** 1 **Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ". **Example 2:** **Input:** s1 = "xy ", s2 = "yx " **Output:** 2 **Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ". Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ". Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings. **Example 3:** **Input:** s1 = "xx ", s2 = "xy " **Output:** -1 **Constraints:** * `1 <= s1.length, s2.length <= 1000` * `s1.length == s2.length` * `s1, s2` only contain `'x'` or `'y'`.
Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors.
Array,Greedy
Medium
null
1,857
hey everyone welcome back and let's write some more neat code today so today let's solve the problem largest color value in a directed graph now while this is a hard problem whether you're a beginner or somebody who's been grinding a lot I'm going to show you some steps you can take to solve difficult problems like these and the most important thing especially with this problem is just reading the problem carefully I'm going to go through the prompt at least in a more simplified way because sometimes they try to confuse you with the prompt but the most important thing about this problem in my opinion is all the way at the bottom of the description which I'm not showing here but we're given a string of colors basically we're given a graph here every single node has some color associated with it now this is red this is blue this is purple that doesn't really matter because each color is going to be represented with a lowercase character that's right each color is going to be from lowercase A through Z that means that the number of colors is limited to 26. that's really one of the most important things about this problem that's what you have to catch but for the most part this is like most graph problems we're given a directed graph of n nodes in this case n is not going to be a parameter but we're also given a string called colors which represents the color of every single node so basically in that string the zeroth position might be lowercase a that maps to this node and the first position might be lowercase B that maps to this node so if we can just take the length of the colors array that will give us the number of nodes which is n in this case we're also given the list of edges they're directed there's something special about this but mainly we're going to use that to build our adjacency list because usually when you Traverse a graph you don't want to Traverse it using the list of edges the most common way that we Traverse things is using an adjacency list where we map every single node to its list of neighbors so in this case 0 has two neighbors that it can reach one and two they also describe to us what a path in a graph is as if we don't know that I don't know if they are trying to confuse us here or they just assume that we're stupid but yeah a path is just a path in the graph like this is a path meaning we go from zero to two to three to four we obviously can't go in the reverse order because the edges are directed and they're only going one way in this case now take this path as an example what's the most frequent color in this path well let's say this is a blue we have one blue but we have one two three red nodes so the most frequent color is red and the count of it is three so the only thing we're trying to do in this entire graph is find the path that maximizes the most frequent color so in this entire graph this is the path that maximizes the most frequent color which is red and the frequency is three and in this case that's what we want to return not the color not the length of the entire path or anything but the frequency of the most frequent color which in this case is three there's no path that we can make in this entire graph that will exceed that count now it's possible that a graph could have a cycle like what if we have a graph that looks like this well then we're just going to get stuck in an infinite Loop so they do tell us that in that case we can just go ahead and return negative one because we can't really find a valid path in that case so now we finally understand the problem which I think is the hardest part now I don't know about you but anytime I encounter a graph problem the first thing I try is the depth first search algorithm DFS because it's the most popular algorithm it's the most common so you definitely want to check is that going to lead us to a solution so let's try it out how could we apply depth first search to this problem well in the worst case we might have to look at every single path so how do we run DFS where do we even start it's not like they give us a starting point it's not like we can just start at node zero how do we know we start here why not start over here so I guess in the worst case we'd have to run DFS on every single node isn't that going to be really inefficient because running DFS might cost us the entire size of the graph so o of n let's say is the number of nodes well technically it would be n plus m is the number of edges because we might have to Traverse the entire graph and how many times are we going to do this well maybe times n because we have to run it on every single starting point but is there something smarter that we can do here let's suppose I ran DFS starting from three I found out that starting from here this is the only path that we can really make so starting from three how many blue nodes were there along the path well there was just a single blue note how many red nodes were there well there was just a single red node so you're probably starting to get the idea if you have some experience with leak code problems where I'm going with this but I'll continue for now that was just the path starting at three now let's just say randomly we run DFS starting at two you might think now this DFS in the worst case is again now we might have to again Traverse the entire graph but two only has a single neighbor and it happens to be three so why should we now have to re-run DFS on this we now have to re-run DFS on this we now have to re-run DFS on this portion of the graph we don't need to we already have all that information stored over here so when I'm asking the question starting at two what's the maximum frequency of Blues that we can get what's the maximum frequency of Reds and we also have a third color here purple so I just add that right over here but it's obvious that I don't need to repeat all of this work so what can I do instead well I know that starting at two we do have a single red node so maybe I can just put a one here for now and then I go to my neighbor three I see it's already been visited I'm not gonna run DFS I'm just gonna look at Row three which is going to tell me what's the max frequency of Blues and reds so what I'm gonna do now is look at this position blue now so far let's just say we have zero because starting at two does not have any blues we're gonna see that starting at three we can get a maximum of one blue so since this value is greater than this value we should take this value and move it over here we can uh get rid of this and now we have a one because we know going from two we can get to three and we know this path will have a single blue so that means starting from two there is a path that maximize the number of Blues and that path will lead us to a single blue and we're just gonna go column by column and do the exact same thing for every single color so here it's a little bit different though because we know two actually was the color red so here we're not going to take the maximum of these two values we would actually take this value and add it to the value over here so I'm going to get rid of this and add one to it so now we're going to have a 2 over here and we would do that column by column here they're just going to be zero so we don't really need to do anything but it's not entirely this simple because it's possible that two actually could have had additional neighbors going in other directions as well it doesn't in this case this graph is pretty simple but this could have been the case so what would we have done in that case well let's say another neighbor happened to be four like this neighbor over here is four so just to make it simple we have a four here there's some values here x y z we don't care what they are but again we would go row by row we'd say let's look at these and since remember for every single node we're trying to maximize this position we're trying to find the maximum number of Blues the maximum number of red so what we would do as we go column by column comparing these two values we would take the maximum of both of them the only Edge case here is that on the source node which is two for the column where the source node is the actual color like in this case the source node was red here we would just want to add a plus one so we just have to keep track of that edge case we wouldn't just in this column we wouldn't just take the maximum of these two we would have to kind of consider a plus one but that's the only Edge case otherwise this isn't super crazy and you might think well for each iteration of the DFS if we're having to do these operations if we're having to go through this entire thing isn't that going to lead us to a pretty inefficient solution not quite because remember what I said at the beginning the number of colors is bounded to lowercase a to lowercase C it's bounded to 26 colors maximum so it really isn't that bad and since we're never having to repeatedly visit the same node twice the overall time complexity of our DFS is just going to be the size of the graph n plus M well we do have a factor of 26 but that's a constant value we don't really care about that so this actually will lead us to the most optimal solution at least in terms of Big O time complexity I will mention there is a solution that will get you a better run time on leak code but this still will give you the Big O time complexity which usually is the most important for interviews so I think it's safe to stick with this simple approach and we didn't need anything super fancy all we needed was depth first search I didn't mention though there could be the possibility that we detect cycles and I'll basically talk about how we can do that within the code at a high level as we visit nodes like as we start at zero we go to two we go to three we go to four if we ended up coming back to the same node we'd want a way to track that I'm going to do that using a visit hash set well I think I'm going to call it something else because we're going to have visit to not repeatedly visit the same node twice but we're also going to have another hash set maybe I'm going to call it path to tell us what are the nodes in the current path of our recursive DFS like what are the nodes on the call stack of this DFS so now let's code this up so I'm going to start with just building the adjacency list this is not super complicated so I'm just going to have that here we're basically creating a hash map where the default value of the hashmap will be a list slash an array we're going to go through every Edge and we're going to map The Source node to the destination node we're also going to have a depth first search and what we want this DFS to do is given in some node as a parameter we want it to return the max frequency of the most frequent color so that's ultimately what we want this to do now I'm not going to fill it in yet because I usually think it's better to see how we can use it before so that's what I'm going to do we know we're going to go through every single node and try to run a DFS starting from that node well first of all how many nodes do we have well thankfully we can get that by taking the length of the colors array so then I can complete my for Loop for i n range n and then pass in that starting node into our DFS now what we're trying to do is maximize the result so I'm going to well first declare that variable result is initially let's just say is going to be set to zero that's usually a good default value and we want to maximize the results so we're always going to take the maximum of the result of this DFS and the maximum of the result and set it equal to the result now like I said we are going to need to keep track of which nodes have already been visited so that we don't do repeated work and we're also going to keep track of which nodes are in our current path of our current DFS like which nodes have been pushed onto the call stack because that will help us detect Cycles while it's required for us to detect Cycles so these are both going to be hash sets so we can do that just like this and this is kind of the complicated part I didn't explicitly talk about it but I kind of showed it with the picture we are going to have a two-dimensional grid which to have a two-dimensional grid which to have a two-dimensional grid which tells us the max count where we are mapping the count the node and the color to the max frequency of that color starting from this node so just like we talked about in the drawing explanation now to actually initialize this 2D grid well I'm going to do it the pretty much pythonic way you can do it however you would like but we know that every row is going to be the number of colors so the row is going to be 26 because we could have up to 26 colors so it's going to be an array with 26 zeros that's how you can do it in Python and how many rows are we going to have well one for every single color so I'm going to say for I in range n which we calculated up here so this is just a two-dimensional grid so this is just a two-dimensional grid so this is just a two-dimensional grid pretty much with these dimensions and this is going to be useful for us in our DFS now lastly I'm going to put our return result here we are going to modify this I'll mention that now but I'm going to save it until we finish up our DFS because remember we want to return negative one if we detect a cycle so we'll have to keep that in mind but now let's go on to the DFS there's a couple edge cases if the node is already been visited then we just want to return immediately I'll just return zero because it doesn't really matter there's also so the other Edge case if the node is in the current path then we want to indicate that we've detected a cycle so we have to return some special value here we could do negative one but the reason I'm gonna do something different I'm going to do flow Infinity basically like the maximum value that we can return the reason I'm doing this is it makes our code a bit more concise you can do it the negative one way but you'll find that you need like a couple extra lines of code doing it this way when we take the maximum because that's ultimately what we're trying to do we're trying to maximize this if we ever return Infinity from this DFS we're going to take the maximum and then our result will be infinity and once it's Infinity it can never become smaller than that so then by the time we get to this return statement we will be able to detect is the value Infinity if it is what we really want to return is negative one so I'm going to do exactly that return negative one if result is equal to float Infinity else return the real result whatever it happens to be it's probably zero or some positive value but it's not Infinity now one thing that you might not notice here is we kind of have a bug here because every time we get a node that's not been visited and is not in the current path what we're going to do then is add it to the visit hash set so we're going to say this node has been visited and this node now is in the current path so now if we visit that same node again then we're going to end up executing one of these but notice if the node is in the current path it's also been visited so if we get a node that's already been in the current path what we'd want to do is return Infinity to indicate we detected a cycle but that would never happen because we would always execute this one first so it's very important that you take this condition and have it before this condition that's an easy way to have a bug so definitely something to keep in mind now for the kind of interesting part we want to take the count the maximum frequency color starting at this node and just set it and for the color of this node we want to set it equal to one because we know at the very least this node is some color and we can find that color and map it to one initially how do we get that color well that's where our colors string comes in we can take this node and map it to get the color of it but remember that string will return us a character what we want is an index so from lowercase A to Z we really want to map a to zero we want to map B to 1 and we want to map Z probably to 2 25 so how do we do this well I'm gonna do that like this I'm gonna basically call it the color index and I'm gonna get the ASCII value of that color basically mapping that color to some integer and subtracting the ASCII value of lowercase a so if the color of that node is lowercase a this will evaluate to zero if the color of that node is lowercase b this will evaluate to one so pretty much what we were looking for then I can use this color index to use it as an index of this two-dimensional array now of this two-dimensional array now of this two-dimensional array now finally we want to start going through the neighbors of our current node so we can get our adjacency list that's what we built this for and use the current node and get all of the neighbors of this node so while I haven't done anything super crazy you can see that this is quite a lot of code it's a lot of things to keep track of it's really easy to make a bug here that's what makes this a hard problem in my opinion but for every node we just want to run a DFS on it now the only Edge case we have to worry about is what if it returns Infinity because if it does then we should probably just return Infinity right away and that's what we're going to do we're going to detect the return value of this is it equal to float Infinity if it is we're going to return float Infinity now I didn't store the return value in a variable because we actually don't need it in this case because whatever the DFS did the most important thing is that it populated our two-dimensional count array so we don't two-dimensional count array so we don't two-dimensional count array so we don't need the return value we just need the count array so now I'm finally going to do the thing that I talked about where we go column by column and how many columns do we have 26 one for each color so I'm going to say for C which basically stands for color or column whatever you think whatever you prefer I guess but there's going to be 26 of them so we're going to iterate 26 times we want to take the maximum of the count for the current node like the starting node which was the parameter of this function for the current color so this will give us that count and we want to maximize it with the neighbor so the neighbor here with the same exact color we want to find the maximum of these two values and we want to assign it to this position just like we talked about in the drawing explanation because right now we're considering this node as the starting point now the only Edge case is which again I mentioned in the drawing explanation is when we get to the color which is the same color as this color like as the same color as the starting node here in that case we would want to add a plus one we want to add a plus one to the neighbor's path because the neighbor has not considered this node yet so here we'd want to add a plus one what's the easiest way to do that well in my opinion to add like a ternary operator so here what I'm going to do is say this is going to be one if C is equal to color index otherwise it's going to be zero that's the most readable way in my opinion you can definitely try other things but I prefer this because we don't need to create more and more variables because the more variables you create the more names you have to create and in my opinion what makes code confusing to read is bad names and I'm pretty good at creating bad names so I try to minimize that now this Loop will find the maximum for every single color starting at this node and then that's what we want to return so starting at this node we want to find the maximum frequency of any color so we don't care which color we just want to find the maximum so this is an array we can just take the maximum of it and return that so then this method will do what we want it to do the only thing that you don't want to forget about is when you add a node to the current path right before you return you want to clean up you want to remove that same node from the current path we can do that just like this we don't need to remove that node from the visit hash set because we never want to visit the same node twice we also don't want to add the same node to pass twice but it's important for us to pop because then we can actually detect Cycles so that is pretty much the entire code it's quite a lot of it so hopefully I don't have any bugs let's run the code to confirm and as you can see it does work according to leak code's runtime it's not super efficient though the Big O time complexity is definitely optimal I can guarantee you that there just happens to be some other there just happens to be other solutions to this problem that happen to get a better run time on leak code but I don't think that's super important if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Largest Color Value in a Directed Graph
largest-color-value-in-a-directed-graph
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`. A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path. Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_. **Example 1:** **Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\] **Output:** 3 **Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`. **Example 2:** **Input:** colors = "a ", edges = \[\[0,0\]\] **Output:** -1 **Explanation:** There is a cycle from 0 to 0. **Constraints:** * `n == colors.length` * `m == edges.length` * `1 <= n <= 105` * `0 <= m <= 105` * `colors` consists of lowercase English letters. * `0 <= aj, bj < n`
null
null
Hard
null
509
what's up guys disease elite called 509 people 19 number if you wanna a numbers commonly denoted F of n form a sequence called the Fibonacci sequence such that each number is the sum of the two preceding ones starting from zero and one that is f of 0 is equals to 0 F of 1 is equals to 1 f of n is equals to f of n minus 1 plus F of n minus 2 for N greater than 1 given n calculate f of n ok so I think we can solve this using recursion but using recursion 1 gonna be the best solution for this problem because using recursion here we are gonna have a kind of recursion called tree recursion which is pretty slow because we and then we're gonna have a tree in our stack I can show you this by drawing but the first solution we're gonna have will beat the tree recursion using recursion and after that we can improve the solution using just a I think two variables were gonna solve the solution for you're gonna solve this problem for us so let's try to write some code to see how these we're gonna work ok so as a recruiter we can start by checking our edge cases so here our edge case will be when n is equal to 0 we can just return 0 and when n is equals or less than 2 we can return what it's less or equal than 2 we can return 1 and after that we can do our recursion case which will be a fib of n minus 1 let's leave all and - choke and that's let's leave all and - choke and that's let's leave all and - choke and that's the recursion here I can try to run the code to see if it works yes it works and I can show you why this is pretty slow let's see here so imagine we have here the number 5 and we want to see the Fibonacci sequence here for this number are editable not number for these and input we are gonna have to calculate the Fibonacci of n minus 1 which is 4 plus the Fibonacci number of n minus 2 which is 3 to get the Fibonacci number of 4 we have to calculate the Fibonacci number of 4 minus 1 which is 3 and if it were not number of 4 minus 2 which is 2 here we have to calculate the Fibonacci number of 3 which is the Fibonacci number of 3 minus 1 which is 2 and the Fibonacci number did you know of 3 minus 2 which is 1 and here in the case of 2 1 &amp; 2 we are gonna get the case of 2 1 &amp; 2 we are gonna get the case of 2 1 &amp; 2 we are gonna get the result of our base cases but here again we have to calculate the Fibonacci number of n minus 1 which is 2 and if one odd number of n minus 2 which is 1 and here you can see in days in this paint here that there are a lot of duplicate computations because we have here 3 twice we have to appear in 3 times we have 1 twice and this is with a small number which is 5 here imagine if we have a bigger number we will have a pretty big tree and all these here will be in this tank with millions memory and also with and also we increase the real time let's day of dissolution time complexity of this solution is exponential is and is actually change at the end this is not true this is quadratic and this is exponential so it the time complexity will increase compared it to increase explanation base it on the length of the input so if the input gets bigger the time complexity will get exponential bigger so it this is not wilt we can prove the solution here by removing the tree recursion and the thing is in night relative way we can do this by saving the current and the last computation into two variables and use them to the next computations so here we can have a last variable which will have by now two and one to the last which will have one why the last here gets the number two because we already calculate here the base case for the number zero the number one and the number two and the next solution the next result here for your very number imagine a number three for example I think we have the example here yes for the number three we will get the output 2 so we are right now we are we have to do this computation so if n is 0 we are gonna return to here because we already did the previous calculation and we put the number one here in the case of n is greater than 0 because we are gonna have to compute the left parable flows the one to the last variable okay so first thing we have to do here is to decrement 3 of n because as I said before we already did these competition for an equal stream here and if n get 0 austerity is decrement I just want to return the result here in the last parable and if n is greater than 0 we can start our calculations here io n is greater than 0 we can okay so we're gonna have a and updater variable here to say the value of the last right now because we are gonna need the last the following to be above last variable to put into one to the last in the next computation and right now I wanna just calculate last blows one to the last I want to swap day one to the last one to the list to get the videos last which is in the ocular purple right now and I also want to decrement n and yes that's it here we are doing the same thing as we did before we are calculating the next Fibonacci number by the sum of the last and the one to the last value II so let's try to run the code let's write to hit submit yes that's it so this solution is pretty better is much better than the previous one because here we have a time complexity of Big O of n where n is the length of n here and the memory complexity here is constant because it does not matter is n gets bigger the amount of memory that we are gonna allow pay will be just the variables that we are using here so that's it guys thanks for watching
Fibonacci Number
inorder-successor-in-bst-ii
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given `n`, calculate `F(n)`. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. **Example 2:** **Input:** n = 3 **Output:** 2 **Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. **Example 3:** **Input:** n = 4 **Output:** 3 **Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. **Constraints:** * `0 <= n <= 30`
null
Tree,Binary Search Tree,Binary Tree
Medium
285
415
welcome to august eco challenge today's problem is add strings given two non-negative integers num1 and given two non-negative integers num1 and given two non-negative integers num1 and num2 represented as string return the sum of num1 and num2 as a string you must solve the problem without using any built-in library for handling large any built-in library for handling large any built-in library for handling large integers you must also not convert the inputs to integers directly so unfortunately we can't just use the integer function if we could do that all we have to do is say convert integer num1 num2 and literally return this as a string right and this would be accepted but it's not valid this wouldn't work so what else can we do other than using this integer function well really there's not very many options is there one thing that we could use though is the ordinal function now what this does is uh gives us the integer representation of a unix character so number one would be represented as 49 i believe and number two represented as 50 so on and so forth so maybe we can do that maybe we can use this ordinal function instead and just do a basic arithmetic adding the first or i should say last digit first and then see if there's anything carry over if there is we'll pass in one and then we'll continue that forward so let's go with that uh let's say we'll first initialize n m to be the length of num1 and the length of them two next we need uh a and b representations and these will just be starting with zero and we also need a carryover which is going to call carry here so let's see while okay this isn't zero i'm sorry a and b is going to be represented as n minus one and m minus one and this will tell us where we are inside of our position since the length of these might not be the same we'll have to have some if statements here so let's see while a is greater or equal to zero at or b is greater equal to zero let's do a loop and we're going to first calculate our inj which is going to be the integer for the first number and the integer for second number so if a is greater or equal to 0 let's actually first initialize i and j here as zeros and we'll say if it's greater or equal to zero let's take our ordinal of num1 and this is a string right so we're going to get a and we'll subtract 48 here this is going to give us the integer function of this character or sorry the integer representation of this number so basically 1 will equal 1 2 equal 2 so on and so forth and make sure to decrease our a here now b if it's greater than 0 we'll do the same thing here num2 b minus 48 and then b minus equal one so now let's create our temp variable we'll say temp equals i plus j but we also need to add our carryover right and right now at the very beginning we know carry is going to be zero but if the let's see if the string representation of i should i don't even think i'll just say if temp is greater than nine then carry is gonna equal one and otherwise carry is still equal to zero now what we do let's have our output this is going to be an empty string at first and we're just going to add or we'll recreate our output say let's see we'll take our temp we'll take the string representation of our temp this might be two length of two so we want to take the last character here either zero or one and we're going to add that to our output this and then just continue that forward finally we turn our output make sure that at this point we might still have a carry so i say uh let's see actually do we need to do that if carry then we will say outputs equals one plus like this okay and this should work let's see if this works oh okay um 10 equals i plus j oh i have to of course i've set my inj here oops okay so this looks like it's working let's go submit that and there we go accepted so time complexity wise and what's it going to be i suppose it's going to be uh n plus m or whatever is graded of n plus m um although this part here because we keep doing that each time actually might end up becoming a m squared but you know luckily i don't think the length of this well um yeah you know what i'm not totally sure uh there probably is ways to make this a little bit faster than just concatenating strings like this but it does get accepted so we'll just call it a day and because i think this is a very stupid question frankly but it works so let's go with this alright thanks for watching my channel remember do not trust me i know nothing
Add Strings
add-strings
Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_. You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly. **Example 1:** **Input:** num1 = "11 ", num2 = "123 " **Output:** "134 " **Example 2:** **Input:** num1 = "456 ", num2 = "77 " **Output:** "533 " **Example 3:** **Input:** num1 = "0 ", num2 = "0 " **Output:** "0 " **Constraints:** * `1 <= num1.length, num2.length <= 104` * `num1` and `num2` consist of only digits. * `num1` and `num2` don't have any leading zeros except for the zero itself.
null
Math,String,Simulation
Easy
2,43,1031
1,287
hello so today while doing this contest number be weekly contest number 15 the first problem is elements appearing more than 25% of the time and the problems in than 25% of the time and the problems in than 25% of the time and the problems in a sorted array and the problem says we get an array that is sorted in non decreasing order so in increasing order essentially and there is exactly only one integer in that array that occurs more than 25% of the time and we wanna more than 25% of the time and we wanna more than 25% of the time and we wanna return it and so here if we look we have two occurs two times one okay just once six appears four times and the others appear only once and so obviously the answer is six because it occurs four times we have an array that is like four eight nine elements and so four is definitely more than 25% of nine and so definitely more than 25% of nine and so definitely more than 25% of nine and so that's the solution so let's see how we can solve this problem here so the first thing that comes to mind for me is that well we could just if you look at who could just keep a counter of the occurrences of each element right and then go through the values of the counters and see which one is more than 25% which means basically is more than 25% which means basically is more than 25% which means basically is more than the length of the array divided by four right so that's a very simple solution that we can do and in order to do that one we just need to have a map maybe right so something like a count right which let's just do collections that default dict why am i doing this and here so that if the valued wasn't yet added to the array to the map then it has and we add it has by default value 0 it won't return that the key if we do not count X and X haven't been added yet like if we do this and X hasn't been added yet we won't get a problem because this will be considered zero and so we'll just put because this one is equal to this so this count X wouldn't be considered that the key doesn't exist but instead to be considered having value one so that's why we use this here and you'll see that we will do this operation to add one later and so for this we need time for the collections and we need to here just go through the array right and then say that count of a is increased by one and now that we did that we need to check the one that occurs more than 25 percent of the time which is more than the length of the array divided by four so check for key and value or maybe you can just we want to return the key right so wanna return the key right and so and we want to check the value so that would be in count and we'll check just if the value is bigger than and divided by four at that point you can just return you just need to handle the case where an equal to zero in that case equal to one and in that case we can just return the first element of the array because that's the only element that exists right for the case where the array length is only one because here in the boundaries we can see that the array length can be less than one but it can be one right so here getting items okay so we don't have any so let's just go find it here so and it's the length of get ready okay so that passes now let's just try one test case which is this one to make sure it works for one element which is the edge case there okay that passes okay so now what we can do actually because in Python we have this thing called counter right so if I have the array here and if I do counter it just give me element and how many times it occurs and additionally that counter if I say this is equal to C it has a method called most common that returns you the most common element and since we know that there is only one element that is more than 25% that means that the most more than 25% that means that the most more than 25% that means that the most common element that's what we are looking for that's the element that who gives more than 25% of the time and so gives more than 25% of the time and so gives more than 25% of the time and so we could just get the most popular the most common element or the element that exists the most using this method and from there we want to get the numbers I want to get this key here and to get that first we have to get the outside the value in here because it's inside the list and so we get our value and next we get this value 6 which is in position 0 in this topple here and so we can just return that and now we get 6 and so essentially what we are doing instead here of all of this is we can just return and what is see is just the counter for the array right and we can even do this more in one line by removing this here and putting this like this okay so now there is a problem it seems here so we need to impart it so from collections we want to import counter right and we're going to run that and I think we can submit now and we can see that it passes so another method with which we can solve this is that so if it appears more than 25% right that means that there is than 25% right that means that there is than 25% right that means that there is a quarter of the array where there is only that element right and so that's what who will be try okay so to do that first we need a couple of things so just n is the length of the array what is the quarter of the array that's just n divided by four that's the position of it and after that wall we need to just try all possible positions that will give us a quarter because what we are interested in is just checking an entire quarter and so we will check if the array at that position is equal to the array at I plus Q so that it can form a quarter right so I plus Q will give you I plus Q plus one elements right because of the indexing for example if we start from zero and the Q is equal to two we will have 0 1 and 2 which are essentially three elements so it's more than quarter by one which is what we are looking for here and so if that's the case that means since this is sorted that means that every element between I and I plus Q is the same so that means we found the element we are looking for so we could just return it right otherwise we didn't find it continue searching and here just for the case where an equal to one is just written zero okay I'll submit okay so that passes so another solution that we can do that is pretty clever is using binary search so what we can do is okay let's just start from every quarter position which are and which are basically so start from quarter position essentially which are basically we know these they are n divided by four and like this and / and divided by four and like this and / and divided by four and like this and / and / to choose another quarter from n / to choose another quarter from n / to choose another quarter from n divided by 4 to n divided by 2 and then 3 and divide by 2 and then and order the last one we don't need to mention because it starts from here and ends at the end ok so what we can do here is that for each one because we what we are looking for is more than or equal to 24 percent so that element is in a run of the same element that passes by either n divided by 4 or passes by n divided by 2 or passes by 3 and divide by 2 right and so to do that so we could just go through these positions basically and so we have n divided by 4 and divided by 2 + 3 + / - right + 3 + / - right + 3 + / - right now if once we do this what we do is we look for the first occurrence of so lastly say this is I we will look for the first occurrence of III and we look for its last occurrence right and that will give us the range of the like for 6 it will give us these because we will find that the first occurrence is so we'll find that the first occurrence is this 6 here and we'll find that the last occurrence is this 6 here so we know that the size is anything in between same thing for this run of 2 values find that the first occurrence is this the sound occurs with the last second or last occurrence is that and we can just return it and we can do this with binary search because the array is sorted and that was our hint here by saying that the array is sorted and once we find these two source for the start unless for this end we can just check how many elements of value array I exist by doing and - start right and if that is bigger and - start right and if that is bigger and - start right and if that is bigger than n divided by four that means we have more the element occurs more than 25% of the time and we can just return 25% of the time and we can just return 25% of the time and we can just return its value right and so to do the first occurrence in Python you can just use a module called bisect right so if I use this array here that we have here and import bisect and do bisect left on the array and search for the value six it will give me the first occurrence of six which should be zero one two three it should be three right so it gives me three now to find the last occurrence which is 3 4 5 6 so 6 is the last one but to get the one before that it's 7 right so if I do bisect for array at position 6 I get just the element after the last one and so now here I know how to get these how to get the first occurrence and the last so I can just say start is equal to bisector bicyclist to get to the first occurrence and the element is just the one at the quarter position so it's array I so this is the first occurrence and after that we have end here which is the last one so last occurrence right and now to get the range and see if it's big enough or we can just - end - star and check if that can just - end - star and check if that can just - end - star and check if that is bigger than 25% by checking if it is bigger than 25% by checking if it is bigger than 25% by checking if it divides and by for and if it is that means that we found the ailment so we can just return it otherwise just keep going and at the end here just to be safe I'm going to written the first element if we didn't find anything okay so we're on this okay so it's one here so there is a problem because probably because of this okay yeah the problem is this it's actually three and divided by four so it's not arranged it's actually just these values that's what we are looking for okay so this looks good right so does it man okay cool so that passes so with binary search by finding the taking each quarter position finding the first occurrence of that value and the last occurrence and saying if that's more than and divided by four which means we have a solution right so the other method we can solve this with is sliding-window technique right which is sliding-window technique right which is sliding-window technique right which first it doesn't look like it will solve it but it can because what you can do is essentially put first lo at the first position right so what we can do is just first put lo here at this position and put high in position of basically just the one after the quarter position right basically the quarter of this is just these two right but we want to put high here I'll show you why in a moment and so put hi here because why do we do that because we want the element to be more than so strictly more than it can be equal to if we put it high here then equal is counted and we don't want that and so that's why we put high here and we check both if they are different that means that's definitely that the element we are looking for and we can just continue looking if they are equal though that means we have a run like this where we have let's say here where low would be let's say here and high here that's more than the so that's smaller than n divided by four and so that means that we found the element right so that's what we are going to apply here and so the way we are going to say it is that low and high the first one is zero the second one is just the position after thee the one that completes the quarter and so what we say is and divide by four right and then while they haven't that this is how sliding-window usually work is while how sliding-window usually work is while how sliding-window usually work is while they happen to the two pointers haven't met we keep doing something so we check first if the both ends of this sliding window are different what should happen so if they are different that means we didn't find anything so we need to move the window so we know that this one and this one is different are different so we need to move the window so we move both like this right and we check so why I why did I move high because if I don't move high and just move low that means that my window became equal to the size of 25% of the array which to the size of 25% of the array which to the size of 25% of the array which won't helped me because what I'm looking for is occurrence more than 25% and why for is occurrence more than 25% and why for is occurrence more than 25% and why am i moving low because I know low is no longer working since I know that it's different than the value at high and so I try another window so here if they are different I need to advance both pointers and so do lo plus one and high plus one right because they are both moving forward now otherwise that means that both are equal so that means I found a window of size more than 25% that contains only the more than 25% that contains only the more than 25% that contains only the same element so I could just return that and to do that I'm just going to break from the array and at the end no matter what is the reason we exited we can just return the array at position lower right and that's pretty much it for the pointer technique one so there is an involved here I am missing this okay so that looks good what's the matter okay so that passes so you can see here we could also solve it with this simple sliding window technique so we saw how to solve this with one with a hash a simple map another one with the counter data structure that Python has and then another solution using just a simple advancing of quarter after quarter which is basically just a linear scan which has the same time complexity as the solution before it and then after that we looked at one using binary search and now one using sliding-window the one using binary sliding-window the one using binary sliding-window the one using binary search is just all like N or fly again and this one however is actually over and divided by I think four I think yeah but essentially yes so those are the type of solution that we have here thanks for watching and see you next time bye
Element Appearing More Than 25% In Sorted Array
distance-between-bus-stops
Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. **Example 1:** **Input:** arr = \[1,2,2,6,6,6,6,7,10\] **Output:** 6 **Example 2:** **Input:** arr = \[1,1\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 105`
Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.
Array
Easy
null
76
a new video in today's video we're going to look at leite code problem and the problem's name is minimum window substring so in this question we are given two strings s and t which are having length M and N respectively and we have to return the minimum window substring of s such that every character int including duplicates is included in the window if there is no such substring we have to return an empty string as the output and the test case are generated such that the answer is unique it means there will be only one final answer so let's take a look at these examples and see how we can solve this question so let's take these examples so first we can identify H case that if the length of T is greater than the length of s we can return the empty string because we have to calculate minimum window substring of s such that every character is T is present inside that window so T should be present inside s but in this case it's not possible so we return our empty string now let's take the first example I've written the same string here so here you can see the keyword that we have to find a substring and you have to compare many substrings so a Brute Force approach would be that you can calculate all the substring such that every character in present inside the string T is present inside the substring so for example here is one substring which has all the characters a b c inside it so I'm just identifying the optimal ones so here is one substring and here is one substring so Brute Force approach would be you find the substrings from all the IND AIS until the end and then you start from here and then you compare if the characters of te are present inside the substrings and you maintain a minimum variable and you keep updating that and return the subring which has the minimum length that would not be feasible if the string has many characters inside it since we are going to form substrings we are going to use a two-pointer approach going to use a two-pointer approach going to use a two-pointer approach using sliding window and this sliding window won't be of having fixed length because we need to compare it with another string so until all the strings are present inside the window we keep on moving the right pointer so we start with two pointers I need two pointers left and right both of them are going to start from zero index and we need to keep track of the number of variables we need to find right so I need a variable to find which is initially equal to the length of the string T which is equal to 3 so we need to find three characters and we need another variable which I'm going to uh name as found which is initially zero because we haven't found any of these three characters yet so once you find this three characters it keeps on incrementing by one and once both of them are equal then you can find a substring so that is the main idea so first I need to find how many characters of each character I need to find so I need a character added to find the characters frequency inside the string the so I create an array which will be of the length 128 because I'm going to use all the aski characters until 128 because small s starts from 97 and capital S starts from 65 so 97 Plus + 26 capital S starts from 65 so 97 Plus + 26 capital S starts from 65 so 97 Plus + 26 is equal to so this is 123 but I'm taking until 128 because the asky characters this will be easier so you can also take 256 that is the entire set of the aski characters but 128 will be enough so I created a character array of length 128 which represents the characters present inside so we start off by iterating through the string T and this will have8 length right for this particular string I only noted the characters which are present in string s capital A will start from 65 and it will go until capital Z and small a will start from 97 until 123 this is the size of the array and I didn't draw the entire array so I iterate through the characters and keep incrementing its count then I get a B increment it count and I get a c and rest of all will be zeros now left and right will start from here left and right will start from zero index and right will move until the end so like I said we need to first form the substring using these two pointers until we find all the characters needed so until these both are going to be equal we keep incrementing a right pointer so first CH is at a we check if a is needed yes a is needed how are we going to check if the value of that inside this array is greater than or equal to zero then we can say that is needed so we found one of the variables so increment the found by one so increment found by one now found is equal to 1 and decrement its count because we already access that so this will become zero now right will move forward now CH is equal to D decrement it value by 1 it was Z it will become minus one because it is not found anywhere and this condition we have to check and it is not being satisfied because the current count is not greater than equal to zero so it is not a useful character so found will be remaining as one now right will move forward again the character is O decrement is count by one so this condition is not satisfying again so we move forward now we are at B get its count it is satisfying this condition so increment found by one now found is equal to two so we found this and since we found B we decrement the value by one so this will become zero now right will move forward it is at e decrement its value by one so e will become minus one and this condition is failing because the value is equal to minus1 so it's not a useful character so found will remain same now we are at C decrement its value because we found it so it will become zero now this condition is satisfying because the value is greater than equal to Z so we found a character which is useful so found will become equal to three now as soon as two find and found is equal to three it means we have find all the characters inside T inside the current window so this is the current window and what is the length of the current window L is equal to Z and right is equal to five so I create a variable called M Window length which will keep on updating and keep track of the minimum window length and it is equal to the integer. max value 2^ 31 - 1 and now integer. max value 2^ 31 - 1 and now integer. max value 2^ 31 - 1 and now calculate the current length is equal to right minus left 5 - length is equal to right minus left 5 - length is equal to right minus left 5 - 0 + 1 because of the index position so 0 + 1 because of the index position so 0 + 1 because of the index position so equal to 6 so update the Min window length by six so you compare that with the current max value and since this is minimum this is six and what is the String we get until now we take the substring from left until right + one substring from left until right + one substring from left until right + one because in the substring method this character won't be implemented if you take only substring of left comma right you have to take left comma right + one you have to take left comma right + one you have to take left comma right + one so character also at right will be included inside the substring so take that and store it inside a variable I'm going to name it result so result is equal to this string now we have to keep moving our left index also right so before moving our left index we have to check if this is a useful character it is a useful character if it is present inside the t count yes it is present so this value will be incremented by one so if t count of s do karat of left so if this value is greater than zero then we decrement found because if we move our left pointer from here to here the string this will be removed and we need a valid character a to form a substring so that is why we reset back this to one by incrementing it by one and decrement found so found will become two because a we haven't found yet in the current window now both three is not equal to two so we need to increment a right pointer now so this is the right pointer CH is at o left is at 1 and right is at 6 now decrement the value of o it is min-1 it will become min-2 because we min-1 it will become min-2 because we min-1 it will become min-2 because we encountered two o's so o started with zero and since we encountered 2 O's it will be decremented two times so it is having the value minus 2 now both are not equal yet so we move right pointer forward now the character is D decrement its value so this will become min-2 and its value so this will become min-2 and its value so this will become min-2 and check if this condition is satisfying no so found is still not equal to 2 find so we move our right pointer the character is e decrement its count it will become minus 2 check if this is satisfying no still this is not equal now move forward we are at B now check B's count since we visited that it will become minus one and check if this condition is satisfying no it's not satisfying and this condition still satisfies so we keep moving forward we need another a to make these both equal so now we found a decrement its count first 1 will become zero now check if this condition is satisfying yes it is satisfying so found will be incremented by one so found will become back to three now both of them are equal now we can calculate our minimum window again because our minimum window is between left and right so calculate the length right is at 10 left is at 1 10 - 1 + 1 is = 10 check if left is at 1 10 - 1 + 1 is = 10 check if left is at 1 10 - 1 + 1 is = 10 check if it is less than the 6 no 6 is still the minimum substring so minimum window length is string and result will still be this now we can move our left pointer but before moving our left pointer we have to increment its dount by one right so if you add 1 to - 2 it will become so if you add 1 to - 2 it will become so if you add 1 to - 2 it will become min-1 and we have to check if this is a min-1 and we have to check if this is a min-1 and we have to check if this is a useful character it is useful if it is present inside the string T it's not present so these values will still remain the same as 3 and now we can move our left pointer now calculate the length again 10 - 2 + 1 is equal to 9 length again 10 - 2 + 1 is equal to 9 length again 10 - 2 + 1 is equal to 9 check if 9 is less than the current value 6 no so 6 will remain the same and now we can move our left pointer so this value will be incremented from -2 to -1 value will be incremented from -2 to -1 value will be incremented from -2 to -1 and now we have to check if O is a useful character no it's not useful so these values will still remain the same now left is pointing at B calculate the length 10 - 3 + 1 is equal to 8 the length 10 - 3 + 1 is equal to 8 the length 10 - 3 + 1 is equal to 8 check if 8 is less than the current 6 no so 6 will remain same uh we increment our B's value will go back to zero now the value of b is z but it is not greater than Z so found won't be decremented and these both values are still the same and now we can increment our left pointer so left is having the value 4 calculate the length 10 - 4 + 1 value 4 calculate the length 10 - 4 + 1 value 4 calculate the length 10 - 4 + 1 is equal to 7 check if 7 is less than the current value 6 no and now we increment the value of e because we moving the left pointer and now we are checking if this value is greater than zero no it's not so it's not a useful character so we move left so left is having the value five calculate the length so 10 - 5 + 1 is equal to 6 check length so 10 - 5 + 1 is equal to 6 check length so 10 - 5 + 1 is equal to 6 check if this 6 is less than 6 they're both the same so it won't be updated and now increment the value at of C so c will be incremented by one and now we check if this value is greater than zero yes so we decrement found so found will be decremented by one and found will become two because it's a useful character and if we remove this character and if left moves forward now this will be our substring the substring is o d e b a and this substring does not have C but we need c that is why found will become now these both are not equal so we move a right pointer now so right is pointing at n and decrement the value of n because we access that it will become - because we access that it will become - because we access that it will become - 1 and check if this value is greater than equal to Z no so it is not a useful character as the N is not present inside ABC so found won't be incremented and still they're not equal now right moves forward and the character is at C decrement C's value by one because we access that so c will become back to zero and now check if this 0 is greater than equal to Z yes this condition is satisfying so increment found so found will be incremented from 2 to 3 and now two find and found will become equal now we can calculate our length so here you can see C got removed and C got added now from left to right the uh length is so left is at 6 and right is at 12 so 12 - 6 + 1 is equal to 7 check if 7 is less - 6 + 1 is equal to 7 check if 7 is less - 6 + 1 is equal to 7 check if 7 is less than six no so six will still remain the same and now we have to move our left pointer right but before moving we increment this value by 1 so o will be incremented by 1 o will become zero now we have to check if o is greater than zero no so found won't be decremented and found will remain the same and now we can move our left pointer so left is now at D so calculate the value so 12 - now at D so calculate the value so 12 - now at D so calculate the value so 12 - 7 + 1 is equal to 6 check if 6 is less 7 + 1 is equal to 6 check if 6 is less 7 + 1 is equal to 6 check if 6 is less than 6 no so 6 Still Remains the Same and now we increment our D count so D value from minus one it will become to zero and we check if this 0 is greater than 0 no so found will still remain the same now left pointer is at8 calculate the length 12 - 8 + 1 is equal to 5 check if 5 is 12 - 8 + 1 is equal to 5 check if 5 is 12 - 8 + 1 is equal to 5 check if 5 is less than 6 yes 5 is less than 6 so Min length is now 5 and what is the string and the string is EB a n c because we take the substring from left to right + take the substring from left to right + take the substring from left to right + one the string will become EB and C so this will be updated to so result is now EB and c and now we have to increment the value of e was minus1 it will become zero and now we move our left pointer because 0 is not greater than Z found won't be decremented now calculate the length left is 9 and right is 12 so 12 - 9 + 1 is equal to 4 check is 12 so 12 - 9 + 1 is equal to 4 check is 12 so 12 - 9 + 1 is equal to 4 check if 4 is less than the current value five yes so update five with four so this value is updated to four and now what is the String the string is B A and C because we take the sub strring and now the string will have the value b n c and increment the value at left by one so B will be incremented by 1 now we check if this value is greater than Z yes the value is greater than 0 so we decrement found so found will be decremented by one and these both are now not equal to each other so we move a right pointer now and now as soon as you move a right pointer you go out of bound so you end the iteration and whatever is present inside the result has the value B and C which will be returned as the output which is the expected output here now let's implement the same steps inside a Java program coming to the function given to us this is the function name and these are the two strings s and t given as inputs and we have to return a string as output representing the minimum windows subst string so let's start by declaring our output I'm going to name it result string which will be empty initially now we can do a edge case that if the length of T is greater than the length of s then we can return empty string as output so let's do that check if T do length is greater than S do length then we return our empty string and the empty string we already declared it here so we can return the result direct now we need a 1D array to find the frequency of elements inside the string T and the size of the tar is going to be 128 SNT consist of only lowercase and uppercase English letters and the large Bond of lowercase English letters is within 128 so I'm taking 128 instead of 256 you can also take 256 but to decrease the memory I'm taking 128 size so I'm going to name it t count and it will be of the size 128 you can also use a hashmap but I'm here I'm using a array now let's iterate through the input string T character by character so we access each character at a time and convert the string into a character array so that we can access the characters inside the array so I'm going to use the two car array method so this will be converted into a array and now I have to increment the t count so t count and wherever this character is placed for example uppercase a will be present at 65 index so there we have to increment the count and D will be at 68 index and c will be at 67 and so on you can refer the aski table for the positions where the array will be incremented now we need another array so I'm going to convert the string as to the character array so I'm going to name it s Cs and convert the string s into a character array now we need to declare the two pointers left and right the left will be the left part of the sliding window and right pointer will move until the end so both of them will be starting at the zeroth index and now we need two more variables to find how many characters we found until now so that we can calculate the substrings length so I'm going to name a variable called found which is initially zero because we haven't found anything until now and we need another variable to count how many characters we need to find that is the length of the string to find variable will be of the length of the T string so T do length and now I need a variable to calculate the windows length so I'm going to name it Min window length and I'm going to assign it to with the value zero because currently the window size is zero or you can set it as integer. Max value because you want to find the minimum value so from the next time whenever you find a value less than integer. max value it will be assigned to this now let's iterate through the string s using the right pointer so until the right pointer reaches the end of the string s we keep on iterating so I'm going to use a while loop so right is less than the S do length so until we reach the end of the S string and now let's access the character which is pointing at the right index we start with the right index which is at a so I'm going to store that character inside a variable called CH and the characters inside s so S car of right will give me the character so initially we start with a so right is pointing at a and a is found inside the character array so whatever characters we are accessing inside the string s we need to decrement it from the t count because we access that character so t count of the current character CH we have to decrement its count so initially a was one and since we accessed a count has been decremented by one and it becomes zero because we visited a inside the S string character at right pointer is a useful character is a character which is present inside the T string it means we have found one character out of a Target three for this example because a is appearing here and a is a useful character so if t count of the current characters so if it is greater than or equal to zero so it means we have two increment are found variable by one and we have to check if it is equal to two find variable now we have to check if we can move the left pointer so for that I have to check if we met all the characters inside T so we have to check if found is equal to two find so if this is the case we have to calculate the windows length so for example till here we accessed all the required characters because the required characters are a b c we found a here we found B here and we found C here so till here we found our three characters which we need so we have to calculate the length of this substring and compare it if it is the minimum substring length until now so if and the minimum window length we calculated it here so initially it is Max value and the current Windows length you can find out by the right pointer minus the left pointer + 1 because of the index pointer + 1 because of the index pointer + 1 because of the index position so right is at five and left is at zero so right minus left is five so 5 - 0 is 5 and we have to add plus one - 0 is 5 and we have to add plus one - 0 is 5 and we have to add plus one because index position start from zero so we'll get our substring length as six so we have to calculate the current substring length here and compare it with the minimum substrings length until then so right minus left will give us the current Windows length if the current windows length is less than the previous uh minimum we found then we have to update this with the current Windows length so current Windows length is again right minus left + 1 so you can again right minus left + 1 so you can again right minus left + 1 so you can store this inside a separate variable here but I'm not using a variable here and now we found the length of this but we need the string right because we have to return the string so we take the substring and the substrings limits are going to be left and right + one because going to be left and right + one because going to be left and right + one because if you take only right this character won't be included inside substring right because in substring the second parameter will not be included so we do wr+ one so we update the result string wr+ one so we update the result string wr+ one so we update the result string it was initially empty by taking the substring from s do substring and now place the limits first we start from left and we take until right + one the result currently will be right + one the result currently will be right + one the result currently will be till here and now we are moving our left pointer right so before moving our left pointer we have to increment its count inside this so t count and now we access the SC that is the character at the left pointer inside the string s and we increment its count by one and now we have to check if this value is greater than zero so if this value is greater than zero then we decrement our found value by one because we removed the useful character from our uh search so found minus and now we can move our left pointer to access the next character and then this condition will be checked again and now in the next iteration for this value we increment a right pointer so if this condition is not met we directly increment the right pointer if this condition is met we calculate the result string and we update the minimum window length and then we move our left pointer and finally this will happen for all the characters present inside the string s and you can finally return a result string outside the Y Loop so I'm going to return result string here now that's it let's run the code the test case are being accepted let's submit the code and the solution has been accepted so the time complexity of this approach is going to be B go of length of S Plus length of t because first we are iterating through all the characters present inside the string s and we are also iterating through all the characters inside the string T and the space complexity is going to be bigo of s where s is the length of the string s because we are uh using a character add it to compute our output that's it guys thank you for watching and I'll see you in the next video
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
394
hey everybody this is larry this is me doing day nate 1819 uh of delete code daily challenge hit the like button to subscribe on drum and disco let me know what you think about today's farm and today's uh everything because uh the contests i believe at least in my local time i guess in everyone's local time it's about an hour away so i would treat this as a warm-up uh let me know what you as a warm-up uh let me know what you as a warm-up uh let me know what you think and if it's a little bit too slow watching a faster speed today's problem is 394 decode string medium problem okay so uh okay that seems pretty straightforward maybe what does this mean okay so um so then you have k and then this encoded string um are there any loopy ways like okay so there is um okay i mean i think so one thing i would say is that there's no way to do this beyond um there's no way to do this uh you know in a good way because um you know you have to upload the entire string right so that means that um that means that at the very least you have to kind of generate the string so i don't think there's any clever way of doing it so let's just start doing it and in this case it becomes a parsing problem at least to start and if you've been watching me on advent of code that's what i've been uh doing a lot lately on twitch um i don't i haven't been streaming on twitch that much uh but i do for have enough code because it is a fun thing okay so let's kind of just get started i mean i think the rules are pretty straightforward um basically you um you see a number uh you um and then you just kind of uh um there you see a number and then you get the next thing and then you just pause it out right okay um hmm let me think one fun way to do it is you can actually change use regex to change this into a ul or both statement and then just return the url but uh but yeah let's not do that i suppose but yeah i mean there's a couple ways you can do it i think you can do this by recursion you can do this by um you can do this with like a stack um i'm actually kind of bad at this i am at least with this kind of thing maybe i could think about this as a way to practice as well because recursive descent is probably the way to go um but i'm always kind of okay so i'll do the n square way and then maybe i'll kind of um look up ways to do it in linear time uh or not look up ways but just like think about it in a little bit later um because it's not so bad but um and maybe i'll do it that way okay fine let's see what we can do right so let's just say we have a stack and then now for x for c and s for each character and then if c is numeric um what do we do let's just say we push it on the stack um yeah let's just put on the stack and then let's just say we have an answer let's just make it an array um so does it make we push it on the stack kind of um and this is if stack of negative one is numeric um or if length of stack is equal to zero or this thing um okay actually if this or a stack is not numeric then we just put push on the stack i think the way i'm going to do it the augmented numeric uh maybe we'll see um else if stack do is numeric uh in this case we want to so the reason why i do this way is because i want to pop from the top and then concat that with uh the character c so that basically for example if you have like 20 you'll just put 20 on it on the top of the stack something like that maybe i don't know maybe this is a little yucky we'll see um okay that's if it's numeric and then ifc is equal to this uh then we just push it on the stack yeah and then else if c is going to do this we pop it off the stack um that means that we have um maybe we don't need to say that uh that means that we what does that mean right that means that we pop it off um so that means that everything that we have so far inside the string we will um we'll keep on yeah i mean i'm trying to think about the queen way of saying it but basically then we just keep on popping until we see this thing and then we get the number that's before that right so yeah so let's just say and we might have to do like some reverse thing um or something like that but that's fine wow stack dot um the top one is not decode to this faint open bracket um that's just append start dot pop and then when we get out this that means that the top is the face then we pop off the top of the autocorrect keeps on adding the other half that's why or auto complete whatever um and then now we look at the previous thing to save as a number right if stack of if length of stack is greater than zero and stacking is numeric um then we actually pop the number um x is equal to end of this pop then and then we push back uh x the number times this uh r thing do i think this is backwards to be honest so let's uh do um and then let's find out what the stack looks like at the end i think maybe we're good but maybe we're not oh well it's not good because we don't do the um otherwise if it's any character we just append this we just put it on the stack right like with an a or two or whatever okay so that looks good uh let's try a few more um i also want to try the double digit ones which is not on this thing um okay so it seems like i actually not gonna lie i actually did not expect this i've been a little bit out of practice on this for some reason um to be honest i should be bad about this but i'm not uh um so i don't know uh it's still uh another one i guess this one's inner one so let's i add in some extra numbers so that i'm sure that i um i paused two digits uh correctly i mean in fear we should also try three but maybe we'll get a long thing but that looks good uh so let's add a one more digit um okay now let's that looks good so let's give it a submit i did it first time correct last time hopefully this time as well yes just as good as i was a year ago at least on this problem um uh what is there to say about this one yeah i mean i think this you can do this with recursive pricing as well i've been kind of bad about those in general to be honest um i don't know let me know what you think and yeah good luck on the contest and stuff like that stay good stay healthy to good mental health i'll see you later and take care bye i actually forgot to analyze the complexion man i haven't slept that well lately i've been a little bit off um but yeah so to go over the complexity and the timing and the interviewness of this really quick um i could very easily see this as an interview question so definitely practice on stuff like this stack especially a problem that is only a stack and passing and nothing else um i would really consider base level skill um in terms of like if you only get this you're probably a little bit lucky um so yeah so definitely be practicing this is linear time linear space the stack will take up linear space and the worst case and any time because we look at each character at most once um keeping in mind that each character even though there's a while loop somewhere while up here each character only gets pushed once and only popped once so that means that each character would only do all one work which means that this is our one time oh sorry or one time per character which is all of n's time um so yeah linear time linear space and that's why i have and then now for real hit the like button hit the subscribe button join me on discord stay good stay healthy i'll see you later good luck on the contest if you're doing it bye
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
93
Peace be upon you, my friend. How are you doing? God willing, today we will solve a new problem together. If you have not solved this problem before, please let us go to it first, and then come back to us again. You may still watch my episode if you brought Exped. It may be a different solution than the previous one. You're in it, even if you don't know how to solve it, let's solve it together. The first thing is that this issue will be solved completely. King: If you don't like the tracking, then go back to the video so you can understand what will be said at home. Okay, if you still understand or you go to study and track it, let's go. We start, in the name of God, from zero up to 255, which means zero with us is 255. Beautiful. You have an example or examples. I can study 255 and there is nothing new. Beautiful. This is the turn of their examples. The first one is zero up to 255, but this is in Zero 11. The second one is four more, but in 312 this is greater than 255 After that, he tells you that he will give you a string. This string will be made from Only Digits. You are supposed to return to him all the baseball Fred IP studies that can be made by putting Dots in this spring. Okay, all that is allowed for you in the IP in DHO Around the digital ok so that you are the IP to study and of course it is necessary that the first thing with us here was that there were two IPs to study in fact that it is the first thing 255 Okay 2 5 1 3 5 The first IP to study told you that I am taking some countries together. And I take these together here, and I will take these together. I put here and I take these together, and that's how I still have a score of 1 2 3 4. I have less than 255 or equal to it. There's no leading zero, and that's the first year of secondary school, and the three are together, and the two are together, and that's why it will still be one, two. Three, four, ok, you can do anything else. If I don't think it will work, you can do anything else. Okay, ok. Here was the only IP I studied. The country is 00 IP. The issue is, as we said, it can be solved by back-trickling. we said, it can be solved by back-trickling. we said, it can be solved by back-trickling. So I will try all the solutions and filter which country is among these solutions, meaning that I am now. If I had the first example, it would have been in two, five, one, five, two, five, one, three, five. All I can do is as it says to me in the question, that you put a dot between A2 in DJ 3. Okay, so what will I do? I will say, by God, I have two choices. Either put a dot, ok, now I will start from the beginning and say I have two choices. Either put the pressure, so if I put a dot in the first place, it will not work, right, okay, can I do something else instead of saying I will come here and put a dot or I won’t come here and put a will come here and put a dot or I won’t come here and put a will come here and put a dot or I won’t come here and put a dot? As I go to put a little something like this, what can I do? Can I come to every start that I can start with? Okay, what I can start with and be the first to spread among the 4, you are supposed to be 255, so I will come here, considering that this is the second curtain. Okay, and I will say, by God, I can start this. My first number is the one you have, the last of us is 255. His line is three, ok, one year. Maybe this is the oldest, or the youngest, three, one. Okay, fine. I will take this one and tell him that I decided to put countries here. Then I have two. The first one to spread is this country or country. It remains until now. Until now, I haven't finished yet. Okay, continue, so I'll go to the new fifth, right. That means three choices, one or two or three. Okay, take care. I'm coming from the two that are at the beginning of the IP. I'm studying for my studies. I will now say the first choice or will I take it? I'm now the new number. It's five, okay, so let me put the five before it, and put the five, but ok, and I'll go to Monday, put the two because I'll take the first choice, and the Monday will send me to the next one. Okay, put five like that. I have how many I have. One, two, three, four, five, so I can study for myself. I don't. I have to continue because I knew, and I am like this, that I am studying and I am going like this. Okay, ok, at the two. Ok, while I am standing at the two, I will say that I was repeating that my turn will remain on one person, so I will leave it on two, so instead of what I was, I will put it here instead of what I was. I put the dot here. I put it here. Okay, I put it here. This was the second choice. After that, I will go to the fifth after I go to the five here, because this is the first choice of these five, which is the one. My number became Nodvelt or the IP I study because it still contains one, two, three, four, five, inter. Okay, so I don't have to continue. This is what I will do. If you prefer to complete the example, it will take a very long time because this will be backtracking, and backtracking will lead us to a large, powerful broadcast that we will not be able to cover in the video. But I think what is the idea in the first place? I will come to every index to try. I take the number consisting of one lens, two lines, three lines, because this is what is available to me. Ok, let's try something else. Let's try, for example, that we walked a little in the electronics and said, for example, 255 dots. When I come to put the worms here, I will try that if I take one myself, it will not work. I try taking It will be useful to say 255. Okay, one, 11, or 1 can come out, which is I put a dot here in the first example. I put a dot here in the second example. A dot here in the third example. How many three will come out of each branch? Okay. Three will come out of it. I mean, let's forget. These are the ones we are currently focusing on, this is the one who is the one. Is he the one who is this one? What should he do? Send me here. Okay. I am standing here. Either I take one, but it is fine. It is nice. And so on, until he sets up an IP for studying with me and I can say that the IP is studying for this. Okay, in other words, that I am. Can I delete these things like this and still know my own numbers? For example, one by one. We agreed on 11. This might work. Ok, so I will go. I will still be standing here and see. This is what I will find. If I put one but one, this will let me take two and three a second time, and this will let the IP study add one to two. Three, four, and the new one will be five, so it wo n't be completely useful, so I will have to take them all at once. Let's see the code, it will understand you more. The first thing is nice, but I don't want most programs to take some of the programs you are standing at on the IP Study or the digital one that is offered to you in the section. The second thing is the number and finger that you have created just now, and you take the current card back. Study what you are working on with the four, so it will not be useful for me to take them with me in the study IP, because the study IP consists of four interfaces, but if I count the four, then I am one million per cent. Note Valet, then nothing. It will be useful to complete the February Okay, if I am less than four or equal to four, then I hope that the IP study this, I am upset. Ok, if I have reached four, it must be at the same time, meaning that the index must be the one I am standing at, and it will be equal to me now. This means that I went out of year because what if, for example, I had 255 like what was there? For example, if I had 255, and after that, it was one. I don’t remember the example: three, neutral, three, five. This was my string. Now, I am supposed to have the index zero, until it’s okay. Okay, if I found that the counters that I built in the string when I was coming were worth 4, you actually have two possibilities. As for you, for example, you made four, but your index steel is still standing here, for example, so this means that you have a counter of four, but where are you going to put the second one like this? Okay, so it should be. At the same time, the index is equal to now. I mean, now it has equals. What does it mean? It is equal to it. It means it went outside. The strings after that, you took all the strings with you. At that time, this will be a team because I took all this digital with me and those with you and made four. Okay. Ben Bush. Cabbage. I study in the village called Valette Idrissi. Okay, ok, if other than that, then I will continue. I mean, I still haven't reached the end of the string. Then I will continue perfectly, even if I reach four. Even if I reach four, because next time you will increase by five, this is another time. I mean, okay, I got out of spite. I'm sorry. I grew up again. Then the next time. There will be four meals, but it is not the same as now, so what will happen next time? I will have five okay, and when I have five, this condition will go away without anything being done here. This will happen when there are Mondays, or the Petro configurations that are the number of the completed Peshawarma I made. ip, but what is the 35, for example, so if I am three, this is my start, then I do not have it. If you are three, this is not there. I last three, five. Every time I will say, if you are of zero, which is the first number in the internet. Inter is on the left. Okay, if it is equal to zero, then I have it. There are two possibilities. The first possibility is that the internet card is number one or the user is one, meaning it will be zero, but at that time there is no problem. So, when does a problem occur? If the user’s account is 2, for example, problem. So, when does a problem occur? If the user’s account is 2, for example, problem. So, when does a problem occur? If the user’s account is 2, for example, or his user is 3, then at that time it is considered useless. Why is its break space because this is my start in the first place? I have a cover from this index in anything greater than one, which is two or three. Okay, it will not be possible to continue because the IP address I am studying will be the noodles. Well, if it was like this or it was not zero in the first place, its name is 255. If it is less than it is equal to 255, then what will I say? If this is Valet and I will continue, I will tell him where he came from with Index Plus, which means that if I took one person, the Index moves once. If I took anything that was two in the next station, it will remain plus two. I go to the start of the next one, okay, and after that I say Number Officure Plus one, then I am an Inter account. In the IP, I study my current one. Now, I have a number with you, okay, and after that I say that I study the current, ok, that's why I was doing it. If it's cold, I will pop back because I will still have an IP. I study the dot. Suri before we close the video. The first thing I have to do is stop at A certain index called AD His one is actually the zero itself, so at that time this is not Lady Zero, this is an island, there must be a zero after it, a number after a number. This means that her lens is greater than one, so if it is the uh, each one is definitely greater than one, because the ay, oh, by 1, oh, by two. With three, okay, then because I will not be able to continue because the IP I am studying will be Noodles. Ok, 255. If it is less than or equal to 255, then I can continue. Continue. How do I make the sound for the start of the new star? It will be the Antix that I am standing at, the Class that I took, and the Number and Finger that I have them on the IP study so far. Nimro Finger Plus will be the one I have so far. Plus the current post, I will publish what I have created or what I have chosen to be added to my IP study. Dot ok and I will come here. If the number and post is greater than four, then the IP study will not work. Exactly, there must not be any numbers left at the end. Okay, and after that you will be afraid of the Valid Address. This is the current one. I study in the Valentin, in the Ariel, it is called Valet, or the Victor Offstring, which is called Valid Addresses and Haritor. Ok, after that, in the function, which is my basic one. What should I do first? Now let it be equal to the size because after that the hearts will be born from zero. Zero is the first index and the number will remain zero. I hope the explanation was good and I understood all the issue. If there is anything I did not understand, you can write to me in the comment and I will see you next time, God willing, fine.
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
1,913
hello and welcome to another video in this video we're going to be working on maximum product difference between two pairs and in the problem you're given a product difference between two pairs a b and c d is defined as a * B minus C * D and c d is defined as a * B minus C * D and c d is defined as a * B minus C * D so the product difference between like these is 16 and given an array nums you want to return four indices such as the product is maximized so for example here we're going to want to return like it tells you right here 67 and 24 that's kind of the idea here to maximize product we want a * a * a * B minus C * minus C * minus C * D where A and B are the two biggest numbers in the array and C and D are the two smallest right because we want the biggest product possible minus smallest product possible and the way to do that is pretty straight four we just find the two biggest and the two smallest that's kind of what we need to do we need to go through this and we need to find the two biggest and two smallest numbers now let's walk through how we can do that so we'll just make an array of numbers and let's just put in some numbers so one easy way of doing that is to just sort the numbers right if we just have all the Norms like let's say these were our numbers then we could easily find the two biggest and the two smallest but we don't want to do that there's going to be a better way so let's just say we have some numbers let's just say we have like five 3 9 8 1 5 15 uh 7 2 three so first we're going to do is we're going to initialize the numbers and the easiest way to initialize the numbers is just take these four and then sort them and then put our numbers in the right thing right so what we want once again is We Want A and B to be the biggest two or I guess in our case we'll have a and b be the smallest two so we'll have a be like the very smallest B the second smallest C the second biggest and D the biggest so we can sort these and just put them in a CD so this sorted would be 3598 so it would be like 3 5 8 n right sorted now we can just go through numbers and we can just check we have to check two things right is it in this range or is it in neither so and by In This range I mean is the number smaller than b if it's smaller than b then we're going to want to add it over here or if it's bigger than C we're going to want to add it over here and then we just need to check where so if it's smaller than b we need to see is it's smaller than a as well if it is we will replace a with it inter replace B with a so let's kind of walk through how this would happen so this is the first number we're out we're going to check is it smaller than b yes it is it smaller than a yes it is so what's going to happen here is B will take the old a value and a will get replaced by this new value so basically what's going to happen here is B will take the three and a will take the one now we'll check here is it smaller than b no it's not is it bigger than C no it's not so it's not a number we care about okay what about 15 is it smaller than b no it's not is it bigger than C yes is it bigger than D yes so then what will happen is c will take the old D value and the new Val 15 will go into D so we're going to have nine so we basically have four checks right is it in this category and do we have to replace the biggest or the smallest number and then is it in this category and do we have to replace the biggest number that's kind of what we're going to be doing then we're going to over here we're going to say okay s smaller than b no it's not is it bigger than C no it's not is two smaller than b yes it is it smaller than a no it's not so we'll just replace B with it directly and finally is three smaller than b no it's not is it bigger than C no it's not so now we have notice we have our two smallest and biggest numbers now we can easily just get a product here and subtract them and that will give us our answer and that's pretty much it so now we can code it up so we are going to have our four numbers initialized so we'll have a b c d equals the first four numbers sorted so number 0 to four we can just do this so the first four numbers sorted will go into ABCD now we have to look through everything else so 4 I in range four we'll start at four up to the end of the numbers we have to check is the number smaller than b if it is it smaller than a and if it is smaller than a then we have to replace a and b right so we'll say like a equals a gets replaced by the number and B gets replaced by the old value of a otherwise B will just get replaced by the number because it's not smaller than a so we'll just say b equals numi and the other case is if the number is bigger than C so if the number is bigger than C then this is basically the same logic in Reverse so if it's also bigger than D we need to replace um C and D so we'll say c d equals D numi otherwise we just need to replace C and finally at the end A and B will have the two smallest C and D will have the two biggest so we just return uh D * the two biggest so we just return uh D * the two biggest so we just return uh D * C minus a * d right the biggest product C minus a * d right the biggest product C minus a * d right the biggest product Min smallest product and that should do it and there we go so now we can talk about the time and space so for the time we went through our array one time this part doesn't cost us anything because we're only using four elements this is o one so we're going through the array one time oen and for the space we just have four variables so it's o1 because we just have this ABCD we're not using anything else yeah the other way is sort it and take the two uh smallest and biggest but that would also be over one space and it would be n log n this more efficient so the other thing you could do um if you were to modify your input just briefly I could talk about is you can actually get the max and the Min and then you can just remove those two numbers and that would also be oven and o one and it would be a lot less code but for most problems you don't want to modify the input so basically you would just get the max like give me the max then you would say like okay that number let me remove it right and then yeah or you could manually look through the list again and you say like okay let me just try to maximize my number again but that number can't be the first that number can't be at like the first index that I got the first number right so something like that works but this is a little bit cleaner so bunch of ways to do it but this is one of them um yeah and yeah that's going to do it for this one so hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Maximum Product Difference Between Two Pairs
make-the-xor-of-all-segments-equal-to-zero
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. * For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. Return _the **maximum** such product difference_. **Example 1:** **Input:** nums = \[5,6,2,7,4\] **Output:** 34 **Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 \* 7) - (2 \* 4) = 34. **Example 2:** **Input:** nums = \[4,2,5,9,7,4,8\] **Output:** 64 **Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 \* 8) - (2 \* 4) = 64. **Constraints:** * `4 <= nums.length <= 104` * `1 <= nums[i] <= 104`
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
Array,Dynamic Programming,Bit Manipulation
Hard
null
293
all right this question is flipping so in order to um flip the entire string uh you want to know it does contain two consecutive substring plus so you can change to minus so one way of doing this is uh you Traverse and you see these two index if they are plus you know you can convert to minus and add a result into the list of strings I'm going to call result right and then your back to the original string again and then your Traverse the next index which is going to be this one and then convert to minus as a result in I mean added string into the result and move on the next index so yeah basically straightforward now all right so how do we do this so just you know the index it's not hard so it's on the list of string results it will do the new and then this return result based on the first Index right first place so um I'm starting the index one right so which does contain what zero I mean I minus one and I right so if I'm going to change the current state to s and start chart at a i minus one is actually equal to plus and also it's got chart at a i it's actually equal to Plus now create the substring so it's just singular string the other actually so I'm initialize the string into the stream Builder so this will be right but I'm changing the current index and changing the I minus one and I into the minus so I'm going to say SB last set chart at AI equal to minus and also it's beta state chart at I minus 1 equal to nine then I will add a string into the results so it's on the resulta app string Builder two string so this will be the solution and submit all right so time and space um just pull my notes all right so this is time all the fun Shivers every single one of them right this is finance right then you just copy and instead the index into the right so you add the string into the result space is all of them because this is a list of string right all right so try some development you know inside so I'm going to pause let's start the ballgame and keep going down you know the first one is Success right so this is stream building adding two results and then I guess two another one right this is how it is right all right so that would be my solution if we still have a question is a comma leave a like subscribe if you want it all right peace out bye
Flip Game
flip-game
You are playing a Flip Game with your friend. You are given a string `currentState` that contains only `'+'` and `'-'`. You and your friend take turns to flip **two consecutive** `"++ "` into `"-- "`. The game ends when a person can no longer make a move, and therefore the other person will be the winner. Return all possible states of the string `currentState` after **one valid move**. You may return the answer in **any order**. If there is no valid move, return an empty list `[]`. **Example 1:** **Input:** currentState = "++++ " **Output:** \[ "--++ ", "+--+ ", "++-- "\] **Example 2:** **Input:** currentState = "+ " **Output:** \[\] **Constraints:** * `1 <= currentState.length <= 500` * `currentState[i]` is either `'+'` or `'-'`.
null
String
Easy
294
1,679
Hello Hi Everyone Welcome To Record Programming In This Video Download Maximum Keep Sankat Select Your Valuable Information By Clicking On Like Button Now Let's Friend Aadhar Number Tesu Samiti Ke And In A Given Number To Subscribe If You Liked The Video Then Improve Number of a given issue number online return of the day candy crush so obviously they cannot afford to loot mouth and lemon in vitamin B6 B2 ki darmiyan pet sutri at that time code file saurashtra 2021 do subscribe 500 and problem harris and here giver number Not Able To Find Duplicate Will Adopt These In Less Time Morning Is Half Hour Morning And Half Hour And Wind Open Access Time Morning Chemical Not Used So I You Are Right 200g Office Installed Every Number Security Bihar Map Sui Below Written Aunty Start With first number 6 Effigy of number 1 minute and number subscribe and listen minute veer Rolex Vivo's com development school 25th you have 4 inch is a fine subject is so let's leather coat after the same that I very young to unhealthy solitaire's map to work number and will go through every number from the governor witch content due to the number own Map removed number camp by MP Sudhir directly - 2 directly - 2 directly - 2 100 toe return is every and Anitya account is a serious matter ke dansh number On this occasion, according to the school, set the number thing in the phone like swimming toe fur will give you on this number This selection of selected 180 plus TV shampoo dr center me affair comment birthday account which you want to join them in this app contains a 140 has been accepted a 200 run time of permissions and certifications for its first time congress Chief And The Today We Present Commercial Shop In Brief And Pimps And Ka Numbers In Term Of Minutes Ago
Max Number of K-Sum Pairs
shortest-subarray-to-be-removed-to-make-array-sorted
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explanation:** Starting with nums = \[1,2,3,4\]: - Remove numbers 1 and 4, then nums = \[2,3\] - Remove numbers 2 and 3, then nums = \[\] There are no more pairs that sum up to 5, hence a total of 2 operations. **Example 2:** **Input:** nums = \[3,1,3,4,3\], k = 6 **Output:** 1 **Explanation:** Starting with nums = \[3,1,3,4,3\]: - Remove the first two 3's, then nums = \[1,4,3\] There are no more pairs that sum up to 6, hence a total of 1 operation. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `1 <= k <= 109`
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Medium
null
221
A Real Good Beginning Unit Co Problem Today Maximum Square Feet Is Lead Code Number To 2131 Problems Were Given With The Name Cross And Finally Matrix Field With Yours And Bones And Need To Find The Largest Square Containing Only Once Again Due To Remain Its Area Super Example In this particular square interest kilometer is updates Tubelight whose years are made of once but scheduled time due to be aware of once in the recent updates youth cross band saree only two options coconut activist and a retired is use gondvi 400 shorty a good to be decided To Withdraw This Prayer To Maz School Birpur Ki Aap Khud Is Vansh Volume Pal Latest How To Solve This Problem Should You Certificate Dynamic Programming Problem View Points Of Problems And Will Solve Problems To Find A Solution Of The Last Lear Percent Area Of Pliers Koi The Latest How To God Hua Hai Ko Safal V Guddu Break Into Problems And Find Solutions To The Problems And Finally User Problems To Front Solution Without The Problem One Notices - Problem Clear Bc1 Notices - Problem Clear Bc1 Notices - Problem Clear Bc1 000 This One Is It Is Gold And Decided To Give one that is not using this one who can be done next so if this playlist is top left corner of research in order for the best all elements to be one can see the example of one to be 323 join elements needed to be one Do not exceed 93 itni move to disrespect another level aap shopping discuss bhaiya considering them s recent s you want to see the square with elements corner is only s good s be small square download with jatin elements na subha considering this particular limit nor such activities element Hair 10 This Element Is Going To Be Placid Top Left Corner Of The Element Also Give Water Element This Elements Of Obscuritism 9000 This Is Not Considered Only Wave May Only A 210 Element Is 10 Largest Square Itself Will Give One Square World Only Batuk Bhairav ​​Square Only Batuk Bhairav ​​Square Only Batuk Bhairav ​​Square Using the information about getting from this element and this element what they can see in between Here Will Be One Plus One Of Its Sides Nominated To Happened Yesterday Morning Ubal D P R A N D First Step In Order To Find Dynamic Programming Problems Solution Is To Create A Fear And Give Me To The Self Defense In This Case GPRS Gondvi of the same size SD Original minister to give wealth should be conducted and crops and are that anti cell is gone to represent distance side length of the largest wire having this channel its top right corner so imagine square so every cell is go into different Decide length side length of the largest square date this is into thumb have this related top left corner suggestion in left hand top left corner hai hua 24 start from bottom right corner and if dad BP 10 years this lineage we tried to see what is The value of dp right bt cotton nddb direct null diagnosis dushman and absolutely minimum of all three for but 128 in this whole value is the name of the largest ko this special top left corner straight with gf with her due subscribe to the Page if you liked The Video then subscribe to the Page if That The Last Row Of This Terrible And Last Column Of This Table Will Give Me To The Directly Vinod The Self Dam Divya Continue To Meet Recent Rans And Decide For Higher Studies 125 Bill Se 1200 10 Ka Record 2009 Ward No. 10 days including Vipin Chaubey Get the minimum of soil from this is What is this is the name of the pyramid Pyramid in the bottom 1000 Subscribe to a plus one is two0 - 121 Soil but one care friends welcome two0 - 121 Soil but one care friends welcome two0 - 121 Soil but one care friends welcome to this point 101 shades consider And what is the name of the m0vie 812 dum and taylor swift new year new dr minimum soviet 0512 nuclear loot 192 this point fennel one thing is disposed to here right successful the steps to look at the weather they can not be given only in the Amidst various checking what is the meaning of other problems but in this case the values ​​already shifted early in the morning to here is the case the values ​​already shifted early in the morning to here is the report also here on that now let's move next point serious one should be considered all three officer one is the minimum one plus one tsp bittu name vikram chronic disease 90 consider all the minimum is lineage oneplus one two 9 0 0share 0tweet c what is the meaning of the word is particular hai ko absolutely minimum balance gum b22 100ml stuart Channel And Id 2nd Grade Three Years Ek Pan Sins Daksheshwar Difficult Sl2 Two Three Liye Buddha Minimum Balance Two Plus 123 Again No This Is Very Important For Both See What Is This Is The Largest subscribe and subscribe the Channel Please subscribe and subscribe the That's another thing but I want to do off International Forum for Every State where also calculating now max value and weaving slice max vid0 and wherever e c t and navm and mode on savi updates max 100 hours this point what you see in the middle of soil Dhairya Na Vikram 2.0 Is The soil Dhairya Na Vikram 2.0 Is The soil Dhairya Na Vikram 2.0 Is The Indian 2003 More Deep Study Love You To That Surya Can See This Square Has Stood Outside And So When You Have 2012 Consists Of Square Of Two Plus Two Science And Having Declared Its Top Left Corner Subjective A Famous Algorithm I Think Pimple you want to have a good profession so let 's go and improvements in terms of 's go and improvements in terms of 's go and improvements in terms of both to the soul let's create available at ease max value and definition of 8th maths 9th global rating dp are not the place where created fear of that news meter effects of Course will be saved from the right bottom right corner to top left corner always in any step using finger using the right bottom dengue fever subscribe ek lemon dal special award chaat show a great leap year and you will start from matrix dot length india starting from Bottom Right Corner 800 I'll Be Lower Is That Metric Start Length Minus One Should Go All The Best 2048 Register Back To Defeat By One Samsung Duos And Judgment Equipped 0 - In The End Equipped 0 - In The End Equipped 0 - In The End James Pattinson Equal To 0.5% Airtel Offer Loop Not Every Step With Check 0.5% Airtel Offer Loop Not Every Step With Check 0.5% Airtel Offer Loop Not Every Step With Check Weather In Adheen Doobi Lutia Values ​​Which Values ​​Which Values ​​Which Lasts Or Not 100ml Se Effect Is Last Roles To IAS In Tree Dot Length In Tricks On Length Minus One Arrested Last Column Solving Junior Is Zinc - World India Showcases Junior Is Zinc - World India Showcases Junior Is Zinc - World India Showcases Debit The Same Valid And Values ​​And Values ​​And Values ​​And Converted Into Number hai so aa way matrix i j is hoon bhi same s matrix ia baje hai but bhi ne to convert distance in to and number so happy new s number that and in this also update mix vegetable soup math dot max from matrix aay j and milk cell at max ki one volume ab hum nn mein hindus continue election bhi come to the next k is the best wishes 120 and north se number matrix hi jeene and deficit viewers 1200 phase alsi matrix k khojja 2014 this is also depends on last Final Specific In The Ring To Write And Share This Cosmic Bliss Of Sexual Matrix RJ Is Good Be Sun You Need To Think About What Is This Is Good Come From Mother Of Discussion That Hard Choice The Bell Icon Is Here Is Vansh Sun Or Looking And Adjoining Elements What Milk 10 Choice Crops Tweet Research That You Column Redwine Column Should Be Mix By DJ Plus Fruits Daily Wear Look At Me Tricks I Plus One Enjoy And Lasting Activities To Give Me Rickshaw Plus One And Z Plus One So Wide One Strong Option Brightness Minimum Hotel In Math Ninth Tenth Minimum And Volume Minimum Balance 8128 And Active Ye Continuity Current Matrix Value It 16 To Take Care And Update And Maximum Level Result Listening Start Max From It's Abt U In Sodium Day I Think Max Will Contain General Truth And Lotan Like Share's Cutting Half Inch All It's Strong And In This Program Okay Pure Silk Mirror Brightness More Race I'm Doing Max Hair Oil Questions About Area Surme Bitmax Content Max Containing D Length Of The Side And In Order To Create A Report To The Side Business Multiply Side With Sides To Maximum Light By Max Eggs All Salt Latest Peeth Box For Example Kaise Saaf Baje Dance Let's Meet On Hey What So I Thing With Solution So Thanks A Lot For Staying With Me We Soon This Point Hai Lemon Like this video please like and subscribe this video channel thank you so much
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
1,791
so hello everyone welcome to this new video and i will be explaining the problem find center of star graph so this is a very easy problem initially i thought it was going to be super interesting so anyway in this video i will be first explaining the idea and then i will code it's going to be i think a short video so the idea so what the problem is asking me that i have been given a graph which is a star-shaped so i have to tell which is a star-shaped so i have to tell which is a star-shaped so i have to tell the node that is the center of this graph okay so the center of the graph will be the node from which it will be contacting all the other nodes okay so if i understand from this example this is the center node okay so how i will be calculating the center node is by calculating the in degree if you are familiar uh with the in concept of in degree you can like skip to the coding part else i will be just be explaining the degree here so in degree means i will basically uh taking all these notes and calculating that how many these connections are coming to that particular node okay so for example let's write one so in case of one i will see it will have it will be having only one connection in case of two it will be having what uh edges or connections whatever like it will be having three like there are three lines passing from two so it will be three and for four it will be one and uh for three it will be one so this is the idea so i will just calculate all the indegrees of all the nodes in degree the nodes that are coming in and then what i will do is that i will get the one which is whose end in degree is n minus 1 and that's the idea to solve this problem so let's solve it you can use a map also but i will be using uh what a vector so first i will be writing in uh n is equal to zero that basically means that is basically means the total number of nodes that are going to be in my water in my graph so now i will calculate it for it i is equal to 0 i less than what edges dot i just dot size i plus and now what i will do is that i will just n is equal to max of n comma max edges i zero comma edges i 1 so by in this way i will just get the total number of nodes for example in this case the total number of nodes is 5 so i am getting this 5 by calculating all the max stuff so now what i will do is that i will make a vector called a vector in called in degree whose size will be n plus 1 so this vector will be doing what this will vector will just be keeping track of in degrees of all the nodes so this is a just a simple in degree problem to be honest and now i will be calculating the indegree of all the nodes so for int i is equal to 0 i less than edges dot size i plus then i will be just increasing the in degree of each node so hs i zero plus in degree just let me copy it ctrl c ctrl v i one so this will uh what do this will do is that it will increase the indegree for example i have been given an edge one comma say two then what i will do is that i will increase the in degree of one by one and two by one so in this way this is what i am doing and uh i will write one more thing okay i will just write another loop i can do this here also but it will let's do it here so into i is equal to zero so now i what i will do is that i will just traverse through my in degree dot size in degree vector and i will make one integer result is equal to zero and in my in degree vector i what i will do is that if there is a node whose in degree i is equal to n minus 1 okay then what i will do is that i will update my res is equal to i and then break it break and then in the end i will return rest so that's a problem let's run this code and hope if it working it's working fine now let's submit it so you know this is just a simple in degree problem you have to calculate the in degree and then you have to check the node who's in degree is equal to n minus 1 so there are many ways you can do it in a shorter way also but who cares i mean okay if you like this video please subscribe to the channel okay bye
Find Center of Star Graph
richest-customer-wealth
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Array,Matrix
Easy
null
402
hello everyone today's questions is removed key digits given a non-negative removed key digits given a non-negative removed key digits given a non-negative integer num represent as a string removed K digits from the number so that the new number is the smallest possible so let's understand this problem using pen and paper so our num is a non-negative integer and so our num is a non-negative integer and so our num is a non-negative integer and K is our number of digit that we have to remove so here case 1 num is 1 2 3 4 5 that is in ascending order form so our first thinking is if you delete the maximum element next largest do you form this num then we will get the smallest possible number so let's try so as you can see 6 is our maximum digit in nums string so now we will remove it so first 1 2 3 4 5 after removing 6 and then we will try to remove 5 1 2 3 4 &amp; 6 then 1 2 3 5 6 &amp; 1 remove 5 1 2 3 4 &amp; 6 then 1 2 3 5 6 &amp; 1 remove 5 1 2 3 4 &amp; 6 then 1 2 3 5 6 &amp; 1 2 4 5 6 1 2 1 3 4 5 6 &amp; 2 3 4 5 6 as you 2 4 5 6 1 2 1 3 4 5 6 &amp; 2 3 4 5 6 as you 2 4 5 6 1 2 1 3 4 5 6 &amp; 2 3 4 5 6 as you can see our first one is the smallest possible number if you deal it I'll just digit form this string then we'll get the smallest possible number so this is for ascending order number if string is in ascending order now we will check it for descending order so in this question there is not given the number is always in ascending order so we have to check 3 condition ascending or descending order and mix without any order so now let's take descending order so our algorithm is working or not same we will do we will remove the maximum digit from the string and that is 4 3 2 1 5 3 2 1 and 5 4 3 1 last one is 5 4 3 2 as you can see 4 3 2 1 is the maximum it's possible Melissa um sorry smallest possible number so here also we remove the maximum digit most big air we drill it most big digit from this string so our algorithm is working for ascending order and descending order both now we check for another number as you can see all largest element is 9 so we will remove 9 form our num string and then we'll check we'll got our smallest possible number or not so now we remove 9 from this string and again we remove 4 from this string and we compare to string which have the smallest possible value as you can see 1 3 2 1 9 is the smallest possible value where we remove 4 that is not maximum sorry that is not largest element in this string so our algorithm is not working here our algorithm is failed for unordered string so we need to modify our algorithm so whenever we scan from left to right then we'll pick the first largest element from left which has the smallest element on right so let's follow this first scan 1 and then we'll scan for and we check 1 is greater than 4 no 1 is not greater than then we check 3 4 is greater than 3 yes four is greater than 3 then we will remove 4 from this string and then only get off the smallest possible number if case one will perform the same one time if K is 3 then we will perform this 3 time if K value is n we'll perform the same n time now we will check how will we will apply this in our actual implementation so first we will take a stack so we scan the string from left to right first we scan one and check three conditions stack is empty and check K is less than 0 and check stack value is greater than our current scanning then as you can see now stack is empty initially our stack is empty so now we push 1 inside our stack and scan next element this 4 and say stack is empty no stack is not empty and check ok K less than Z don't know K not less than 0 and take 1 is greater than 4 no 1 is not greater than 4 will not perform any remove operation so we simply add 4 in our state so our stack top element is 4 and we move to the next element there is 3 and we check stack is empty no stack is not empty K is less than 0 no K is not less than 0 so 4 is greater than 3 yes 4 is greater than 3 so we remove for home stack because the right value of largest element is smaller so now we check scan next element and say stack is empty no stack is not empty sorry whenever we pop remove operation then we will decrement one with came decrement by one so now our case two so now we check too so check stack is empty no stack is not empty so as you can see stack top value is greater than 2 so we will remove again so and do add two in our stead so we add two in our state and decrement our K value by one so now our num is true so we check with stack is empty no stack is not empty and K is less than zero no case not less than zero and six Tech Talk value is greater than two no this is equal so now we add two in our stack now we move to the next element that is one we check stack again stack is empty no stack is not empty K is less than zero no case not less than zero and now we move to the next condition that is stack is greater than one yes deck is stacked value is greater than one so we remove stack top bell and decrease by one so as you can see we already delete K digit for hosting now we add rest of the digit in our stack now add one instead and then nine in our stack because now k0 stack is our final answer because stack is our smallest possible number that is point 2 1 9 so here K value is 3 so we remove three element from this string that is four three two-and which string that is four three two-and which string that is four three two-and which is which right value is minimum so we remove it so let's move to the coding part first we take a stack and then assign K in our iterate and we visit its element iteratively and check the condition why are not lesser than zero and stack not empty and check stack top value is greater than I if this condition satisfied then we will pop one element from stack and decrease our value by one and then we append the I value in our state and now we remove the leading zero power remove the leading zero from state as cool according to our coefficient statement if there is any reading zero so we have to remove it from our actual insisting so we will remove our using the else trip L for leading strip zero plus the element zero so now finally we return result if alien race is not null it's zero so now we'll check our algorithm is what our code is back or not so yeah running successfully and submitted yeah got accepted if you liked this video please give me a thumbs up if you have any difficulties please comment below I will help you as soon as possible if you are new to this channel please consider subscribe and don't forget to hit the bell icon thank you for watching this video
Remove K Digits
remove-k-digits
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`. **Example 1:** **Input:** num = "1432219 ", k = 3 **Output:** "1219 " **Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. **Example 2:** **Input:** num = "10200 ", k = 1 **Output:** "200 " **Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. **Example 3:** **Input:** num = "10 ", k = 2 **Output:** "0 " **Explanation:** Remove all the digits from the number and it is left with nothing which is 0. **Constraints:** * `1 <= k <= num.length <= 105` * `num` consists of only digits. * `num` does not have any leading zeros except for the zero itself.
null
String,Stack,Greedy,Monotonic Stack
Medium
321,738,1792,2305
1,032
Hello hello guys welcome to front media say today they will go through the date when the problem August recording channel industry me character please like this video in you don't forget to subscribe to the channel shayari never miss any update element history channel transferred in constructor in various Jobs in The Very Difficult to Quit Example Subscribe My Channel Subscribe Our Video Explain in Detail Check the Video's Description My Favorite Rah Gargadh Not Inside a True Knowledge Will Have Eaten Edit 1960's This Character Schoolly Present in Her Words Now With Every Character Will Be again in the area of ​​mistakes this is the basic structure of ​​mistakes this is the basic structure of ​​mistakes this is the basic structure of but why will also have a flu signifier and would be working with the same approach in the case of most welcome to the validity position and inside senior position against and world-class military similar Will Wait For world-class military similar Will Wait For world-class military similar Will Wait For Others To Vote And Destroy Will Be Generated In Which Path Se Bhi Nahi Tu Kal Tak Various Method And See The Current Character And Spirit Character From World Which Recently Awarded Death Sentence To Life In No Wise Not Present In The World Will Happen Next Chief Minister To Consider Giving Lift To Find A Logic To Understand This To Avoid Subscribe And Balloons Not Present Which Should Be Seen That Which States And Vinod Episode 10 200 Britain True For Not Forget About All The First Man Focus Of This To Deceive Was Stored in Top to Bottom Fashion Suvva Reddy By August 2018 Come Into Squares 121 Bottom to Top Fashion Developed for Us And See Who Wins Silver To Do Not In Line With Which You Can Change Anything I Decided To Bring With You All The Best Can Simply Stored But The Record Date For Dividend Will Be Amazed When They Get From Root On Thursday That Thing And Joe President Switch Like It Is The End What It Is The End Should Return True And Till The Bone Neither Question Is How To Start The Previous Which is the answer is Visto rating list for every evil and character and values ​​in this month from right to left character and values ​​in this month from right to left character and values ​​in this month from right to left and they can see from NDLS to the start of the turning point where in the world and also it is Edward Witten true if you don't mind Character Visit in Forbes List Serial Gautam Worth His Processing Units Very Least One Looter The Elephant Ride to Win and the World of the Method of Loss The Character in To-Do List Play List From the Character in To-Do List Play List From the Character in To-Do List Play List From the State Will Update The Character of President Rule Only Tempered Glass Return Forms Will Continue To Rule The Romantic Position Widening Simply Return Forms A Time In Space Complexity Per Preprocessing Us Of Him Into And Where Is The Number Of Boys Square Length For Query Mathematics Of Them Where Maximum Day To The Prime Example Quotes App And You Can also find and according description below the more questions you to the molecular concept yadav this question also thing try chat start the video to lenovo thank you for watching my video please like share and subscribe latest na inquiry thanks for the video
Stream of Characters
satisfiability-of-equality-equations
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`. For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`. Implement the `StreamChecker` class: * `StreamChecker(String[] words)` Initializes the object with the strings array `words`. * `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`. **Example 1:** **Input** \[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\] \[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\] **Output** \[null, false, false, false, true, false, true, false, false, false, false, false, true\] **Explanation** StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]); streamChecker.query( "a "); // return False streamChecker.query( "b "); // return False streamChecker.query( "c "); // return False streamChecker.query( "d "); // return True, because 'cd' is in the wordlist streamChecker.query( "e "); // return False streamChecker.query( "f "); // return True, because 'f' is in the wordlist streamChecker.query( "g "); // return False streamChecker.query( "h "); // return False streamChecker.query( "i "); // return False streamChecker.query( "j "); // return False streamChecker.query( "k "); // return False streamChecker.query( "l "); // return True, because 'kl' is in the wordlist **Constraints:** * `1 <= words.length <= 2000` * `1 <= words[i].length <= 200` * `words[i]` consists of lowercase English letters. * `letter` is a lowercase English letter. * At most `4 * 104` calls will be made to query.
null
Array,String,Union Find,Graph
Medium
null
263
Hello friends today I'm going to solve liquid problem number 263 ugly number in this problem we are given an integer n and we need to find out if the number is ugly or not an ugly number is a positive integer whose prime factors are limited to 2 3 and 5. so uh for n the value could range from my negative to positive right and here we are given that ugly number is only positive so we from this we know that if the number is negative we are going to return a false if it is positive we are going to see if the prime factors are only limited to 2 3 and 5 if yes then we are going to return it true else we are going to return our false now how could we see if the prime factor of an integer is limited to only 2 3 and 5. okay let me just explain you here so suppose we have a number um six we know six are the prime factors of 6r 2 and 3. we also know that uh talking about those factors six and one is also a factor of six right but six is not prime neither is one for any number to be prime um the number should only be divisible by 1 and itself so 2 is only divisible by 1 and 2 3 is only divisible by one and three and um in case of one is only divisible by one right so it is only a single value so uh for any number to be prime it should be divisible by 1 and itself which is a total of two different numbers so that is why one is not a prime two and three are Prime and in case of six we know um six is not a prime because it is divisible by itself by one by two and a three which is equals to total number of four factors right now um so how could we find the factors how could we see if uh the prime factors of 6 are limited to two three and five only it should not be and it is an or basically it should be limited to two it is either two or three or five only and nothing else so what we are gonna do here is we know six uh is divisible by two so we see if the remainder is equals to zero if it is equals to zero which means that we could divide six by two right so when we divide 6 by 2 um it returns some value which is equals to 3 here which is equals to three now three is no more divisible by two right because the remainder is not equals to uh two so next what we do is we try to see is it divisible by three yes it is divisible by three so next in turn um we divide three by eight three which means the number uh n by 3 and then uh the value we've found was one now one is not divisible by two one is not divisible by three one e is neither divisible by five but uh from this example we could see that one is a prime one is an ugly number because uh its factors are limited to two three and five only so uh since we encountered a value one in our next step um that is when uh we will return a true so we are going to return a true when the value is equals to 1. else we are just gonna return false now let's see in case of another numbers of big numbers suppose it's 40. we know 40 is divisible by 2 right um so what we do is we divide 40 the new value becomes equals to 20 again 20 is divisible by 2 the new value becomes equals to 10 again and the new value becomes equals to 5 since 15 is also divisible by 2 so we keep on dividing by 2 as long as it's not divisible by 2 which means that one of the factors itself is two so far we found one of the factors which is to next Factor next value we found is 5 which is not divisible by two we try dividing it by three and then we see that it's not divisible by three as well because the remainder is not equals to zero so next we try dividing it by five it's divisible by five right so the final uh when we divide it by five we get a value one and since um the value 1 is an ugly number so we return Our Truth ultimately we are going to return true if the value is equals to one if not we are going to return of false let's try to coat this value so since we only uh ugly numbers are only positive integers we are going to return false if any value is less than or equal to zero is also not a prime number why because any uh value 0 divided by uh 2 is also equals to 0 divided by 3 is also equals to 0 divided by 5 is also equals to 0 and 0 divided by 7 which is a prime number seven is a prime number is also equals to zero so basically zero has infinite factors so which means that 0 also has factors prime factor is not limited to two three and four through two three and five so that is why 0 is not an ugly number so if we found zero or negative number we are going to return false because it's not an ugly number else what are we gonna do is while n is divisible by two um we are gonna update n equals n divided by two also while and is divisible by three octave and cosine divide by three again while n is divisible by five um we are gonna update and okay so basically I can do this operator here close to two and finally um we are going to return true if and equals to one right if n is equals to one we are going to return to else we are going to return of false let's run our code great let's try multiple test cases uh let's add one from our side as well hmm and some random value okay so the time complexity um why did that happen let me just check for all of these okay what's happening if n is less than equals to zero I'm gonna return false right here so what's causing the problem foreign I need this thing here great let's submit the solution
Ugly Number
ugly-number
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_. **Example 1:** **Input:** n = 6 **Output:** true **Explanation:** 6 = 2 \* 3 **Example 2:** **Input:** n = 1 **Output:** true **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Example 3:** **Input:** n = 14 **Output:** false **Explanation:** 14 is not ugly since it includes the prime factor 7. **Constraints:** * `-231 <= n <= 231 - 1`
null
Math
Easy
202,204,264
1,379
hi guys welcome to algorithms made easy today we will go through the question finding a corresponding node of a binary tree in a clone of that tree so we are given two binary trees original and clone and given a reference to a node target that is present in the original node the clone tree is a copy of original tree and we need to return the reference of the same node in the clone tree note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree so here we are given that the number of nodes in the tree is in the range of 1 to 10 raised to 4 and all the values in the tree are unique the target node is a node from original tree and is not null so in this problem we are given that the nodes have unique values but if you see the follow up it is given that can you solve this problem if repeated values on the trees are allowed now let's see the various approaches and the idea behind the question so let's take this example so here we are given two trees one is the original and the other is a deep copy of the original tree the target is the value from the original tree which is three and now we need to locate this target value in this cloned tree and return the target node from the clone tree so now one thing that we know is we need to do a tree traversal while comparing the node with the target so we'll traverse both the trees simultaneously and compare wherever we are getting the node in the original that was the target and if we get the same node we return the corresponding node in the clone tree so now comes the condition for this case we are given distinct node values in this case we can compare the value of the node and the target while we are traversing but for the follow-up we are said that follow-up we are said that follow-up we are said that what if the values are repeated in that case instead of comparing the values we would be comparing the node itself so now the main thing that is left for us is tree reversal so what are the approaches for tree traversal recursive and iterative in both of them we have bfs and dfs in dfs it would be a in-order pre-order or post order a in-order pre-order or post order a in-order pre-order or post order traversal while in bfs it would be a level order reversal we have covered all these traversals in detail in our tree data structures series and you can find the link to that in the top today we will be solving this question recursively by using an inorder traversal i'll give you a placeholder wherein you can plug any other traversal method that you want and the code will still work so let's go ahead and code it up so first of all we'll take two variables that will be at a class level and that would store our target and our result node in this method we will do this.target in this method we will do this.target in this method we will do this.target equal to target and we'll call in order on our original and cloned at the end we will return the result now this is the placeholder to place your reversal method so here since we are using the inorder recursive traversal let's just write the function so now if original is not equal to null we'll do our traversal and since here we are using inorder we'll go from left root and right so first what we do is we do an inorder on left then we process the root that is if both of these are equal the result will store the clone node so this is our desired node if not we go to right so that's all let's try to run this code and we are getting a perfect result over here let's just try to submit this one and it got submitted so here we used in order traversal which takes a recursion stack because we are using recursive method and so the space complexity over here would go up to o of h that is the height of the tree and the time complexity would be o of n that is the nodes present in the tree other way to solve this would be by using iterative method that would not take up your recursion stack but then it would require some kind of stack or a queue of one solution for this problem would be morris reversal but in this question we cannot perform the morris reversal because we are not allowed to change any of the nodes and in morris reversal we are supposed to change the pointer so that we can save the space so that's all about the question and how we can solve it and what not we can do with this question hope you guys liked it see you in the next one keep learning keep coding you
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
reconstruct-a-2-row-binary-matrix
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree. **Example 1:** **Input:** tree = \[7,4,3,null,null,6,19\], target = 3 **Output:** 3 **Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree. **Example 2:** **Input:** tree = \[7\], target = 7 **Output:** 7 **Example 3:** **Input:** tree = \[8,null,6,null,5,null,4,null,3,null,2,null,1\], target = 4 **Output:** 4 **Constraints:** * The number of nodes in the `tree` is in the range `[1, 104]`. * The values of the nodes of the `tree` are unique. * `target` node is a node from the `original` tree and is not `null`. **Follow up:** Could you solve the problem if repeated values on the tree are allowed?
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Array,Greedy,Matrix
Medium
1711
962
um hello so today we are going to do this problem which is um which is uh maximum width ramp so here we are asking that we get an array of numbers and we want um there is a pair right um we call a ramp a pair of injs such that J is bigger than I and the number at position I is small or equal than the number at position J and for this ramp we call the width of a ramp basically the difference between the indices so J minus I and the goal of this problem is to find the maximum width of a ramp and the list of numbers and if there is no ramp which is going to return zero okay so for example let's see this array so the largest the maximum the ramp with the maximum width is from 0 to 5 right because you can see here I is more than J and the number at position I which is position one here is smaller equal than the number at position 5. so to get the ramp we just do J minus I and that gives us 4. so that's the main idea here now you can see we have up to 10 to the power of four elements so that tells you we can do something that tries all the possible um maybe all the possible let's say sub arrays and takes the one with the maximum width that's not going to pass it's going to give us 10 to the power 4 it's going to be N squared so it's not going to pass so how do we tackle this um okay so how do we tackle something like this so the array is we have an array for example the first example like this and usually the shape of an array like this one where it's not sorted it's going to be something like this where we have a smaller element bigger one another smaller maybe something equal bigger right it's going to be something like this the shape of the array right um and bring this over here okay and so what can we do well the main idea here that we can pursue is that if we go right to left right in these positions what matters for a position like this one what does matter well what matters is the elements to the left that are smaller than it right and the furthest possible is better okay so in this case um it's either this one or this one right because this one let's say this is the okay and so how do we do something that helps well the I if we maintain sort of track of the decreasing elements right then we should so this is for example in this case this is five we are at five so if we had maintained the decreasing element to the left then we can tell that the smaller the um the smaller one like the furthest one that is smaller than 5 is going to be zero sixes doesn't qualify because it's bigger so what we can how do we do that then well what we can do is maintain a stack in this case a monotonic one where it's a stack of decreasing numbers right and so in our case here what we'll do is we'll do a first pass to just fill up this stack so okay and then after we do the first pass to fill this decreasing number stack we can just go right to left and for each position right just take the top one because the top one would be smaller because this is a decreasing um stack because the decreasing stack would be something like so and it's visibly it's like something like this in a stack so we just look at the top one and we get the difference and then we pop it off look at this one and get the difference in popular okay so let's apply it on an example and see what we mean here um the key idea though is we only care about these points for this one only the points that are decreasing and actually this one if I just clarify which one is let's say this one is like this that in this case we only care about this one and maybe this one because it's smaller right so how do we accomplish this well we can just go copy this first and let's create our stack so our stack will just go left to right and so first we'll put six and then we will go 0 is 0 smaller than six yes so we can put it eight is bigger than zero so we don't add it two is bigger than zero we don't add it because remember we want a decreasing stack okay because if we add 2 here that's useless because for any element to the right if it's if 2 is smaller than it's then 0 is smaller than it and it's always better to take zero because zero is further to the left so the length would be bigger so the width would be bigger so it's not useful at all to have this two here because there is something already smaller than it however it's useful to have seven because what if we to have this six because it's further to the left because what if we had seven right then it's better to have the range from this here to this here because 6 is smaller than seven so it's better to have this range than just this range okay so that's the core idea so we have our stack we go to two we don't add it one is bigger than zero we don't add it five is bigger than zero we don't add it seven is bigger than zero we don't add it so at the end we have Auto decreases stack that contains the smaller um elements okay and so now we can do another pass right to life in this case so we copy this let's do the now our right to left pass so we can remove these move this um okay we don't need this okay now so for our right to left we go here first right and we look in the stack to see the top we first check the top one right so what we do is we of course have our best ramp so far which is initially zero okay and then we check so this is zero one two three four five so what we want to do is we want to check the top of the stack the element at the top of the stack which is in Python just minus one we want to find one that is smaller equal than this let's call this maybe J because that's the constraint we need to find an i to the left that is small or equal to J because that's a valid ramp okay so if you find one in this so if the one on top of the stack is smaller which in this case 5 0 is smaller then this is a valid ramp and so we want to do it while it's the case so um in this then we just update the best with the difference so that would be Max of best and the difference J minus I so here what's the J minus I well it's 5 okay what's the um here instead of putting the values let's put the indices because that's what we need here to get the difference so the index for six is zero the index four zero is one and that doesn't change really the comparison here because when we take the top of the stack we just get it as the index and get the element using it so we just do stack minus one okay and we apply to a or two nums to the array to get the elements right so it doesn't change much um okay so 5 minus 1 that gives us four so we update the best with four and we pop off this one now you may say why pop it off because then when we're exploring one if you pop it off you can't use it anymore well that's okay because when you get to one right either there is a solution with six then it's equal maybe it would have been bigger but if there is a solution with zero then this solution is smaller than the one with the previous element so it's better to take this one and so we don't actually even need to check for this Solution that's why we pop because we already have a better one and remember we are looking for the max so that's why we can pop it okay um and now um four we popping this off so let's just remove it we are remember at and then we check again is the top which is six small or equal to five no and so we move to the next element we are going right to left remember right to left so this is for J it's going to be from n minus 1 to 0. and so when we go here is the element in the top of the stack which is six that's more equal to one no so we move we continue moving so now we are here is two smaller equal to six no eight however is more equal to six okay and so we check what's the G minus I well it's going to be the index of 8 is G and the index of the top of the on the top of the stack that's zero so this is two so it's not bigger so we keep it as there is and then we pop it off right because remember here this is J minus the top of the stack that we pop off okay and so now at zero there is nothing in this stack so um so we don't need to do anything here there is nothing in the stack so we stop and so our answer is four okay so that's the idea we keep track of the smallest elements to the further left right if we find one that is even though it's small but it's um there is a smaller element to the left and then it's better to only have that smallest element because then we would have a larger ramp right or a larger width ramp okay so that's why we keep track only of the smaller ones okay so zero is the last one because there is nothing smaller than it and once we have those we just go from left to right from right to left right and for each one we just get the if it's valid with the top of the stack we get the width um and then we keep going and that until the end and that's pretty much it now in terms of time complexity both of these are going to be of both of the loops right they want to fill the stack is going to be oven and then the one to get the best is also in aggregate going to be oven so overall it's going to be oven time and since we are using the stack so it's going to be open space as well um yeah so that's the idea now let's implement it and make sure it passes um okay so let's implement the solution we just saw in the overview so um we have we need a stack right so this one is going to contain maintains indices of values decreasing order uh from let's try so we will go through the array let's just have the light here and I'll just rename this to a because it's easier um so it's going to be something like that and this in the range of n we'll check if um if our stack doesn't contain anything or the latest one right is bigger than the current element then we can add the current element because it would be in decreasing order which means basically the previous element is bigger which is exactly what we have here except the stack contains indices so we need to get the value so in this case we want to append I and now we'd have the stack so let me actually just show you the stack on an example to make sure it's easy to understand um and here let's just return a placeholder and you can see for example for this year it's going to be just six and zero so the indices 0 and 1 right and so that's correct now we need to go through right to left okay and then we want to check if while we have a stack okay um and the element in the stack is we need it to be smaller that's the property for the ramp is we need it to be smaller than or equal to the current to the element at position J because remember what we are looking for in the stack is the leftmost bound all the develops most in the interval um so that well that's the case then first we want to record initialize our best ramp width and so it's going to be just the max of that and the ram puts for this one from this J and what's the I is just the element at the top of the stack and so let's just pop it up okay and then at the end we just return that best and this in aggregate is going to be at most oven because once the stacks stack is empty we'll no longer call this and this low prance is just four n times at most so if we submit this it does pass right so I think this is a useful this is a very good problem to practice on especially for it's a good application of monotonic Stack um because here we maintain a decrease in stack here um and yeah that's pretty much it for this problem please like And subscribe and see you on the next one bye
Maximum Width Ramp
flip-string-to-monotone-increasing
A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`. Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`. **Example 1:** **Input:** nums = \[6,0,8,2,1,5\] **Output:** 4 **Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5. **Example 2:** **Input:** nums = \[9,8,1,0,1,9,4,0,4,1\] **Output:** 7 **Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1. **Constraints:** * `2 <= nums.length <= 5 * 104` * `0 <= nums[i] <= 5 * 104`
null
String,Dynamic Programming
Medium
null
884
foreign welcome back to my channel and today we are going to solve a new lead code question that is uncommon words from two sentences with the help of python so the question says a sentence is a string of single space separated words where each word consists of only of lower case letters a word is uncommon if it appears exactly once in one of the sentences and does not appear in the other sentence given two sentence S1 and S2 written a list of all the uncommon words you may return the answer in any order so guys just before starting to solve this question please do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so there are two strings S1 and S2 and we have to check for uncommon words in both of these strings and if there are then we have to return them in the form of array so we have to check for uncommon words in both of the array and both of the string and then we have to put it in an array and return that array so now we are going to solve this so first of all I will just concatenate this I will just add these two arrays so that will be my S 1 plus so if I return S I will be just getting the whole thing here foreign okay so what my Approach would here be that I will just now split s is equals to s dot split so that I can just convert this whole string into an array and now I will be just converting this whole string into an array and that two that I will be getting this apple sweet this Apple is SAR so all these in my s here but uh all these uh eight words are in my array here and in my list here that is my S now I will just create new empty array in which I will be pushing these values or appending these values so for that I will just say that for word in set so if I take set as that means that I cannot use the word twice here so I will be getting all the distinct value here now because I have taken set here because say I do not take repeated value so it will take only distinct value now I am getting I will be getting only uh this is a sweet start I will be left with five bits here now I will say that uh if word sorry s dot count word is equals to one then unstart append that word so I'm just saying that if the count is of what is 1 in s here then just push that value in my word or append that value in my word if I return it now written as I will be getting it I will be getting my answer finally so see I have been I have got my answer here and this was only the thing we have to do here the first of all we have to just concatenate these two race and then we have to split that so that we can get it in a reform and then we have to create an empty array in which we will be pushing these values and we have created a loop in which I have said that forward in set s so set is the key thing here and then we have use a function of python that is found that will count the number of right number of the frequency of the word so it counts the frequency of the word and then if the frequency is equals to 1 then append those values inward and the printers word into my arms and then return that so that was all in the question guys hope you have understood it and if you still have any doubt ask me in the comment section so I hope you are liking my tutorials on a lead code question which I have been solving with python and hope you will subscribe to my channel thank you guys for watching the video and see you next time
Uncommon Words from Two Sentences
k-similar-strings
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
String,Breadth-First Search
Hard
770
1,799
hello guys welcome to deep codes and in today's video we will discuss liquid question 1799 that says maximize score after an operation so guys solving this question you will learn a new concept of using bit masking for memorization purposes so yeah guys stick to the watch the complete video and make sure to like And subscribe to our Channel so here you are given one Norms item and an array that is a of size 2 into n uh where n is the number of operations you can perform okay so let's say if you can perform an operation then the num's address size would be 2 into n further what is the ith operation in the ith operation we chose two elements X and Y then we try to calculate the score is nothing but I into gcd of X and Y and then we remove X and Y from the nums and then again calculate the score of other elements right so here by doing this we need to return the maximum score after performing n operations and this the series nothing but the greatest common divisor of X and Y all right so the question is pretty much straightforward that we need to choose uh some elements X and Y wisely that's that way it written the maximum score at the end right everything depends on choosing the characters X and Y okay right now if you take a look at the test cases or the examples so here there is only one option to choose X and Y these are limited X and this is why or this is X and this is y so yeah this is uh the straightforward here because we have only one pair of elements for X and Y so we find Y into because this is the first operation so 1 and the City of one and two so answer is 1. now guys if you look at this example to get the optimal answer we have to choose these two pairs so let me show you so we have to choose three six in one pair and the other pair we have we will choose four and eight right in the first operation we will choose this and second operation we will choose this so first operation is 1 into gcd of three and six second operation is 2 into G serial three and four and eight so it is three plus eight so overall answer is eleven this is the maximum answer you can get so now what if you did one into gcd of three and four if you did like this plus 2 into gcd this is deciding of ah six and eight if you did like this what would be the answer same now 1 into gcd of three and four what is the greatest common device of three and four it is nothing but one plus two into the series of six and eight what is the greatest number that divide both six and eight it is two so this is 1 plus 4 so this is 5. so this way you will get answer 5 but if you perform in this way if you choose 3 and 6 and 4 in it you will get the best possible answer that is 11. so guys uh the whole question lies in choosing X and Y efficiently that's how we will get the maximum answer got it now similarly in the third example if we will choose a 1 and 5 here then we will choose this 2 and this four then 3 and 6 this is 3 and this is 6 here and yeah this is the first this is the second and this is the third operation we sum them we sum all this and get the answer 40 and this is the best possible answer here okay so guys the complete problem uh revolves around choosing the two elements if we choose two elements wisely then we will get the maximum answer and yeah in each ith operation we are performing this choosing two of elements calculate the score remove X and Y so remove X and Y from now that means this is nothing but uh calculate remaining score this is nothing but to calculate remaining score okay now since we have choices we can think of recursion okay yeah we can think of recursion so if you would perform recursion then it would be something like this so for an example if you have some elements A B C D E and F for uh so first let's say we took a and b in the first step so we get this state cdef are remaining see we get a and we choose a and b and we calculate some answer now the other answer or the remaining portion will Define our answer total answer right so yeah we have to check what elements are that we picked and what are the remaining elements we have to keep track of this right then only we would we can yeah we can take care this is the set of elements that is remaining and we have to pick from them so we have to make sure what the elements are already picked and what are remaining so we have to keep track of that so let's say we choose a and b this is the remaining A and C we can choose a and d a n e a and F so likewise we can choose B and C up till E and F right so there are many choices here okay and each choice will result in some other remaining set right this if you choose a and b remaining as CDA ANC the remaining is b d e and f right so yeah this way the recursion will work but at some point let's say from this state if you choose BND the remaining state is enf if you choose B and C the remaining state is enf now you will see that there will be repeated state so this state is repeated two times now is it efficient to calculate the answer for E and F each time no it is not efficient so since there is a repeating sub problems right we choose one uh one sec then is the remaining set we choose one set that is remaining set so this remaining set of elements is repeated that means it is nothing but repeated sir problems and guys as you know that whenever we have repeating sub problems in the recursion what we do is we choose memorization that means we will calculate only once for this enf and then we will directly use the answer that is already calculated right we won't calculate uh for this repeating sub problems like E and F for each time we will calculate once store it in our Dynamic DP atom and use that answer everyone okay got it so yeah this is how recursion will end up in creating repeated sub problems and then we have to introduce memorization now for the memorization part two things we have to consider first is keep track of remaining elements right and store the answer this is nothing but dprm so first we can think of how we can keep track of the remaining elements let's say we choose a and b then we need to keep track what are the remaining elements okay so for that considering uh that we can either use a Boolean atom so let's say Boolean Adam if you are given N1 up till n 6 that is six elements we can create what Boolean area that is that will store true false so here this Boolean array something like this it will represent the two elements are chosen four elements are false that are not chosen right so something like this we can keep track of Boolean array that will operate in bigger of one time complexity because we can choose an element and make let's say make visited of N4 equals to true that means uh we have marked the N4 element as chosen so that this operation is nothing but takes we go of one time but this array will take bigger than space complexity right because since this is an error so yeah and we need to keep track of all n elements so yeah it will take bigof and space complexity okay so if you would use mass then it will take big of one time as well as big of one space complexity now many of you uh might have a question of what is mass let's say uh if you want to represent an element Phi in binary then what is it is 0.01 that is four plus one this is y 0.01 that is four plus one this is y 0.01 that is four plus one this is y okay so this is a binary representation of Phi now let's say uh you and you are given one atom let's say you are given one add a of size let's say size six size equal to 6. so initially what is the mask all elements are not chosen so let's say this is the mask okay so this is nothing but zero now let's say at some time t equal to at some point T okay just assume at some point T you Choose You will choose element uh with index one and you will choose element with index three you will choose one element with index one and index three so yeah here what we will do is we will Mark that index as one so starting from the right zero one two three zero see this is what ah the binary order binary of all zeros is nothing but zero in decimal now binary of this is one zero what is this it is two plus eight this is 12 right now let's say at some point t Dash you can say you will choose all element right at some point all the elements will be chosen so what is this representation in decimal it is nothing but 2 to the power 6 because there are six elements so by masking what we can do is we can take uh one integer so what integer we will take some huge integer let's say 2 to the power 6 4 here we took 2 to the power 6 okay now from here e to the power 6 how many elements we can keep track one two three four five six elements we can Track by changing their bits there are six elements we can track right we just need to track whether the element is selected or not whether the value is true or false so if you took a decimal number 2 to the power 6 in that you can keep track of six elements so yeah guys here we just need to keep track whether the ith index is 0 or 1 so first all the six elements we can keep track right either the idle number is zero or the beat is zero or one right for all these six elements we can keep track whether the number is chosen or not taken or not so guys that's why we can use mask here another thing see what is the maximum number of Beats present in the mass it can be 32 or for an integer maximum number of bits uh is 32 for an integer so we have we can you choose we can store 32 different uh numbers that are chosen on 32 different indices of number right from 0 to 0 index up to 31 index we can store in integer size of bit inters are size of mask okay because we had 32 bits here for an integer so we can choose the state whether the element is chosen or not for 32 different elements that is from index 0 to 31 right so that's why we can say we have 32 options for 0 and 1 integer or true and false zero and one or true and false you can say now here the given M or the size of the norm side is less than equal to 14. if you guys check the constraint the N is 7 the total number of operation and the num's length is 2 times of seven that is 14. so guys this 14 is less than equal to 32 it is less than equal to 32 that means here we can use mask right we can simply use mass and reduce the space to be go of one instead of you using the Boolean area we can reduce the space to make over got it if this uh size of the numps item if let's say m is a is equal to let's say 18. so let's say sorry n is 18 that means 18 operation so nums uh size would be nothing but 18 twice of 18 that is 36 so in this case we won't be able to use integer size of mass because we have 36 different possibilities and integer size of mass has can only store 32 bits okay so that is 32 different possibilities so guys in this case we won't be able to do this but since here the maximum different possibilities or the size of the nums item is 14 so yeah we can use Mass to store this thing whether the element is taken or not whether it is true or false right so this is one thing to keep track of remaining Elements by keeping 0 and 1. second thing we need to also do is store the answer for the DP atom inside the dprm now what is what would be the size of the DP array right is equation see guys let's say here if you have one 14 times 1 right now what would be the decimal representation of this 14 times 1 it is nothing but 2 to the power 14 right so our DP address size would be nothing but 2 to the power 14 this would be the size of our DPL so this would be the maximum size of DP right this would be the maximum size of DP error needed right and 2 to the power 14 is nothing of some value like 16 000 it would be somewhat greater than 16 000 this value so we can easily store this many a value or in this DP array that means we can easily create the DP and of size this right it is easy this won't take much space so yeah guys by combining all these things by using mask by using the size of the DP area that we have calculated and understood by using all these different concepts let's move on to the coding part and see how we will solve it ok so initially I two kids I to M that is the size of the nums order I gen generated the maximum mask value what is the maximum value of the mass that is nothing but ah 2 to the power M so in the binary or by using bitwise operation that is left shift we can perform two to the power in this way there is one left shift M times we created this DP area of Maximum mask value uh comma minus 1 that is stored the minus 1 inside is DPR and this call this all function now inside this wall function we took for the base condition if the count of operation see here we are taking mass count of operation DP at as well as the norm Center mass count of operations and they both are changing variables now for any for instance if the count of operation is greater than n see how many operations you can perform that is a normal size divided by two these many operations you can perform and if the total count of operation is greater than equal to n that means all the uh all the operations are not done so in that case we would return 0. nothing is remaining now if there is an overlapping soft problems that means a sub problem is already calculated and thus DP of mass is not equal to minus one then in that case directly written DP of mass or the store value inside this DP now then we took maximum score and these two for Loops now inside this for Loop we are taking the value of first number I in the second number J okay we will check if the mask of I is already one or not so for an example let the current value of mass is this okay let's assume the current value of the mass cases this is the current mask okay now let's say I is nothing but ah first index so I is nothing but 1 here okay now we have to check whether the nums of I or the first index is chosen or not how we will do that we have to check whether these elements if this is zeroth Index this is first second and third whether this element is one or not we need to check how we will do this what we will do is we will do 0 1 0 we will right shift I number of times that means if I is 1 we will right shift one time so what would be the value of I is here I equal to one so what would be the value of this right shift it would be 0 1 right 0 1 then what we will do with this value we would take B2 as n with one that one is nothing but zero one we will take B2 is n with this one and by performing B2 as in if you will get one that means last bit of speed is 1 then that means the ith index or this bit is one right we have shifted and moved to the last position and but and we took between with the last position see all would be zero because it is B twice so this one and zero it's zero and zero to zero it all would be zero but since this is one and one bitwise and with one is one so we will check that mass right shift of I number of times and then taking bitwise and with one whether it gives a result one or not if it gives a result one that means the number is already chosen all ready selected or you can say chosen or you can say pick already picked then in that case we would continue and don't process for that index I got it right this is how this right shift operation takes uh place right it shift all the bits right towards the right I number of times and then if this condition doesn't satisfy then we will choose it I and we will try to select different J now we will start the loop for J from I plus 1 up till M and we will also check for this J for the same condition if that number of J is selected or not if it is not selected then what we will do we uh we would try to calculate new mask so for that same original mass is this for and let's say I is no is three and let's say J sorry I is 0 and J is 3. so this zero index was in the second index and third index now what we need to do is we need to mark this is one as well as this is one because we are selecting these two I and J so what we will do here is we would uh do 0 1 0 bitwise or this is bitwise or which what one this is nothing but left shift one left shift I number of times so I zero so we will take one here this would be zero and again take B twice or one left shift J number of times so that means one zero so we will take bitwise or of all these three numbers this is zero and our answer would be one see this was the original Mass this is the new mass that we produce where we select the zeroth index as well as the third index element so guys this is how the new mask is formed where the ith index and Z index element is marked as chosen right they both have one now so they initially they both were zero that means they were not bit now we are picking them and we are marking them as true that means there's two elements are chosen so guys this is how new mask is formed then we calculate the current score is nothing but count of operation plus one multiplying the gcd of num so fine Norms of J and the remaining score is nothing but the recursive uh that we answer that will we will get from recursion that is solving for Norms the new mass count of operation plus one and the DPI and we will keep track of Maximum score that is nothing but maximum of Maximum score and the current score plus remaining score this is the current state right so if we will take maximum of both of them and store in the maximum scope and at the end return DP of mass is equals to maximum score so guys I hope you have understood that how we are performing this beat masking or how we are performing this live shift right shift marking the element is uh chosen or Not by Shifting the bits and taking a mask element must of it so yeah this is this was all about this question now here we are performing gcd right but we can what do one thing we can optimize this thing by pre-computing can optimize this thing by pre-computing can optimize this thing by pre-computing so in this approach what I did is I pre-computed gcd of all I and J pre-computed gcd of all I and J pre-computed gcd of all I and J combination right of all inj compute combination we pre completed and I directly use the CD of our inj instead of calling the built-in method gcd of calling the built-in method gcd of calling the built-in method gcd I pre-computed and directly added gcd I pre-computed and directly added gcd I pre-computed and directly added gcd here right gcd of inj right so this will say a bit of time complexity here right instead of calculating CCT all times I pre-competed calculating CCT all times I pre-competed calculating CCT all times I pre-competed and directly use the city of ing now guys talking about the time space complexity so for this above approach the time complexity here is let's calculate so how many different states are there the different possible states are nothing but 2 to the power m because where m is the size of this non-sider so This many different state non-sider so This many different state non-sider so This many different state for each time we are iterating for M Square we are using n square that means two inner for loops multiplied each time we are also calculating this gcd this will take log of 10 to the power 6 right because this is the maximum element we have so it will take big log of 10 to the power 6 maximum time so this is the time complexity for this approach number of State for each state we are calculating this right and the space complexity here is nothing but 2 to the power M because that size of DP array we are using here to do the power M that means this is left ever m is the size of the norm side now here since we are pre-computing this now here since we are pre-computing this now here since we are pre-computing this will take save a bit in our time complexity and our new time complexity would be say it would be M uh M Square because pre-competing will take big of uh M pre-competing will take big of uh M pre-competing will take big of uh M square plus how many different states 2 to the power M into M Square because for each state we are again taking two inner for loops so yeah this is our new time complexity and the space complexity would be 2 to the power M for this DP area and uh what would be the size of this gcd this DCd would be nothing but a of a size M Square so this would be our new space complexity so yeah guys that's all for this video if you guys have still any doubts then do let me know in the comment section make sure you like the video and subscribe to our Channel thank you
Maximize Score After N Operations
minimum-incompatibility
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array. In the `ith` operation **(1-indexed)**, you will: * Choose two elements, `x` and `y`. * Receive a score of `i * gcd(x, y)`. * Remove `x` and `y` from `nums`. Return _the maximum score you can receive after performing_ `n` _operations._ The function `gcd(x, y)` is the greatest common divisor of `x` and `y`. **Example 1:** **Input:** nums = \[1,2\] **Output:** 1 **Explanation:** The optimal choice of operations is: (1 \* gcd(1, 2)) = 1 **Example 2:** **Input:** nums = \[3,4,6,8\] **Output:** 11 **Explanation:** The optimal choice of operations is: (1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11 **Example 3:** **Input:** nums = \[1,2,3,4,5,6\] **Output:** 14 **Explanation:** The optimal choice of operations is: (1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14 **Constraints:** * `1 <= n <= 7` * `nums.length == 2 * n` * `1 <= nums[i] <= 106`
The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
null
314
and welcome back to the cracking fang youtube channel today we're going to be solving leap code problem 314 binary tree vertical order traversal let's read the question prompt given the root of a binary tree return the vertical order traversal of its node's values ie from top to bottom column by column if two nodes are in the same row and column the order should be from left to right so if we're given this binary tree here the answer that we want to return is going to be what so the first column is going to be 9 so that's going to be 1 and then the second column is going to be 3 15 and then the last uh the next column is going to be 20 and then we have one more column seven here so basically we want to return all the values in each of the columns let's see how they got this solution well we can see that this is one column and remember we want to go from left to right so we can see that this is one column here this is another column and this is another column but how exactly are we supposed to solve this question well what we're going to do is we're going to be smart here let's pretend that the root can be considered as the coordinate 0 comma 0. so if this is zero comma zero then when we go to the left what are we doing we're moving the x coordinate to the left by one and we're going to be increasing our y coordinate by minus one so this can be considered the coordinate minus 1. cool so to go to the 20 what do we do well we moved our x coordinate by 1 and we also decrease the y coordinate by 1. so this coordinate can be considered as minus one oh sorry one and minus one so now nine doesn't have any children so we don't need to explore any further but twenty does so again what we're gonna do is we're to you know figure out the coordinate of this 15 well remember going to the left we subtract 1 from the x coordinate so this then becomes 0 and its y coordinate is going to be minus 2 since we've moved down another level and in this problem the y-coordinate doesn't matter there's the y-coordinate doesn't matter there's the y-coordinate doesn't matter there's actually another leak code problem which is basically the exact same thing where you're going to use the y-coordinates to you're going to use the y-coordinates to you're going to use the y-coordinates to sort your values but in this particular question the y-coordinate doesn't matter question the y-coordinate doesn't matter question the y-coordinate doesn't matter so all we care about is really the x-coordinates x-coordinates x-coordinates now for the seven again when we go to the right we increment the x-coordinate by right we increment the x-coordinate by right we increment the x-coordinate by one so this can be thought of as what uh 2 and you know minus 2. so that's the coordinate now we can start to see that we can group things based on the x coordinate right and if we did that and we maintained some sort of map where the key was the x-coordinate so where the key was the x-coordinate so where the key was the x-coordinate so all the points that start with zero let's store them in a list and we're going to say okay we have this value 3 here because that's at you know when x is zero we have three and then we have you know 15 and then we have okay minus one and then we have uh okay so that's that value nine and then at the coordinate one we have what we have the 20 um we have 20 here and then at the coordinate two for x we have you know nine uh sorry seven it should be seven okay cool but you know this isn't in the correct order remember that we wanna return our answer from left to right so what we want to do is all those values will be in our dictionary here and what we want to do is we want to return the values from left to right but we have to keep track of what you know the leftmost column is and then the rightmost and then we can go through our dictionary and basically pull the values out so it'll be in the correct order so if we somehow knew that minus one was the leftmost column and then minus two sorry two is the rightmost column we could iterate through you know the range from minus one to two and extract our values that way you know we get minus one so we'd see the nine which is the first thing then you know what's next zero so we see three fifteen and then one we see this 20 and then 2 we see the 7. so we'll have to keep track of what the minimum you know x column is and the maximum is so that way we can iterate through our dictionary here which is storing the values and we're going to be populating this dictionary as we go along so this is the general approach that we want to solve that we want to use to solve this problem now let's take it to the code editor and i'll show you how to actually implement this and solve the problem okay we've gone over the explanation as to how we might solve the problem but let's actually write the code and hopefully things will be quite clear on how you're going to solve this problem the first thing that we want to do for pretty much any tree based question is to handle the base case and basically that is what happens when the root is null here we see that we want to return a list of lists as our result so that means if the root is null we should just return an empty list so we're going to say if not root we're simply going to return an empty list now we need to define the data structure that will actually hold our result remember from the diagram we're using a map where the key was the column and the values was a list of the node values for every node in that column so let's define that so we're going to say level actually we're going to say column items equals to collections dot default dict and we're going to use a list here cool so we've defined our map data structure where the key will be you know the column number and then the value will be a list of items which is basically where we're using this list for in the default dictionary now to do this traversal we need to touch every single node in the tree and we're going to use a level order traversal here although you know we're not really going to be iterating through level by level we just need to touch every node so this i guess should just be you know standard breadth first search through the tree so we're going to use a q here so let's define our q data structure so we're going to say i'm going to define a double ended queue here and we're going to assign it with what we don't want to just put the root in here if we were doing a breadth first search remember that we need to keep track of our column position so we know how to populate our column items dictionary so let's instantiate it instead with a tuple and the first item is going to represent the x-coordinate of our current the x-coordinate of our current the x-coordinate of our current node that we're working with and then we're going to put the node in there remember that we start assuming that the root is going to be the coordinate 0 and every time we move to the left subtree it would be equivalent to subtracting 1 from the x coordinate and also subtracting one from the y coordinate right because we're moving to the left one and we're moving down one with the y this problem in particular is the medium version of this question where you actually don't need to worry about the y coordinate there is a lead code question that you do need to take into consideration the y position of each column value but for this one we don't need it so we're not going to worry about defining a variable for that we're just going to worry about the x's because that's all we care about so we have that and then we also need a data structure to hold our results so we're going to define a list here to store the result we're going to do a standard breadth-first search so we're standard breadth-first search so we're standard breadth-first search so we're going to say while q we're going to say the x-coordinate and we're going to say the x-coordinate and we're going to say the x-coordinate and the node that we're working with is going to be whatever we pop from the front of the queue so we're going to pop left from the queue and we're going to say column items and i can't spell today column items for that x we're going to append the list of values for that column the node.val values for that column the node.val values for that column the node.val cool now what we need to do is we need to check whether or not our current node has left or right children so we're going to say if no dot left then we need to append to the queue the left child and we need to tell what its position is since we're going to the left we said that would be the equivalent of subtracting 1 from the x so we're going to say x minus 1 and we're going to put node.left and we're going to put node.left and we're going to put node.left and we're going to do the same thing for right so we're going to say if node.right we're going to say if node.right we're going to say if node.right we're going to say q dot append and we're going to put x plus 1 because remember moving to the right is x plus one in terms of the coordinates and we're going to put node.right going to put node.right going to put node.right cool what we want to do here is go through the entirety of our tree and actually there's one thing that i forgot that i should mention now remember how i said we need to iterate through our column items map to basically return the answer from left to right and the way that we were going to do that is we were actually going to track the value of the minimum x column we've seen and the maximum x column and then we're going to iterate for in that range so to do that we actually need to maintain what the minimum is and the maximum is so we're going to say min x is going to be float infinity and we're going to say max x is going to be float negative infinity and then here after we've appended the values we can simply say min x is going to be the minimum of the current minimum x and we're going to say max x equals the maximum of max x and x so that way we'll always have this min and max x available to us for the next step so once this while loop ends we know that we finished the breadth first search and we basically populated our column items but now it's time to return the answer in the way that we want it which remember is from left to right in the column so it should be 9 3 15 20 and then seven so let's do that we're going to say four level in range from min x to max x plus one and remember it's plus one because ranges are not inclusive at the end point so we need to use that last endpoint so we need to do plus one on the end uh what we're going to do is we're simply going to say res.append we're simply going to say res.append we're simply going to say res.append we're going to extract from column items whatever the values for that column is um let's see column items of level and we're going to append it to our result and at the end all we need to do is simply return our result let's submit this and double check that it's going to work and it does cool so let's talk about the time and space complexity so we are performing a breath first search through our tree which means that we need to visit every single node and we need to do some operations here none of these operations are anything but constant time operations so that means that our entire time complexity can be summarized as big o of n because we need to go through the entire um tree here touch every node and then you know update column items but that happens in constant time so we're not adding any extra you know space here uh time sorry uh so it's gonna be big o of n on the time space wise we need to basically store all the values of our tree in this column items um so at the end you know this is gonna be a big o of n operation because we're going to end up storing all the values of our tree and nothing more so time wise it's going to be big o of n and space wise it's going to be big o of n and that's how you solve binary tree vertical order traversal this is the first of two questions on leak code that does um this exact same thing the second question does take into account the y coordinate this question does not so for that question which i should have a video for sometime soon we will be solving it and actually taking into account the y coordinate there is a little bit more nuance to the solution and it is a little bit more complicated but for this one luckily it's quite straightforward and pretty easy to solve once you see that you need to basically treat the root as coordinate 0 and then going to the left is you know subtracting 1 from the x and then going to the right is adding 1 to the x and that way you can group your columns by that x coordinate and that will give you the columns so if you've enjoyed this video please like comment and subscribe and check out my other videos if you're preparing for an on-site interview happy coding
Binary Tree Vertical Order Traversal
binary-tree-vertical-order-traversal
Given the `root` of a binary tree, return _**the vertical order traversal** of its nodes' values_. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from **left to right**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Example 2:** **Input:** root = \[3,9,8,4,0,1,7\] **Output:** \[\[4\],\[9\],\[3,0,1\],\[8\],\[7\]\] **Example 3:** **Input:** root = \[3,9,8,4,0,1,7,null,null,null,2,5\] **Output:** \[\[4\],\[9,5\],\[3,0,1\],\[8,2\],\[7\]\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
102
257
hey what's up guys Nick white here I do tecnico do stuff on twitch and YouTube solving all the code hack rank problems explaining the algorithms people are confused people are like how do I do this what does this code mean I'm here to explain the code it's all you got to do it hopefully it is a good explanation compared to a lot of the people that are slow boring please like and subscribe by the way if you can this is 257 binary tree paths an easy problem great this is a very good introduction to DFS depth-first search introduction to DFS depth-first search introduction to DFS depth-first search right tree problems are really good for mastering BFS breadth-first search and mastering BFS breadth-first search and mastering BFS breadth-first search and DFS depth-first search this is given a DFS depth-first search this is given a DFS depth-first search this is given a binary tree return all root to leaf paths okay so a tree is just a bunch of nodes and a tree looking structure right so the top has one node and then it's a binary tree so this is the structure of an tree node right so each node has a value like 1 is a node this is the root node the first top of the node is the root node it has a value of 1 and then it has a left in a right Chuck child right now the left child is to the right child is 3 right so a binary tree can have 0 1 or 2 children so if it has no children the left and right will just be no if it has one child either the left or right will be no one of them will be null and one of them won't be null right and these that you know the children just point to other nodes right so this is the root and the leaves are the ones at the bottom the leaves are the ones that have no children a leaf is a node with no children says it right there didn't even notice that okay so this is the leaf you know this is a leaf right so we want to find all the root to leaf paths return all the root to leaf paths so like one two five in one three and we want to while we find these we want to put them in a string with arrows I don't know why they have that going on but you have to do that maybe if some would have been easier but that's fine so to do this a root to leaf path DFS isn't the best solution here I'm sure you in most of these problems you could either do DFS or BFS you can choose either one of them right in this one I would say do DFS because root to leaf is just DFS that's the definition breadth first search is known for going level by level so you do one then you go to three then you go the next level in the next level right DFS is all the way down and then back up and then a different path all the way down it's depth-first while you know it's depth-first while you know it's depth-first while you know breadth-first means level by level breadth-first means level by level breadth-first means level by level depth-first is all the way down to the depth-first is all the way down to the depth-first is all the way down to the leaf and then you know back and then all the way down to leave right okay so we're gonna use depth-first search now I we're gonna use depth-first search now I we're gonna use depth-first search now I have this question on my live stream when do you use a helper method you use when you have a structure you want to pass in I would say as a parameter and you don't want to modify the original function right so we have this original function we take in the root node right so the root could be null right so we're gonna return this list of strings so let's just start setting up our list of strings so the list of string is going to be called result this is what we're returning right so this is going to be a new ArrayList it's just a basic list it's gonna have all the strings of the paths and this what we're gonna be returning so down here you can just write return results that's what we'll do and we're gonna have a helper method that we pass this in because we're gonna pass it in over and over again we're not gonna modify the structure of this and do the recursive calls DFS is a recursive method so we're gonna just make a method right we're gonna say public void we're not gonna return anything we're just gonna modify we're gonna pass this in and modify it the result so we're gonna pass this into a helper method we're gonna do something add the strings to it and then at the end it'll be modified and we'll just return it back in this method right so this is gonna be called DFS and it's gonna take this tree node it's gonna take a Trina we're gonna take a current path string so current string or current path I'm gonna call it current path and then we're gonna take in that list of strings results so we taking a result and we'll modify it down here right so each node we hit so we're gonna start at one each node we hit we're gonna add it to our path string so we're going to c1 and then we're going to see two we'll add two to the string and then we'll see five and we have to add the arrows as well so basically what we're going to do is we're going to set current path plus equals a arrow and then also plus equals the value of the node sono da Bao so that's gonna be what we're adding every time we do this recursive call right so we get first of all the route could be not right the route could be null so we want to check against that if root is null we just want to return an empty array right if root is null return result there's nothing in results there is no strings and results so we return result there's no paths there's no route there's no if there's no route there's no tree so there's nothing to traverse there's no paths right now what we're gonna do is we're gonna make our string current path that we're gonna pass in red string current path is going to be equal to sorry inna jerk to string of root dot Val right so we're just making a string of the number the route right so we're gonna start it off then note the root node is going to be the first thing in the string each time so we're just adding that to the string right so we had one to the string right so we just add one to the current path right if root down left is equal to null meaning there's no children it's just the root we're just gonna add this to our output so and then we're gonna return result right so root dot left is equal to null and root dot rights is equal in the hall meaning there's no children then we're just gonna say okay result dot add current path because it would just add that one note to the strip that would be the only path so just add that to the result and then we'll return it otherwise so we're gonna have these conditions if root dot left is not equal to null then we're gonna call our method on route table left we're gonna pass in our current path and we're also going to pass in result and we're gonna do this for the right node as well that makes sense so we call this as long as there's children nodes we call this method on our right and left nodes so we call this on two and three so we start going down the paths we can go down right so this is how you know as long as they're not all we got on the past we pass in our string they already have the root note in it and now each time we're doing recursive calls each time we do a recursive call we're gonna add the arrow in the nodes value until we get to the leaf so when we get to the leaf that'll just be okay if root Eric if node dot left equals null and node that rights equals null then we've hit a leaf and what we can do is we can add that string because we've been building this current path the whole time so we'll do a result I add current path and then we'll return we're done we've hit it so when we hit three on these recursive calls we're gonna finish the current path out all the arrows it'll do arrow plus three like in this case we're gonna look at okay one right we make a string of one right that's and then we make our call and then it's one arrow three okay and then there's no children for three so it'll do result I add one arrow three so result add some one over three and it returns and then it returns result boom you know what I'm saying so and then the only other thing is you just do these things again it's the same thing down here before you do the recursive calls you just want to make sure that the nodes have left and right children so if no dot left is not equal to null and no dot right is not equal to null then we pass in no dot left and we pass in and that's it so you just keep calling you calling all the possible paths it'll do every path with the root starting in the string and yeah that's pretty much it you know 100% that's pretty much it you know 100% that's pretty much it you know 100% hundred percent this is DFS so it's recursion if you don't understand recursion you might want to learn it a little bit more before you do DFS because it's all recursion so it just calls you know what I mean one gets out it's it like for the other side one gets added to the string right one is the string and then it passes in the left side so left it calls on the left now left node gets passed in two so current path plus equals arrow then two so one arrow to so far is it that is a to have children yes so you go down here it doesn't call on the left side because there's no note calls on the right side five so then it does one arrow to arrow five and then it adds it to the result so one over two or five get and on the right call it would have added one arrow three and then it has both of those in the result and we were turning the result when we come out that's it we submitted it's all good DFS check out BFS I'm sure there's one in the discussion there's also other implementations of DFS I think this one's pretty straightforward let me know you guys think thank you for watching please like and subscribe once again I'm out here with the green screen hopefully I'm not covering up the code easy problem good for DFS there's a you know Tung tree problems get your tree problem ah thank for watching and I'll see you in the next video alright peace
Binary Tree Paths
binary-tree-paths
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,null,5\] **Output:** \[ "1->2->5 ", "1->3 "\] **Example 2:** **Input:** root = \[1\] **Output:** \[ "1 "\] **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `-100 <= Node.val <= 100`
null
String,Backtracking,Tree,Depth-First Search,Binary Tree
Easy
113,1030,2217
213
Hello everyone welcome to me channel questions playlist video number are going to come ok before starting some speech or motivation 23 ka six math pass ok have you daan n kitna shikha kitna group hai aapne IF YES Cup it up if you know your style go 6 more men don't take tension friend 6 months will pass sir I couldn't do anything there is nothing like this even 6 months and children of this monastery rise up from the air if you work so hard then no one can rock you Okay, you can apply cup talking hard, so thoughts on IT, D Motivation part of mine, you can also follow these two pages, I am available on Facebook and Instagram, I post some motivational things there only, I am okay and you will know that In DP concept, we were working on 1D base DP and we had done all these questions and boat, its reconstruction was also bottom up and we had done the constant space solution of Hyderabad in video number seven. Today's video number comes. Okay, that's why I am saying that it is okay to watch the Consonant Special Solution of Robert Hadar Hyderabad Tu One, it is in video number 7, it is there, watch the video, so today's video is nothing, simply the code of Concern Space of Hyderabad is here. We are going to do it, okay, so in Hyderabad, you have read this question many times, the question is not meant to impress, okay, we will solve it today from the conference space, okay, so you will definitely remember the question, okay? The only thing that was there in house number was that brother, the first house was connected to the N-1 house, so if you steal in the first house then you connected to the N-1 house, so if you steal in the first house then you connected to the N-1 house, so if you steal in the first house then you cannot steal in the last house right and if you steal in the first house then If you have n't done it then you can steal the last house so it was something like this h1 h2 s3 dot if it was like this then it was told in two parts right h1 if you stole then no - will right h1 if you stole then no - will right h1 if you stole then no - will go till 2 only if h1 is not stolen s2 If you steal from N-1 then it is good that N-1 can also be steal from N-1 then it is good that N-1 can also be steal from N-1 then it is good that N-1 can also be stolen from. Okay, so these two are the ones who used to put a Howard rubber band in it. Put one on the holder in it. Put one in this also. Thoughts, the same thing has to be done in this too, that is, it must be of one. If the code comes then you can write any code of Hyderabad, okay then remember one is in space, right in video number 7, then just code it from D on every side, different cases are visible, the code from this one is here. Do it for house number 2 also, okay, look at it simple, you know what is the question of house number, you both know it, I will tell you the story again here that how to write the code, you will understand it completely. It will be clear well. Okay, sir, if we see the code line by line, then let's write a very simple code. Just like writing a story. Okay, did you know that both the cases will come in House Robot 2 ? What was one or the other? If you ? What was one or the other? If you ? What was one or the other? If you take a house of 1, you can steal up to N-2 houses take a house of 1, you can steal up to N-2 houses take a house of 1, you can steal up to N-2 houses and if you don't take a house of zero, if you take a house of 1, then you can steal houses up to N-1. take a house of 1, then you can steal houses up to N-1. take a house of 1, then you can steal houses up to N-1. How was this two made and if you are okay with it? Let's do something, first of all, friend, we know that if N = 1, that means there is only one house, then = 1, that means there is only one house, then = 1, that means there is only one house, then nothing else, just by stealing from that house, we will get evicted, then what will we do, the cheapest will be the expensive house which has the most money. They will take that return, they will steal from it i.e. the name is sub zero take first home, we have stolen from the first house, if we have stolen from the first house, what does it mean then we will send, either leave the name, now we are taking the zeroth house. If you are there, then you can steal up to N-2 houses. Okay, can steal up to N-2 houses. Okay, can steal up to N-2 houses. Okay, second, what is the difference, if take note, take the first house. If the first house is not stolen, then it is very simple, which house are we stealing from, i.e. If you are stealing from the first house, i.e. If you are stealing from the first house, i.e. If you are stealing from the first house, then you can steal from the last house also. Which house is the starting one and which is the ending house? From where to where can you steal? You will start with I = L. If you select the current house If you don't steal, then you can take the profit up to its just previous house, then I will store the value of its just previous house in a private variable named perfume. Remember, we had solved this in the constant space, we had taken a private and a I had taken the previous right, now keep both of them at zero in the beginning, okay, then I will give the profit that was till the previous house, okay and if by not skipping and stealing the current house, I am late, then it is okay for the current house. I will get the money because I have stolen the current house just to the left of it i.e. the i.e. the i.e. the previous one, when we had built house number one, I had told you the same thing, so let's find out who is going to be the maximum among the two. Are you getting more money than the one with maximum skip or have I stored it in the table, okay and it will have to be updated, the current answer will be mine, the preference for the next index will be the current answer, neither here. I have given the tempo, ok, that's the end of the story and remember I told Constant that look at my final answer, Kismis is a thief, we will return the maximum among these two, but in the next video, let's code it quickly and Let's finish this, let's solve house number 2 also with constant space. First of all, as usual, take out the dot size here and put two checks here that if the value of n is one then nothing has to be done. Which house is there, one house is which and if you are there, then give the maximum of the two. The house with zero and the house with one is fine. Now after this let's see. Take the first house. It is fine. What will you be able to do in this. You are not taking the first house. Means we can do right from n1 to n-1 then can do right from n1 to n-1 then can do right from n1 to n-1 then what is the return to be done which is max a from both i.e. first house is taken and first house is i.e. first house is taken and first house is i.e. first house is taken and first house is not taken then how to get the one from both of them will be my answer ok if If you have skipped the current house, then as long as you have got the profit in the previous house, you will put it in the pref script, okay, that means, if you have not skipped your current house, then you can take the profit of its just previous head till Jashn Ghar, okay. For different reasons, if you steal a house, you will get the profit of the current house, but you will not get the profit of the one in the next generation, but you can get the profit of the previous one. It is okay and the maximum of the two will be my answer. It will be the maximum. Previous needs to be updated See you again Next video Thank you
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[2,3,2\] **Output:** 3 **Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. **Example 2:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 3 **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
Array,Dynamic Programming
Medium
198,256,276,337,600,656
36
hello everyone welcome to my youtube channel today we will see another lead code problem the problem of valid so do co so here what we have to find that we have nine cross nine uh pseudo forward and we need to find it out whether it's a valid or not so we need to find we need to have some particular logic and based on that we need to find only the field cell first logic will be the each row must contain the digit 1 to 9 without repetition each column will have 1 to 9 without repetition and second third condition we have each of the 9th 3 cross three sub box of the grid uh we need to find whether there is a duplicate duplication or not so the first condition whatever we have it's very easy how we will do for the each and every row we need to create one health map and against that we will put the element and we will check that whether we have any duplication or not for columns also we will create another hash map and we'll store that columns value and respective to that columns will check whether we have that element whatever we have in that columns let's say this is the columns right so whether we have the duplicate value this will be the value let's say 5 or 6 that will be stored based on the columns so this will be the column this will be the row and like that way uh we will store that columns and row has map and based on that key value here we can find whether we have a duplicate in each row or column but the problem is here when we calculate the grid right we have 3 cross 3 grid here we have this grid so each and every three cross three we have grid and we need to find out whether is there any duplicate or not so how do we calculate that three cross three uh elements so here the logic is what we need to do let's me let me draw this to better understanding let's say we have this uh block right three cross three block so let's say we have a one block here that will be uh this block is let's say this will be uh one and two let's say one and two this is the block so for one and two element we need to find it out this particular element where it exists in which grid in it exist and based on that grid based on that great value uh we will create the hash map and we'll uh map that value right so this will be the grid index and this will be the value right so here the grid index we need to find how do we get the grid index we know that this is the index of zero right the index will be great index will be zero and zero this grid index will be zero and one we can say like that but how we will get this value 0 1 so we can get it by divide by 3 as we have the length of this grid as a 3 cross 3 right this is the 3 cross 3 grid so if we divide this let's say for 1 and 2 if we divide 1 divided by 3 the value will be we need to take the floor like 0 and for 2 divided by 3 the value will get the 0 then the grid index will get 0 and 0 for let's say let's take another example uh let's say we will calculate this eight and eight this uh index this for this block we need to find the grid index so we'll uh see this is the 8 divided by 3 and we'll take this 8 divided by 3 so how we'll find these things let's say 8 divided by 3 is how much 8 divided by 3 is 2 and 8 divided by 3 is 2 then this grid index will be 2 and 2 right so like that way we need to find and we need to create well has map and we need to map the value and again we will uh do the same condition and we will uh create a hashmap and we will put the condition like is there any unique value is there or if there is any duplicate any duplication will return false so let's uh take a look on the coding part uh let me clean these things and we'll write the coding for this so we need to create the three has map right so for the complexity power point of view as we are creating the has map the complexity will be big o of best complexity will be big o of n right and time complexity as we are traversing a area so that will be linear time big o of n so let me create three map right so let's let rows equals to new map split calls equals to new map let blocks if we name it as a block that will be a new map will create a three separate map and now what we are going to do now we are going to traverse the number array sorry traverse the board let r equals to zero and r less than nine we have nine right are plus similarly we'll do for column let c equals to zero and c less than nine sorry c less than nine and c plus okay and now what we are going to do let's uh let's take the number right it will be more easier to understand number will be what will be the number board we have and r and c so now we will uh use a if condition if number whatever number we have not equals to a dot because the empty position we are just ignoring right not equals to dot then only we are calculating if we will calculate whether the elements are in that the three has map or not so how we will calculate let's say we have rows are if the if rows are our position in the rows map we have the value if we have the value will calculate rows r dot has will calculate the particular element like number we have or not so or we will calculate so let's say we need to give a bracket here right and here we need to give another bracket to close this for loop and for columns also we'll do the same thing right and instead of for rows we'll use the calls is that map name and that index will be c and here we have calls and here we have c and here we have the number right so the same way we can calculate for blocks also for blocks the index for the blocks what will be the index will be we need to calculate by divide by uh to calculate that particular blocks number right so here we need to divide by 3 and we need to take that floor of that particular division so we'll use this math dot floor and we'll calculate this or divided by 3 and we'll again calculate that math dot floor and we will take c divided by 3 right so this will be that for particular index we need to find we need to calculate like this way and we need to check whether the number exists or not whether we have that number exist into this particular you know into this sorry one second into this particular block or not so how we will calculate this block uh whatever number we have in the block and dot has number right so if this three condition exist of any of these if it is true then we'll simply return false because for if those conditions match then it is not a uh it is not uh sudoku right and then for earth condition what we are going to do we need to set it right in earth condition we will set that map our number and we have calls dot set we have c number right and for blocks dot set or blocks whatever we have right this condition this index we need to add and against that we'll put the value as a number and at the end what we're going to do at the end we need to return true by default it will be returned true right if that condition not match let me run this code so let's say uh what it's oh it's accepted right so it's uh it's pretty much about this problem and like that way we can add uh we can achieve that linear time complexity this the time complexity will be not linear i'm sorry uh the time complexity will be big o of n square and yeah that's it about this problem thank you so much stay tuned for more update more content related to data structure and algorithms
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
272
how's it going youtube don here in this video we're going to do number 272 closest binary tree search value so given the root of a binary search tree a target value and an integer k return the k values in the bst that are closest to the target may return the answer in any order you are guaranteed to have one unique set of k values in the bst that are closest to the target so if we take a look in this example we can see that we have a typical bst here and then we have a target of 3.714286 k is equal to 2. so whenever we see that k is equal to something and then we want to return k values automatically i think that we're going to be using a heap or priority queue but we also have to keep in mind here that we're using a bst a binary search tree so we also have to have some sort of a tree traversal algorithm in order to actually traverse it right so another thing that we need to consider is that we need to find the closest value so how do we find the closest value you might be thinking to yourself well the one thing that i'm thinking right now is what if we decided to minus our each of the root values here from our target here one four two eight six so if we do that what we're going to get is 4 minus 3.7 something is going to be is 4 minus 3.7 something is going to be is 4 minus 3.7 something is going to be i believe 1.714286 right and then let's see number two minus 3.714 two eight six is equal to um also one point seven one four two eight six all right so two minus three is one point seven four minus three is actually this is zero my bad is it yeah it's like 0.28 something yeah it's like 0.28 something yeah it's like 0.28 something i can't do mental math right now let's actually use a calculator 0.714283 is 0.285 right and then we have three point seven one four two eight six minus two is one point seven four all right and then what else do we have five so five minus three point seven one four two eight six equals two point something so two point seven one four dot and then we have one minus three point seven one four two eight six is equal to i believe that's two point seven something dot and then lastly we have 3 minus 3.714286 so that's going to be 0.71 so that's going to be 0.71 so that's going to be 0.71 right so as you can see here what are the values that we would be returning well we would be returning this and as you can see here that's exactly what we're returning here so how do we do this well what we want to do is we actually want to use a min heap taking to this uh this final value here after we subtract it and then from there we're just gonna output those values right so what do we need to do here we need to use one as a dfs you could also use a bfs but it doesn't really matter in this case as long as you're using some sort of tree traversal algorithm and two we're going to use a min heap right so now that we know that let's see how we implement that with code here so the first thing that i want to do is i want to take it one step at a time right so what i want to do is i want to create my depth first search and what we're going to do is we're going to pass in the current node we're going to pass in the target and we're going to pass in the heap right because we do want to make sure that we're pushing the values into the heap here right so if current node is none all we need to do is we're going to return since we don't need to do any type of like uh traversal or we don't have any return default value then the next thing we're gonna do is we're going to simply traverse the tree so we're just gonna keep going down and then we're going to push the values into the uh into the heap as we go along so i'll show you guys how to do that so you're going to have dfs current node.left node.left node.left which is the left-hand side first target which is the left-hand side first target which is the left-hand side first target and then heap then what we're gonna do is it doesn't really matter what order you do it but we're gonna do heat push the first thing i forgot to do is from eq import you push heat pop all right so heat push what we're going to do is we're going to take the absolute value of the current node.val of the current node.val of the current node.val minus the target right so this is going to tell us which is the min heap right now and that's going to help us get our final result right then we're also going to also pass in the current node.val also pass in the current node.val also pass in the current node.val for comparison sake just in case we get a really close value we're going to take the closest actual value the current node.value current node.value current node.value as the comparison right so if we had say i don't know i can't think of a good example here most cases is going to work but depending on let's see if we had something close like say uh two-point uh two-point uh two-point uh now i can't think of an example right now but we always want to pass in another value for comparison say so dfs current right traverse the right hand side if we can't find anything on the left hand side just like how a dfs would work and finally we're going to create our heap here we're going to call our dfs roots target keep and then lastly we're going to pop the elements from the heap with our output if you uh haven't uh watched uh if you don't really understand what's going on here i do recommend that uh you do binary tree in order traversal i believe i have one on my channel and closest binary tree value which i will do in the near future so output is equal to an empty array right and then for blank since we don't care what's in here in range okay what we're going to do is we're going to append our values to the output eat pop and what we're going to do is we're going to pop values from the heap and the first element right and rousty we're gonna return output right and that should work he pop one element should be in the list oh i'm stupid forgot that then obviously in order to prevent it from passing me in air i want to make it one argument instead of two and there we go all right and all our test cases pass and success and we see that's faster than 40 uh 88.46 88.46 88.46 our time complexity here will be o of n log k depending on if we have k elements right so if you guys enjoyed the video don't forget to hit like comment subscribe leave me a comment if you're confused about anything and i'll see you next time
Closest Binary Search Tree Value II
closest-binary-search-tree-value-ii
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286, k = 2 **Output:** \[4,3\] **Example 2:** **Input:** root = \[1\], target = 0.000000, k = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104`. * `0 <= Node.val <= 109` * `-109 <= target <= 109` **Follow up:** Assume that the BST is balanced. Could you solve it in less than `O(n)` runtime (where `n = total nodes`)?
Consider implement these two helper functions: getPredecessor(N), which returns the next smaller node to N. getSuccessor(N), which returns the next larger node to N. Try to assume that each node has a parent pointer, it makes the problem much easier. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. You would need two stacks to track the path in finding predecessor and successor node separately.
Two Pointers,Stack,Tree,Depth-First Search,Binary Search Tree,Heap (Priority Queue),Binary Tree
Hard
94,270
937
hi guys today we're gonna look at lead call number 937 we order data in log files so the problem is you have an array of vlogs each log is a space to eliminate string of words and for a short the first word in each log is an alphanumeric identifier so it says it's having our Vedic words and numeral words together it can have both then either each word after the identifier will consist only of lowercase letters or each word after the Dinan for your rule consists only after the so Butterworth's it so only this or only orders or call these two varieties of love sweater logs integer logs it is guaranteed that each log has at least one word after its identifier so we can actually use that in our yeah we can split and use the second element as the identifier and after that we order the love so that all the letter logs come before any detail of the other logs are or lexicographically ignoring any fire with the identifier used in case of ties did the digit logs should be and put in their original order returned the final or after laws so for this we can use first digit logs as our just desert logs digit and empty array and letter logs as another empty array and after that we will have the for loop for log in logs and if the log that split second element as it will have and by the way this these are the examples of it so you can see that digit logs are after and we have we don't have it high here yeah we don't have a tie here but we'll have to sort the logs lexicographically by art can art 0 an own kit and if we have another art can it'll try to sort it by let 1 or the 2 or whatever so anyways let's continue with our separating the logs and we will oh and who have to set up a function is something and if it is alpha we will just put it inside the letter log else I think I can safely use what else here this is going to go into digit logs after this for the digit logs it's fine but for the letter rocks we have to solve it you can use function called sorted you can also use rest a sort but we can use the sorted file as well and can put input letter and a key we have to put in Chuukese the powered 30 key is pretty much the ones separated left so in this case we can use log a lambda function and we can use X and we will have a cube or that have its that split and for the split function I will have the separator as a default world I am the empty space is a default for the split function but I'm putting this because I don't want to put in the next flip button the function which will allow me to enter the first which is the not key part of the log and after that we will just X does it and his face 1 and will put 0 in it and we would have to add this with the digit function which is this and it is accepted and we can submit it and it is accepted also faster than eighty six point seventy one percent the Python of course there are other ways to solve it yeah but this is pretty much how you are familiar using this sort function so in Python and I can use sorted by the first element and the second element that's pretty much how you can solve this problem okay so that's it and have anything
Reorder Data in Log Files
online-stock-span
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
Stack,Design,Monotonic Stack,Data Stream
Medium
739
1,502
hey everyone today we are going to solve the little question can make arithmetic progression from seconds a sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same given an array of numbers are returned to if the array can be rearranged to form the arithmetic progression otherwise the return Force so let's see the example so you are given 351 and the output is 2 because we can view the element as 135 or 531 with difference is 2 and -2 respectively between each 2 and -2 respectively between each 2 and -2 respectively between each consecutive element so that's why in this case we should be done true okay so let me explain with this example so three five one and uh yeah there is a better way to solve this question and the easiest way to solve this equation is that sort input array and get like a 1 C5 and then uh check the difference between other Json numbers and then if the old adjacent numbers are the same difference and then we should return true if not we should return Force and that solution should be order of n log n and then but we can solve this question with when time complexity so let me explain about that and so this is the input array and first of all uh take a Max number from input array and take a minimum number from input array in this case Max is 5 and the minimum is 1. and then first of all we calculate the difference between two other adjacent number so with this formula So Max number is 5. minus minimum number is 1. so divide so N is a length of input array so 3 minus 1. so that means the answer of this calculation should be 2 right so somebody wondering why we need a minus one so because uh so in the end so if we sold this one um we will get one oops sorry one three five right and uh so we start from one and uh the difference between one and three is a two right and between three and five so the difference is two right and the total difference between a minimum number and the maximum number is E4 right and then we start from one so we don't have to care about this number so we have to care about the we have to care the number from next and the rater so that's why uh in the case we have two number three and five so that's why um we need to um like a n minus one so accept this number so if we have like a seven nine and same thing so between five and seven is two and the seven and nine and two right so in the case uh total difference between minimum number and the maximum number is like a eight and then we need a like a so we don't have to care about the starting number so just so we need to care about the rest of number like a three five seven nine so for this phone number and that's why a total number e312 c45 and the minus one is four and so eight minus divided four is two right so it looks good so that's why uh we need to minus one here and the next we need to iterate through all numbers one by one and every time we increment two but if we sort this input array so time complexity should be an order of enrollment but I'm talking about the on solution so how can we avoid the order of energy so two about the like assault solution and I use a set and uh put all number into set and remove the like a duplicate so in this case that is not duplicate so now set three five and one and then we iterate it through from a minimum number until like a maximum number and every time increment two so that means we start from one and then every time we take the current number if current number is in set and if we don't find the current number in set we immediately return Force and then so let's begin so 7 and 9 is a example so I remove this one and we start from one so check the set so set has one that looks good and then move next so increment two so that means current number is 3 and there is a three in set looks good and other two and get a five so this is a Max number and uh 5 is in the set so in this case um we did it through all numbers so with like a same difference same differences so that's why uh in the case we should return true yeah so that is a basic idea to solve discussion without being said let's get into the code okay so let's write the code first of all look at the minimum number and I mean and already and the maximum we call Max and array and get the links of input array other n so like this in the first of all calculate the diff equal as I explained earlier so maximum number minus minimum number D by and N minus 1. and then so let's say numbers and the set and the array and the if diff equals zero so just return so check lengths of numbers equal 1. so if ranks of numbers is one now return true if not the case and then after that start iteration so for I in range and minimum and uh so we need to include the maximum so much C mom plus one oh oops plus one and then uh every time increment diff so we can't put zero here but we take zero case here so that's fine and then if current number is not in numbers in that case we imitate the internal Force and then after for Loop just we return through yeah that's it so let me submit it looks good and the time complexity of this solution should be order of n so we eat it through like a array to find a minimum number and the maximum number and iterates through like from minimum number to maximum number with the differences so I think actually n and The Eliminator constant number so that's why time complexity should be order of n and the space complexity is a order of n so we use sit and uh in case where all input numbers are unique in the case we have to put n number into a set so where n is the number of um input number so that's why in the case um space complexity should be order of n yeah that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Can Make Arithmetic Progression From Sequence
construct-k-palindrome-strings
A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same. Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`. **Example 1:** **Input:** arr = \[3,5,1\] **Output:** true **Explanation:** We can reorder the elements as \[1,3,5\] or \[5,3,1\] with differences 2 and -2 respectively, between each consecutive elements. **Example 2:** **Input:** arr = \[1,2,4\] **Output:** false **Explanation:** There is no way to reorder the elements to obtain an arithmetic progression. **Constraints:** * `2 <= arr.length <= 1000` * `-106 <= arr[i] <= 106`
If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?).
Hash Table,String,Greedy,Counting
Medium
null
89
I hope all doing good welcome to the land digitally and that today will do July recording challenge 201 shedding tears will have any posts in the record handed over media only question that and this is PM in this video medicine not very hard work You can not but as a little bit 50% s you have tour who little bit 50% s you have tour who little bit 50% s you have tour who is the question very well so that you can get how to code this question a this tube white k cancer amit bhai taking some example i am suresh pink so what is your Own Question and with Great Question is a sequence of power and every teacher is in the inclusive ranged from zero two one to that Tuli Power of and Management The First Indian Resources Page No More Than Man Skin Infections Uske The Independence of Years of Difficulties In The Work Of First And Last But Not Least Give Subscribe Because The Best That David Positive They Need Your Number One Choice After But You Have All The Beta Same Accept When In This Wave Theme 053 Top Number 10 Friends Incident Me To The Number Three And 210 Three Line 98100 Give Me The Blind Imitation Of The First And Last Year Deposit Lever 20 Means The Last Year I Have Enough First Year Bsc In db2 Service M Ki And Differences With Difference Only Of But Ooo Are You Can See Sight Se 018 Diff But Know How Will Implement This That His Son The First Point In This You Will Notice A Backup Number First Number 11 Number Is Same But Different Amir Whatsapp Se Subscribe Will See To You A Dead In Itself Will Give You For This Point Depot This point unit Vijendra in the middle of 528 you changed in the top 100 by changing with you can get from 40000 subscribe this is the cost of in super singer you want to download this app will give you or total set viewer please make a Change in the mid-1960s 512 MB make a Change in the mid-1960s 512 MB make a Change in the mid-1960s 512 MB In this today you can give you can simply amazed 08992 100 em In this changed your Pan Navamsha Ninth What you can edit on December 10 2013 [ edit on December 10 2013 [ edit on December 10 2013 Liquid and Saif Ali Khan 220 Vikram Desh OK Its With should I will give December LIC t**** change BTN DKK December LIC t**** change BTN DKK December LIC t**** change BTN DKK in this 102 number this add is encounter what we can hide in other number Vikram Bisht Yog Services December also update so what is have decided to not the and depend on 98100 Simply one this is the property of cost of but two digit 200 main one pure number also get this 09 jaye vikas bhawan and benefits am sorry for the number of but 1000 daily 200 grams sim main saudi se where chicken top and this topic this is Not The Father Question Is The Question But Not For Example Soengi Person Gone 1947 1100 Width 000 Sure Fiber Limited Click Subscribe Button next9news Room 102 December Hero And This Is 100 Seven If You Take This Is How Can Change Distance By Taking Bribe Just What Is Life Issue Hai 108 Viewer Few Have This One And Defeat A Rise In The Price Of This That The Number One Shift Edition 1008 Jis Position 2006 Disposition And Later This And Nothing Should You Have Enough To Show This But This City Will Give What Is This What Is this that the number is also 1048 will shift here the number is zero it will shift here phone number is zero eight mill just come to is a 209 inside that but inside 0 tomorrow morning but if it is 820 to or this 8909 issue atlist morning is that image will have sim number sotheby's is not changing morning fit one speed one enemy morning British changing and npt change by one you can see in Chinese 115 right just will take the right just means behavior and sweet once ride set me what Is Shiksha-Dixit Speed ​​Ek Bada Itself And what Is Shiksha-Dixit Speed ​​Ek Bada Itself And what Is Shiksha-Dixit Speed ​​Ek Bada Itself And Wick And Will Get Number Do Ki Pakke Ki Soegi Antiseptic Show All The Thing Which Have Been Check The Fast Beat 0 Number Is Not Appear In The Minds Of Idli Dabish Point To The First Channel Subscribe To Apne Solid fail will work by discus me aa i miss you like to work on that affected this than a good direction jatin ki suicidal this song guest swami the same thing like 6000 this time 10000 less hai inside 100 number one now have nine to speed 1000 Of measurement of is 108 mid-2013 notification to 96952 of is 108 mid-2013 notification to 96952 of is 108 mid-2013 notification to 96952 that the last phone number will take and address seven 7 and seven in the notification sodium flash light less five notifications and updates shoes pick less 100 that demonetization 108 speed less I think this country is hua Now it's 2006 005 so add number 69 explanation m77 34608 k something hai unbridled hair do me main aapke show hi tasty [ __ ] five th 65th at once country is gh seven difference ekedhin daily earthquake 0 ka naash to r coming notice five this 6 63 65 Unit specific award four or especially 19 this is last quotes bigg boss is hybrid it was more than that number and spiderman number 14 number 10 roti 100 ki 12345 600 switch off karo jai ho ya yaad hai 220 patti show suvidha number 2012 chudavat in total power and Means will get gate number 9 1.3 ltd ki 1.3 ltd ki 1.3 ltd ki 9000000000 will always have worked with power train number of karo ki devi hai bas tu power and means waver ki city number ki that's why does behavior essentially baat ko bhi hum because bhi hai visits hai ye Conclusion Should I force her then end in chief vice president 12818 start from north sperm 027 pass ki's struggling personality 800 do a pipe 67 in 123 take speed less food speed less 5 days sitam se porn computer 7 definition number 7 end edition launch number get in Here will come for no hour and fast number is 00054 this article does not know example so in this same it is to 100 difference of Ghanshyam Rai detail show am Just removing all things is first world war charity work in all sorts of fasting bill ok Any Day Ago When British Welcome Back Practices Question What You Can You Please Take Number And How To Change 110 Impatient They Can Get The Number Change In The Midnight You Can Get The Job But You Can Get The Number But What Is Exam Number One Number Improve Guys I Will Meet In Aim Please Comment Subscribe And Meeting For You And Your Family A Person Or Thing Is Video But Don't Have Any Subscribe Who Is He Information Advertising And One Note Specified In Obscene Subscribed Button Hot Mom You Are You Forget YOU WILL GET BACK POINT THIS ABOUT POINT ANNIVERSARY THIS TIME EVERYONE SP MAHESH TAKE CARE A LOOT
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
739
hey everyone today we are solving lead problem number 739 daily temperatures in this problem we are given an array of iners temperatures represent the daily temperatures and we have to return an array answer so what is answer I is the number of days you have to wait after the ith day to get a warmer temperature and if there is no future day which is having a like warmer temperature we'll just return zero let's try to understand using an example let's say the temperatures are 30 40 50 and 60 and what we have to return is we have to return an array let's call it answer in which I have to tell for each day how many uh like after how many days we get a war more day so let's say we are at I equal to Zer we are at zero day so we will see like when we will get a War day after 1 day we have 40 which is a warmer day so it means after 1 day we will get a warmer day same for 40 after 1 day we are getting a warmer day same for 50 after one day getting a warmer day but after 60 there is no day it means we will keep it zero so this array we have to return and the constraint given to us is that the temperature length the temperature array length will go up to 10^ 5 from 1 to 10^ 5 and this question 10^ 5 from 1 to 10^ 5 and this question 10^ 5 from 1 to 10^ 5 and this question is a very important question has been asking many companies many tier one companies uh as well okay so how we are going to approach this problem first of all let's see the brute force of this question I have taken this example a random array where every day is representing a temperature every element is representing a temperature of that respective day okay let's try to build an answer for that for 4 1 let me also Mark the indices 0 1 2 3 4 5 five for one we are experiencing a warmer day after one day for four we are exper experiencing War day after 1 2 3 days for three we will experiencing after 2 days for two we experiencing one day for 9 there is no warmer day we will keep it zero for five also we will keep it zero okay so what did I do here I iterated over each element for I equal to 0 2 N - 1 and for element for I equal to 0 2 N - 1 and for element for I equal to 0 2 N - 1 and for each value of I'm going from j = i + 1 each value of I'm going from j = i + 1 each value of I'm going from j = i + 1 2 nus1 and I am seeing if let's say aray of J is greater than array of I if any element at the J pointer is greater than I pointer it means that we have found a wmer day and what is the value that is going to be updated in the answer that should be Jus I and we will break here okay so this is going to be the Brute Force so we are at one at means zero index we'll keep on checking until we find a larger element we started with j i + 1 we found the element right away j i + 1 we found the element right away j i + 1 we found the element right away and we will be updating Jal to 1 here IAL to 0 here so J - I is equal 1 and IAL to 0 here so J - I is equal 1 and IAL to 0 here so J - I is equal 1 and when we are here when we are at I = 1 I when we are here when we are at I = 1 I when we are here when we are at I = 1 I will see J = 2 J = 3 J = 4 J = 4 is will see J = 2 J = 3 J = 4 J = 4 is will see J = 2 J = 3 J = 4 J = 4 is greater than j i = to 1 so 9 is greater than j i = to 1 so 9 is greater than j i = to 1 so 9 is greater than 4 it means J value is 4 and what will be the answer at this position J minus I which is 3 so in this way I have built this array so here as you can see we are going n sare for every element we are keep on going till we find a better element let me also try to explo elaborate let's say we have temperature like 999 so for this index for I equal to 0 we'll keep on moving till here for I = 1 we'll keep on moving till here for I = 1 we'll keep on moving till here for I = 1 we will keep on doing here for I = to 2 we will keep on doing here for I = to 2 we will keep on doing here for I = to 2 we will keep on moving till the last element so in this way for every n element we are moving around like appro approximately n times so in this way time complexity for this brute force is n into n and what is the space is just the space we are sto taking to store our answer so this n s is not going to work for us because the constraints are quite High it is going till 10^ 5 so let's say High it is going till 10^ 5 so let's say High it is going till 10^ 5 so let's say we are having 10^ 5 we are having 10^ 5 we are having 10^ 5 elements if all the elements are same in the array in the worst case we are going to make 10^ 5 into 10^ 5 which is 10^ 10 to make 10^ 5 into 10^ 5 which is 10^ 10 to make 10^ 5 into 10^ 5 which is 10^ 10 comparisons which is way too large so yeah the brute force is not going to work let's think of a better approach here uh at every position I we want a j where array of J is greater than array of I and if it is not the case we'll just returning zero so in this way let's say for every element here after that we want we only need an element which is greater than this even at two I want an element which is greater than two even at one I am bothered about the element which is greater than one so in this case we generally use monotonic stag uh monotonic stag is nothing just like a normal stack where we generally keep the items in the order so here let's say what I'm taking a same example 143 295 let's also Mark the indexes this is 0 1 2 3 4 5 so this is our approach two or you can say the efficient approach this is the temperature given to us and this is the indices here what I have to do is for every index I need to get an index J whose value is greater than I so it means if I keep the order in the increasing or in the decreasing order in this time or maybe for at element let's say this element is smaller than this element that is increasing order in the this direction so I think this might give me the answer so let's say here in this case I'm going to start my answer like my iteration from the right I have this five okay this five is at the fifth index I will see whether there is any El element greater than this or not if the Stag is empty it means there is no element after that so for five we are keeping it zero and after keeping it zero I'm also going to add the index of five here because five is the biggest element we have captured so far now what I will do is I will keep on uh keep on moving ahead we were at uh here I will be shifted here the value is N9 it means so first of all we will do is first of all we have to remove all the smaller elements from stack and then we will capture result for that I and then we will add to stack we have to follow these three main steps so here we were at four index first of all we have to remove all the smaller element from this stack so four we value is nine and here at index five the value is five so we are directly going to remove it from the stack and we will we have removed it from the stack and then we have to capture the result so here we will capture the result for I and what is the result after removing the element the stack is again empty it means there is no warmer day after index 4 so we will also keep it zero and then we will add the element which is step three it means we have added four in the stack okay now we come at the index 3 so first of all we have to move all the smaller Element no smaller element is there at index 4 we have nine so now we will capture the result for I how do we capture at this index we have a element greater than this I index so I index is 3 and the stack dot Peak is four so subtraction of those two is one it means after one day we are experiencing a warmer day now we come at three index I is pointing to three value so here first of all we have to remove like in the previous call we are also going to add this three and here we are at index two so first of all going to remove all the smaller elements index 3 has a smaller element so we are going to remove that and now we will capture the result we are at index 2 and index 4 is greater having greater element so after 2 days we are experiencing a w day this step is also done I'm point the I is pointing to one which is having value four so for index one is having value for we also added index 2 from the previous call so index one is having value four so it means all the elements all the values which are less than four we are going to remove at index 2 we have three so we are going to remove that at index 4 we have N9 we are not going to remove that so we will capture our answer I is equal to 1 and stag to top is four it means after 3 days we are experiencing a w day which is this 3 days so now we come to and also we are adding one to the stack and here we comes to the first element which is one at a zero index so first of all we have to remove all the elements lesser than one there is no element less than one and in this way we will capture our answer so answer will be 1 stack dot Peak is 1 and current element is 0o so 1 - 0 which is 1 and element is 0o so 1 - 0 which is 1 and element is 0o so 1 - 0 which is 1 and after that we will add it to the stack Zer is added to the stack okay now the iteration is over so our answer like our problem is also over we have captured the answer array for our temperatures so in this way let's try to analyze the time complexity here at like in the temperature array we like processed every element only once so in this case the time complexity is going to be order of n which is way better than order of n sare in the brute force and what is the space complexity will also go order of n so here we were able to solve this problem in the O time using monotonic stack I hope you understood the problem let's code this out first of all let's capture the length of this temperature array temperature do length and then I'm taking a array to store my answer new integer of size n and then what I was doing is I was iterating over this temperatures from right I = to nus 1 I great than equal to right I = to nus 1 I great than equal to right I = to nus 1 I great than equal to 0 iusus so I was having three steps remove smaller values also smaller or equal values because we only want a warmer day and then capture result and then push to stack because there is no element smaller to the ith element at this step so we can directly push it here and after that I can directly return my answer so to remove the smaller element while stack is not empty I'm also I also have to take a stack of iner stack new stack I'll keep it a monotonic stack and stack dot is empty while there are element in the stack and the element in the stacks are temp s do Peak are less than or equal to Temp I in that case I have to remove those element so stack do pop directly I have to capture the result if there are element in the stack in that case we will have to like do the subtraction if there are no element in the stack it means there is zero day and zero is already stored in the array so I will just check if stack dot is empty if there are element in the stack it means I can just directly store answer is equal to S do Peak minus I okay now we have to push to stack do push I okay all the three steps are done I think answer will be stored in the answer array let's try to test over sample test cases on the sample test cases it is working fine let me submit the problem it got submitted successfully hope you understood the problem thank you guys bye-bye
Daily Temperatures
daily-temperatures
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead. **Example 1:** **Input:** temperatures = \[73,74,75,71,69,72,76,73\] **Output:** \[1,1,4,2,1,1,0,0\] **Example 2:** **Input:** temperatures = \[30,40,50,60\] **Output:** \[1,1,1,0\] **Example 3:** **Input:** temperatures = \[30,60,90\] **Output:** \[1,1,0\] **Constraints:** * `1 <= temperatures.length <= 105` * `30 <= temperatures[i] <= 100`
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
Array,Stack,Monotonic Stack
Medium
496,937
1,512
Hello Everybody Welcome To My Channel It's All The Problem Numbers Of Good As Snow In This Problem Give In More Fold It Difficult For Pun Turn On The Number Of Good Example Vighn One Two Three 500 Subscribe Singh Sudhir With Two Three Four Years In These Directions 1999 From This Two Three One Two Three 600 Some Solution Cinema In Business Used To Follow Us At One Point Will Go From It From Zero Two And Minus One Number Of Element - Boy's Rule And Minus One Number Of Element - Boy's Rule And Minus One Number Of Element - Boy's Rule For Loop In Side Discharge From Will Start From Plus One Will Go To the name of the ka naam saaf i request to name of j&amp;k saaf i request to name of j&amp;k saaf i request to name of j&amp;k bank will entry bank account variable name saaf me jai hind is eng ke is business simply app dawar account par this account plus and will return software is the code of the subscribe my Like Share and Subscribe the channel Time Complexity Running Switch Off Do Hai Sometime Complexities That Sexual Space Complexity Is Just Oven Vikas Vihar Jaisi Hai Contest Account Can With Father Optimizes Page No Hai Every Number Like Never Before Getting So In This Example So Let's Move With This Number And Let's Check The First Number One To Three Live With Shyam Radhe Are Live Watch 2130 Relative Position Change Of Individual Numbers Are Not Getting Subscribe The Channel Gambhir And VC And Dasvand Subscribe Shyam Ego Joined Check Yash Is Equal To en- light Joined Check Yash Is Equal To en- light Joined Check Yash Is Equal To en- light case will update our account y z minus one ifin adhir welcome to it is equal to one will be 282 2012 - 1929 fan and 282 2012 - 1929 fan and 282 2012 - 1929 fan and subscribe the Video then subscribe to subscribe ki ranbir updating your account jail - vikas ki ranbir updating your account jail - vikas ki ranbir updating your account jail - vikas tak current j is looking how many Previously The Same Number And Vitamin A Times The Good Players Such S B C The Time Complexity This Is Running From This Algorithms For A Minute And Login Time Log In To Subscribe To Members The Soul Second Solution In The Morning Neetu Father Optimizer Time Companies Can Increase The Time Complexity More So S Vacancy In The Con Is On The Problem Solve Unadhe Only Be Stored Number White Account Number Three For New Number One To Three Live With Se 0.5 Inch Subscribe 107 151 What Is The Way Will Have All Like This With Se 0.5 Inch Subscribe 107 151 What Is The Way Will Have All Like This Quite From 012 And on which your did not just a little but will update the frequency of wave similarly they will update the three times in chief also did not know what is the currency of 12312 total number of this so let's implement his nomination first and implemented solution also Neend Account Variable Wishes Frequency Are A Souvenir Of This Country Are It A Freak And Genuine Top Hundred Of One And Will Treat All The Number Nine Forms And Just Simply Update Account It Is Equal To Plus Frequency Of Mouni Subscribe And Medium Lo Ki Nitish Compiling Mian Cutting Correct Answer Let's Media and Total Hai Next9 C The Time Complexity of Dissolution Swift Audition Diya Jis Running One for You All the Number Time Complexity of Dissolution of Time Complexity of Dissolution Subscribe our Channel subscribe The Channel Please subscribe My Channel
Number of Good Pairs
design-underground-system
Given an array of integers `nums`, return _the number of **good pairs**_. A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`. **Example 1:** **Input:** nums = \[1,2,3,1,1,3\] **Output:** 4 **Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. **Example 2:** **Input:** nums = \[1,1,1,1\] **Output:** 6 **Explanation:** Each pair in the array are _good_. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
Hash Table,String,Design
Medium
2285
1,515
what's up guys so let's solve this one five best position for several century and this problem is a little bit uh math so i mean so that's why i try to i think it's still i need to be film hope you guys subscribe to my channel so to leave your basically i mean you don't need to answer uh see all these all you need to know is there's a point so the idea is that uh there's uh some finite points on the plane and the goal is to find the mean is to go to minimize this distance basically let's find x y such that x minus x i squared plus y minus y squared and then take the square root and then try to minimize it so you need to find x and y okay so this problem is actually very interesting because the idea is that it i mean if there's no square list right then you can just solve this by just differentiating partial to the partial derivative on each x and the results will be the center of mass so in this case the answer will be the center of mass okay but if you take a square root then there's no simple rule to do this right i mean you can do a derivative but you cannot look at that derivative is solved okay so actually this is called uh this is in the wikipedia page this is called the geometric median and uh there is an algorithm that uh called this and you can use the gradient descents and uh to do this right but uh actually there is a paper uh as originally called uh it'll give you the proof basically uh yeah so let me just finish a theory and we will go to the code okay so uh the theory is that uh right this is the function that you want to do in dimension and uh you can prove that this is uh you can prove at least this function is convex okay so if f is a convex function then you can prove that f is local minimum if only if it's global minimum so basically uh that means that uh there's a global measurement for this and you but you can solve it by using the local meme okay so our idea is very straightforward it's very straightforward right you first initialize the points let's say you initially zero and then i say another four and uh you just random and you just pick four directions choose any one of them and if you find a distance if you find final distance basically this minimum function if you find this minimum function uh decrease which then you just update you just out you just update a point and you keep doing okay and the first you need to you can choose these steps to be one okay but the idea is that if you find uh if you find if there's a case that if you go one and you'll find that the answer is these four green points is less than this it's not still greater than this origin that means that you need to shrink the step also idea is that right here this is convex and you find a step start from here and picking piggy p but right but maybe in here that if you go this then these two are both larger than these right so you need to shrink the step and you just keep going and then finally you will definitely arrive the local minimum and uh another theory tell you that this function is convex so local medium will indeed give you a global meaning okay so this is the theory and once you know theory once you know it's convex function and you can solve the trivial so n is the length of position if it's one you return zero because there's only one point and you'll define distance right so distance is uh for every position you just for given x and y just calculate the distance okay so initialize the points and compute the currents and the step to be one and if step is greater than at least your first step false means that uh you didn't find a meaning you didn't find the direction that which will make it decrease and you choose the four directions and update this and you check that where these current new directions is less than current if it's less than current then the you update a small you update and uh change the change coordinates and then define have to be true that means you'll find something which is a large i'm sorry which is smaller and if it's false that means you didn't find anything then you can update your steps right instead divide by two and the return current okay so this is just the try to find local minimum but once every time you find local minimum then the studio will tell you that you find global meme i'll see you guys next videos
Best Position for a Service Centre
find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**. Given an array `positions` where `positions[i] = [xi, yi]` is the position of the `ith` customer on the map, return _the minimum sum of the euclidean distances_ to all customers. In other words, you need to choose the position of the service center `[xcentre, ycentre]` such that the following formula is minimized: Answers within `10-5` of the actual value will be accepted. **Example 1:** **Input:** positions = \[\[0,1\],\[1,0\],\[1,2\],\[2,1\]\] **Output:** 4.00000 **Explanation:** As shown, you can see that choosing \[xcentre, ycentre\] = \[1, 1\] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve. **Example 2:** **Input:** positions = \[\[1,1\],\[3,3\]\] **Output:** 2.82843 **Explanation:** The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843 **Constraints:** * `1 <= positions.length <= 50` * `positions[i].length == 2` * `0 <= xi, yi <= 100` F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2) for n >= 2.
Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process.
Greedy
Medium
null
314
hello everyone so let's talk about the binary vertical order traversal so you are given the root of a binary tree and you want to return a vertical order traversal so uh this is pretty straightforward so uh i mean let's talk about example one so the vertical treble so is that latest right and then you want to just uh this every single note in the vertical uh in the vertical notes right so 9 will be itself 3 15 and 20 and then 7 right so this is pretty much the idea right so uh let's just go to uh example two so four nine three zero one eight seven five four nine three zero one eight seven so let's talk about the idea right so how do you actually need to solve this so it has to be left to right so we have to know um uh if the order if you start it from zero right so if you go left it's going to be negative right if you go right it's going to be positive right so we need to keep track of the negative and positive and i mean we can go offset right so depending on how far away you are from the root right but i'm going to say uh column right so column value right this is going to be column zero this is going to be called a negative one right so this is my uh my note right all right so uh again i haven't talked about how i solve it so i'm going to use map right hash map so i'm going to use hashmap right so what is my key so my key is going to be integer the integer is going to represent what integer is going to represent a column right so if i didn't initialize this column value i need to initialize first then i will add i will definitely add a value 3 and 15 into my what uh into my um basically math right you can use hashmap or treatment if you use hashman then you have to sort later on right but if you use three back right you sorry right away and then this is because the integer the value the column value right we know like it's going to starting from negative to uh i mean the most negative to the most positive right so tree map will be better right then you don't have to sort it right and then how about all my uh my value my values is definitely going to be less of integer right because i need to store every i mean more than one element right so you have to be more uh at least right so again uh let's stop holding so i'm gonna finish one on my tree map but we are over here and i just have to delete something easier but i'm going to call mac right and i'm going to try this picture and i definitely need a list of this so in this video we're using a brief research idea so what do i need to pass in the route right uh let's just say root right so if the rule is as able to know the base case right you return nothing right so if you're giving the mt if you're giving the empty array right you supposed to be you should supposed to return the mt empty 2d array which is list of this right so if you say return then you need to return this right so this is pretty much the best case i all right so let's talk about how you do it in preferred search so for the professor you definitely need a cube right so what do we need to store all the queue you need to store the uh the three note right but we also need to uh store the column value right so you need to store two uh two items right so i'm gonna say class here right and this has to be i just initialize uh right so i need to create a class right here and i'm going to say go to queue and link this right okay now uh what i will have to do is i have to push which is over into the queue right now i just basically try first okay so uh if you are familiar with the preferred search you go level by level right so you need to know like this is the level you have for this current notes and then you push into the queue and then you know how many elements you have for the children then you traverse again so in this question i'm going to say here so uh i'm using current okay yes her so i will say cue that whole now i will be able to know like um oh hold on i need to know my size right so how many elements i will have to try verify so for e i zero i am less than size i plus so if i don't have this one then i would definitely get all the bone right so i would say i pull out the first one i have right then i would just say okay if i didn't have in my mac full of uh for the key right so for column right column uh current.column uh current.column uh current.column if i don't have it then i need to initialize my current column to new english something like this you can use the realistic matter so if i do have it then i just push into my map but in this one we're using the get method we get this one and then we add into the linked list right so we get current.colon so we get current.colon so we get current.colon that so now we know that we push i mean we add the first value the first node into the map and then we check the children right so i'm going to say if then i would have to push into the queue right pushing the queue but q dot over and then i need a class of appear called q right so it's going to be what uh the first value is going to be no so it's going to be minus one right so it's gonna be current dot column minus one right and this is gonna be exactly the same thing for the right this is gonna be plus places from the right and then everything else this will be here right so uh what do you need to do you traverse every single one until the end and then you hit a no then you and then you come back to the main function so once you have it you're using a tree map right so you know uh the key you're storing is a column it's a column value right so it's starting from negative to positive so i'm going to try verse um transverse what transverse like this integer valve which is meta uh value right method value so i will say this if i add that then i probably will don't have to take care of my key anymore because it's already traversed uh okay i made a mistake so okay i just made a mistake for the full up here when i push i need to appear right so here and it should be root and the current value uh or the current value should be zero rest right i just try again interesting so maybe all right so now convert so network column oh no doubt all right so many mistakes but whatever okay i made a mistake but whatever so yeah it's pretty much it right so what's the timing space so for the time you need to traverse every single one of them known right so it's going to be all the fun so preference search if you label child traversal right so all of them and then follow the photo space it's going to be it's only all of them as well so this is a bfs with a class of peer you can also use uh bfs without a class so i'm going to start it again and then i'm going to just um in this time i'm going to quickly go over it so you don't need a helper function but you need a list of lists again i'm going to call this new arraylist right so if the rule is equal to no right i'm going to return this and i'm going to use the hashmap in this time i'm not using the uh trimet so i'm going to say release i'm going to store it in the image now it looks new you know and this is zombie so the first version of the bfs uh i only have one queue but in the queue i'm using the pier so if i want to take the pier out right so in this one i'm not using the castle here right so i'm i need to store the value separately right so one is the column value the other one is what three node value right so i'm going to i'm also going to create another two variable called min and max this is going to be uh this is going to keep track of my minimum value for the columns and maximum value for of colors so when i traverse i would definitely just get the value and then search for the map right so you definitely will follow along later so q dot offer right uh i just offer the root so while q is not empty i would say 3 no not equal to what q right and then i also need to add a column right so uh in the column so column couple so this is the value for the three uh root so this is going to be zero this is going to be three right so if a map does not contain t of what color right we need to just put my column with what with the initialization for the release so this is what new now i just have to add some metal gate column i need to add what value for the node right so in this time i'm not going to make mistake then i need to check my left and right so if no double left it's not no it's not alright it's not okay and this time if not the left is not know i'm gonna just add the value right away so offer uh column minus one right and then i'm gonna push i know the left the queue i also need to update my method my minimum value with the column my son and me how about the right exactly going to be the same idea right but we're using a plus right plus max next nice all right so this is pretty much like when you try version label order right for the folder for the tree so once you finish uh in a hash map uh you definitely know uh you don't definitely have every single one of them note in the map right so i'm going to using my min and max in this time so i know the range right i listen to max plus you definitely need to include a max right because you keep out you keep updating right now we're just using the map get high because we are using the list inside my valuing for hashman and then we can return what can you turn this right so okay so yeah so in this one without the castle here it is a little bit i mean definitely a little bit long but uh the structure should be easier to understand if you use the class of p right you need a helper function and then basically you just have to think about the structure for sure all right so the last one uh dfs so dfs is hard uh in this one i'm still going to use it so again i'm going to use the tree map and i'm definitely going to store integer right so we are still going to store integer and we're using the list array i'm going to call map i have that new tree map so um for the dfs right we just keep traversing until the end and then we request recursively up going up and then we will basically store the value into my map and then i will just starting the value for the i mean definitely solar value right over here right so this one's stored for column and this one is in array right i'm going to store so sorry so this is column value and then value is one this can be that and this is going to be the offset ah sorry this is the value right all right so let's talk about our dfs customer root right i'm passing a zero percent zero so problem so if the route is actually return if you don't have it make a contains key offset method and then we will just keep doing this so what we will add the offset right so we are adding the uh the depth and then so for every single value since this is the list right link list we need to store two value then when we starting and then we push into the list of lists then you will be ordering right so i will talk about this later but whatever so this one will be easy so i'm going to traverse the left i'm going to know my depth is going to be plus 1 and my offset is going to be y minus my exactly the same thing for the right and then you're going one level deeper so it's still plus one and this one's going right is plus one right and then we come back to here and then we need to have a list of this you can call this and again you want to return this okay so i will say traverse my key set so integer once i have it right so i'm taking this all right so this is what value right and then uh in this one so here's what i mean for this so this is that zero one two right so uh i want to know like when i push into the list for this one so this is what give me one more second uh this is column zero right which is all i mean offset and then this one uh us ui in the list right but in the list you are also in a in 1d list right so in this one this is 0 3 comma and this is 2 15 right and then we have to sort based on the first uh first index in the list of uh 1d in array right so we know who comes first right three will definitely comes first right so we sort the first value so you'll come up with this order right and then we just push the value uh i mean traditional value right so this is the idea so connection i'm going to show the value and then i'm going to just do the number expression a0 minus b 0 right so list of integers right the reason why i need a list again this is because i need to push into here right so once i uh once i started right i can all traverse nonstop add right and this is bell dot get i at one the index one and then later on we just have to at least add the numbers and then i would just definitely add every single column into the list right and this is pretty much the solution for dfs and let me run it so submit all right so for the time and space for the dfs uh the time is what using a tree map is gonna be about unlocking right and in this one not only on that one because what uh when you're adding uh and then when you have to compare and then you need to go deeper so i'm just copying my timing times time space complexity so the time is only unsee log c is going to represent the node in the column in a tree and represent how many nodes so this is oliven right you traverse dfs traverse and then uh for every single time right um you either go left and right but the level of the tree is gonna be c right so we say unlock c for sure and then in this one okay in this one this is all of c i all of c and then you have what uh the rest of the value so the worst case is going to be this one the worst case is going to be this is all of c right this is all of n and this is all what c log c i think right so l c log c is the worst case so this is dfs and the space is definitely all the framework and then for the full of bfs without the peer is all of um with it's all open for the time and space right and then bfs with a width appear right we're using it we're using a tree map right so it's gonna be like something like this right and this is a solution so feel free to watch whatever you want and sorry for the mistake and i will wish you all bye
Binary Tree Vertical Order Traversal
binary-tree-vertical-order-traversal
Given the `root` of a binary tree, return _**the vertical order traversal** of its nodes' values_. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from **left to right**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Example 2:** **Input:** root = \[3,9,8,4,0,1,7\] **Output:** \[\[4\],\[9\],\[3,0,1\],\[8\],\[7\]\] **Example 3:** **Input:** root = \[3,9,8,4,0,1,7,null,null,null,2,5\] **Output:** \[\[4\],\[9,5\],\[3,0,1\],\[8,2\],\[7\]\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
102
56
and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem number 56 merge intervals given an array of intervals where intervals of i equals start of i end of i merge all overlapping intervals and return an array of non-overlapping return an array of non-overlapping return an array of non-overlapping intervals that cover all the intervals in the input so if we were given this input here of intervals 1 3 2 6 8 10 15 18 how i may merge these well we can see here that there's an overlap between these two intervals right because the two is within this interval so we can merge these two and we can get one and six then what we can see is that in this interval there's no overlap because the end of this one um does not coincide with the start of this one so these two are disjoint this one there's also no overlap between these two because obviously the start of 15 is after you know 10. so there's no overlap here so it'd simply be 8 and 10. and that's essentially what we want to do is we want to take our intervals and we want to look whether the interval that you know that we're considering if it's start is less than the end of the last interval then what we want to do is we want to merge those two and then we want to basically you know do that for all the intervals but then we also have to consider you know say we merge these two into one and six we now have to consider you know for the next one eight and ten when we're doing it we don't wanna be going off of you know two and six we want to be going off of the merged interval of one and six and that's the approach that we want to take but there is actually one thing to notice here which you know may not always be true so if you look here these intervals are actually sorted based on the start of you know the interval which is not actually guaranteed to us by this problem so for example if this interval was given to us as you know one three eight ten and then two six that would mess us up right because we would try to you know we would first try to merge you know eight into ten obviously there's no overlap so we would say oh okay well there's no overlap therefore you know we need to keep them the same and then we would get to you know two and six oh there's no overlap again we can just add it in no you would have to actually merge it back in time with this one and the reason that this isn't good is because we actually have to you know if there was a lot of these intervals that we had to merge into then we'd have to be trying like multiple places which isn't ideal and it's gonna make our algorithm a lot slower than it is so to combat this what we're gonna do is before we do this merging that we went over in the first step we want to actually sort this to make sure that it's sorted based off of that first element once it's sorted like that then we can do the processing that we did in the like initial illustration where we took the intervals and we simply merged um you know based on the end of one interval and the start of the other interval so that's what we need to do we have to accept this sort in the beginning otherwise um you know despite the fact that we're doing an n log n sort here um it's still going to be faster than if we tried to just leave it unsorted and then merge you know intervals every which way so that's the approach that we want to take and the code is actually really simple to write if this part didn't make sense then when we go into the code editor in a second you'll see what we're going to do and it's going to make complete sense to you because it's really simple so let's go over to the code editor and write the code for this problem so we're now back in the editor and it's time to write the code the first thing that we want to realize is a little bit of an edge case if there's only one interval provided to us in intervals then there's nothing for us to merge so we can simply just return intervals because there's nothing for us to do so we're going to say if the length of intervals is less than or equal to one we can simply return intervals now remember what we need to do is we need to sort intervals based on the start of each interval so that way it's in the nice order that we can work with and we can do the merging um you know without having to worry that things are not in the correct order so we need to sort our intervals so we're simply going to say intervals dot sort and the sort function will actually just do that for us based on the first element in these lists it's quite convenient that it works out that way so now what we need to do is we need to define our result so we're going to say res is going to be equal to a list which contains intervals of zero remember that we're always looking back at an interval and looking to see whether its start comes before the end of the previous interval obviously for the first interval there's nothing before it so we simply put the first interval into our result and then any subsequent intervals that we're working with we're going to check whether or not they merge into whatever is already in result because the result is going to be storing the kind of the merge state of our intervals so now we just need to iterate over all the rest of the intervals so we're going to say 4 start and in intervals starting from 1 because we just handled the very first index right this interval zero what we're going to do is remember if the current start is less than or equal to the previous interval and remember that we're putting all merged intervals into res so we're actually going to be looking into res so we're going to say if it's less than or equal to the previous interval's endpoint then we know that we need to merge them right so we're going to say res minus one which is the endpoint of the last interval that we have in our result is now going to be equal to whatever the maximum of the end the current end for our interval that we're working with and whatever its current end is oops um we're going to do that okay otherwise if there's no overlap we know that our current interval has no overlap with the previous one and we can simply just add it to our result so we're going to say res dot append and oops i'm going to append start and end here and that's all we have to do we go through all of the intervals and we're simply going to just you know do the merging if we can so basically if the current interval start is less than or equal to the previous interval's end and if it is we're simply going to just set the end point of the previous interval to be the um you know whatever the maximum of end here is or you know the previous end and the reason that we don't change the start point is remember that the intervals are sorted by start so there's no way that this start point could be before the other start point because obviously you know it's sorted by start so anything that comes after a particular interval will always have a start after it because they're sorted on the start one so we don't have to worry about changing the start we just have to worry about the ends because that part may need to be um checked okay so that's gonna be the problem let's submit this make sure that it works and we can see that it does so what is the runtime complexity of our algorithm well here we have to do a sort so sorts are always going to be big o of n log n and then we have to basically go over the entirety of the array and you know potentially merge all the intervals so going through that in the intervals is going to be a big o of n operation but because the n log n is actually larger asymptotically what's going to happen is that our algorithm is just going to run in big o of n log n um this n log n will basically trump the o of n here so oh we can basically disregard it in the asymptotic runtime complexity so for space complexity we do have this res which in the case the intervals um you know all the intervals here are disjoint so there's no overlap at all then res will end up storing basically the exact same thing as intervals which means that our space complexity will just be you know a list here um intervals which is just big o of n so it depends on how large intervals is going to be so that's how you solve this problem it's quite a simple one the code is really easy to follow um and yeah if you enjoyed this video please leave a like comment subscribe if there's any other videos you'd like me to make please leave them in the comment section below i'd be happy to make those for you guys just let me know which ones you want to see and i'll get back to you otherwise in the meantime happy coding bye
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
337
yeah so hello everyone so we are having today another problem the problem is that you need to get the maximum sum so these are all the notes that you have given that we have given a tree and we need to get the maximum sum in such a way that there will be no such parent child are connected which means that suppose you have a tree like this you need to take the north in such a way that there will be no parent-child that there will be no parent-child that there will be no parent-child relationship will be happen so which means that suppose if you are taking this you if you are taking this three this one then you cannot take this and if your if you are taking this then you can take these this there all right so these are all allowed so suppose you I'm having another one some stuff like that so if you are taking this then you cannot take this if now you have to take the value in such a way that one level I had alright so if you are going there so you don't have to take this and you need to take here so this is a quite difficult problem that people usually say but this is really not if you are having few you are in a good data structure so if you use proper data structure then it will be very easy problem so let me tell you what exactly you need to do so the problem is that so if you are taking this then you cannot take this alright and if you are not taking this then you can take this so this whole problem is divided into this step all right so what is the data what is the sum of this element this level and what is the sum of this level all right suppose say the sum will be X here and suppose here the sum will be Y here and the moment if I came up here so I need to check whether I need to add this node or not whether it is feasible to add this node or not at any point of give enough time so if you are adding this node then you have to add with Y all right and if you are not adding this node then you need to return this X but when you need to so many people say why don't we add it so but the reason is that support say X the value of x is more than this addition of this 3 plus why so that particular time you have to choose this so this is what exactly again so if you are going for a route so let me generalize this principle suppose that there are three levels here alright so let me go with this approach if you are going for this rule so the thing is that for that you need to add it or you need to discard it and if you are adding it then you have to add it with this if you want to discard it then you have to take it this so in this way that you need to do and you need to take the maximum value and so these two nodes are imaginary all right so which means that support you whatever the nor that I have given here so this Y means so this Y is equal to the maximum number that this whole subtree the maximum sum so the moment the way I'm doing it here I assume that it has done over here as well all right so I'm having this and I am having this so how do this for each element so I'm having two things 1 X the value of this child and the value of this and system in descendants so what is the value of the descender so that is y so the thing is that all I need to do is I need to add so what I'm going to do is I need to add 3 plus y what I'm going to do is I need to add root plus y which means defendant or I need to check so this left child so what will be the till here or else I need to check what will be the maximum value of this left child and what will be the maximum sum of this right child and I need to compare with them all right so let us do that all right so here it go so the base case is that suppose say so here I'm going to use 1 data I mean stl so that is called pair if you don't know it just go to Google and you can this is very simple D I mean stl so pair contains means suppose say that the way I need to write pair is pair integer from my integer comma X so this X the previously supported before integer if I'm saying X so I need to assign only one value but if I'm taking a pair I can assign this as two value so which means that suppose what I'm gonna do it as X is equal to PI comma 1 which means that so this first integer contains one fight and the second integer contain water so which made that suppose if I am giving this opposing if I am saying an integer X 2 which means that X of 0 is equal to 1 X of 0 is equal to Phi X of 1 is equal to 1 so this is the same thing alright so this is a two dimension I'm in one dimensional array so this is contained two away so this is as simple as that so what I'm going to do is suppose you this X so how to print this if suppose you I'm going to do is suppose I need to print C out X dot for if I execute this statement this will print five and if I click X dot second for that particular time it will print so this will be first and this will be second so this is first and this is second so I'm going to used it because in every sequence I need to value here or I need to take care of the descendant or the child all right with each load so this function whatever the function that I am I'm calling it suppose a fine max will return this pair for this pair so Northey their integer coma interior so this will return fine Max and this suppose say this is wrote so now if wrote is equal to null so this is the base condition the porch a fruit is equal to null so that particular time what happen though I need to return what return zero comma zero which means that if there is nothing so which means that the maximum value I will get a zero all right I'm passing I am returning this integer of pair so I need to return in this form or else what I'm gonna do a so I will for the left sub-tree err integer comma for the left sub-tree err integer comma for the left sub-tree err integer comma integer x find max I will go route left so in the same way I will go Y find max so now if you came up here so let me draw this so the moment I came up here so you can see here the moment I came up here okay so you can see here this is 4 1 5 or whatever it is so I will go to the left child here and I will go to the 0 comma 0 so X will be 0 comma 0 here X will before death X will be 0 comma 0 and Y will be 0 comma 0 yeah so this X comma y 0 comma 0 so here what exactly happening it so what I'm gonna do is approach a I need to take I will need to add this or I need to discard it but you can see here there will be no so 0 so Y hat where I did so what I'm gonna do is I will add this one and the other one is 0 all right that in the same way I will add this file and the other one issue so now this X so this will return it 1 comma 0 and y equals to 5 comma 0 now here you need to see or now you need to add this one if you are adding this then you have to add this 0 whatever the what exactly this so this is the first one and this is the first one means this is the child and this is the descendant so if you are adding this 4 so you need to add this the second one not with the first one always represent the whatever the value that you got from the child so child taking at your concentration but this you need to so what you gonna do if you need to go so this size left so this side laugh till here whatever the value that you got from this sub-tree got from this sub-tree got from this sub-tree without considering this so that you will get from here and from whatever that left right subtree that you got in the right subtree without considering this so you will get it here so 4 plus 0 so this side so you need to take if you are taking this if you are adding it but if you are removing this so what exactly is that so the first item that you are getting without till here is one all right if you are not adding this and if you are adding this roots of tree so that is one and from this right subtree you are getting this fight so you need to add them up so this is the first one so if you are adding this root then that will be for if you are not adding this so that particular time you need to find what is the maximum well value that you got from this subtree and you need to find the what is the maximum value that you got from the software you need to add that the maximum value that you got is one from this subtree and the maximum value that you got is five so total will be one plus I will be six so in the same way so here it will be 1 comma 0 and here it will go so this side you will get exit 0 comma 0 and Y will be 1 comma 0 if you want to add that so the first one will be fine and if you don't want to do that but the second one is what 1 so this side will be so if you are not adding this so the maximum that will get out 1 so 5 comma 1 if you are coming from here so now this situation is worth more clear you know so now you need to find if you are adding this then you have to add this part here for this part and you need to add this part so this whole level in it work right so this whole level is added here you can see so 6 will be odd so this left subtree that you got 1 plus 5 and from this one that you got this right subtree so in the left subtree whatever the value that you got is 6 in the right subtree whatever the value that you got here so what do you wanna but you can see here this 4 if you are adding taking this child so the left child is 4 and the right child will be fine so if your you have 2 option now you can take of this 3 or you can discard it if you are taking this up so what you gonna do 3 plus 6 plus 1 6 means what is the maximum value if you are not considering this child and what is the what is 1 the right subtree if you're not considering this right check 3 plus 6 plus 1 note is that if you are taking this if you are not taking there then you have to consider this so you need to say that what exactly the maximum one so till here you can see this still here in the left subtree you can see here if you are taking this left subtree so you are getting this for all right and if you are not taking this then you will get what 604 that the six will be the one if you are going for this you can see this if you are taking this for that particular time file and if you are not taking this in that particular time this is one so what you gonna do is if so many situations there people used to say that you can see here I am taking this six which means that I'm discarding this you know what you can see here thing is I need to take this five one so what exactly the meaning is whatever the maximum one here I need to take that it can be the if I need to go with this or I need to go with that doesn't really matter so that doesn't really matter I need to go with this or I need to go with this that doesn't really matter all right so what I'm going to do I need to get the maximum one so whatever the maximum that I need to take so six is the maximum and you can see here six I was taking from here and from five I was taking from here all right so five was taking from here so I need to take whatever the which one I need to whether I need to take it from here or I need to take it from here so that is the thing so 10 plus 6 plus 5 which is 11 which means that if I'm taking this 10 here if I am taking this 10 here then I'm making a mistake if I'm taking this 3 into consideration then so that particular time I'm making a mistake so I need to discard this so that particular time you need to go over here and you need to check right so I need to discard it so what I need to return the way I was doing here from anyway we are thinking return so pair 1 I need to return like this how I got this 10 so the first the root whatever the element that we got from the root plus second value that you are getting from the pair in the left child and the second value that you got in the pair in the right shape so that you have to get so rooted or value plus F dot second plus y dot second okay we need to say that X dot second and Y dot second so after that so this is the first value that you got this at 8:10 so you need to that you got this at 8:10 so you need to that you got this at 8:10 so you need to calculate the 11 so what you going to do is you need to take find the maximum one so for that what you're going to do maximum of X dot first comma X dot second because these two are totally different entities so if you are bisecting this so this is a separate entity so this is total separate and this is total separate okay what I am doing is I'm taking this I am taking this edge consideration I am throwing it out but what I am doing here is I am taking this as a consideration what I am doing is I am NOT considering the left child of this rope so with respect to that what I am doing I am considering the right child of it because this right child is maximum then the other element alright so which is present in the road so this will be the maximum so that is the reason what I am doing throw maximum X dot first Y dot X dot second and plus maximum Y dot first Y dot second so this is what is the thing so this is quite easy actually and if you so what I am doing is suppose I let me revise it again so what I am doing is so if I'm going for a node so what I am assuming is so till here I have calculated what is the maximum value till this node if you are taking the left and right a check consideration so for that what I'm going to do is I need to either I need to discard take it or I need to discard it what is the minimum of taking is if I need to add this with the left child well I mean the left sub-tree so child well I mean the left sub-tree so child well I mean the left sub-tree so this part and I need to take to the right this part okay and with respect to this if I am discarding it so I'm having this whole load so what I'm gonna do it so in the left subtree what I am going to do whether I need to add it what I need to discard it all right if I'm not taking it if I'm I need to add this or I need to discard it in the same way I need to add this or I need to discard it you can see here i discard here and I have take this and for here I have taken it and I discard this so this is the thing that is happening so you are the first one and the next one so this is very simple problem but if you are not able to you use these data structures or that particular time it will be a bit tough as you're thinking
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
1,282
That there is a problem of Taj Mahal loot from 122. Whom are you discussing with? So let's start with this problem statement itself, that record has to be taken on the right side. This bench is a mere 10 to 15 minutes long, I was standing in the remaining two time, first understood. It was not from Custom and Central, it was coming at the time of Science Mission. I had done the 2014 Sangh's but was not the first, so now we will see that also in this. If we made this Islamic change, then according to the problem statement, we will have the group youth in which There will be elements that Idea will definitely have to listen to the trend and put them in the group and they can have their own cyber which is Jahar Light Agarwal Pati himself, neither these three can create such a group, its size is three, it is not worthy of that. Like, now you can see that there is one, he will surrender, if I do this show of 1 hour, then the vacancy that we have life is on friends, so only one group of it was formed, although there is no one else except 11, so that group. A committee can be formed. Let's see, 3 persons here, two here and here we are among ourselves. 63 If ​​Mark is Tirtha and we are among ourselves. 63 If ​​Mark is Tirtha and we are among ourselves. 63 If ​​Mark is Tirtha and his two groups, we can form 3 minutes. Tree itself cannot be formed, so we are forming groups, we are making their index because Thing training appear in the examination group but there is a yagya that one percent can remain only in one group and according to multiple if we can do any organization and guaranteed there is a solution but it will happen think if we set in this we can see That's it Zero 12103 Landscape Three Four 1622 Groups became 6 Pimples Problem Solution of 2012 Now we did it from this year, let's see, it's okay too friendship insolation, I didn't make any extra, I just had to do it in Choli Hatana, courier That's how expectorant explains today by making one, according to this I clicked and my tip is what can I do in this, find my one in this today morning which is 12:00 to complete, today morning which is 12:00 to complete, today morning which is 12:00 to complete, make this dress and do the bar in it This will be accomplished when the enjoyment will go to its size officer but this is the three then the descendants of the three do some of these results Shivlinga came true to him during his answer is the studio put time in it a whole sir took this survey stuff in the morning marks body and doing You have given the global answer, so now I can turn it upside down. Is our group Rajasthan going till the end? Its size is that element. This is the first and also the second one. Is there any Brahmin in it? It has become one and a half inches long. It has become adverse. We have found that whatever cheap phase we have, it will run smoothly and we can search it for one second on cold power 80, we can use it comfortably without any problem and run it from one second because we only need it. If N1 is right, then I will continue to be a That's Hum group, so definitely he doesn't have the benefit of likes, he will go till Venus and loot, or will he be checking with the difference of being Hum, set a reminder, he will not do this thing at all, as it will not do, he will not do this. Which will be done at that time and it will be made and its coriander leaves will be of that size of J&amp;K and here the coriander leaves will be of that size of J&amp;K and here the coriander leaves will be of that size of J&amp;K and here the fabric will be there. Next 9 will show from the news room, so I will show it from 15x scope. While making an owl, a group was found, what will we do, we will check all the answers dot sized nickel to come that our stuff sir, which we have made, but in the beginning there was nothing in the nurses, otherwise now these people will not work that our It will not be given equal to one, so its size will not be related to zero, it will be 1.25 Sharma will go to Pooja, be 1.25 Sharma will go to Pooja, be 1.25 Sharma will go to Pooja, its index has become specific, so now what do we have in the answer, now our child said file, then what will we do and this is our Will consider that it is not there at all then it will come out of the people Okay, it will be filled with this look It is inside, it will come on this condition All this coat has been put on size It was put on that antivirus should not give feedback But if our stuff is government size If it is zero then it will not give feedback. Is there anything against Guru? Dalit society. Now if we get some feedback about our global answer broken, then whatever is there will continue and anything will happen in it. The 13 ones we take were easy, understand that too. Takes three, that's us, what will happen in the case of a triple century, when we have here, you will be free. After I3, the group size will be equipped with zero size. Third, his who celebrates with the group, his children 7. Okay, we have made a new morning. Took riders, made others, okay, made a lot of them and in this, we decided that all the elements, Jatin's quarter, coal, others also have repair things, now what will we do and this condition is not acceptable, this was the condition. But it must be going through group answer and Z10 coolness, we think they have a call to paper, but this one condition and the one inside condition, this one condition till then till me, if we increase the size of all these answers to three or more then we Till then what will I do, my Salman will do it on time, then we will have an indication, zero has come, yes then it is okay, but when he will come to the forces, it is okay here, which has happened, we have a little inductive which is needed on them. Will come on 431, whose industry will be there, saw that Arthur group size, this is your pimple but our society, government, science updated daily 123, this means we cannot make a bigger group than this, so what will we do in this, we will immediately ask our studio Ramesh and tell him Will clear the money from Salman, all these things of Salman time audio will be removed, this will be our surprise by adding it to a new group, till now both of us were tired and all the answers will be only for me, it will be free, it will be famous from 10th Jayanti. After that, he will also come to the place of religious shadow, either after that, this loop will be completed, so friends, we will see that the size of Salman Sarkar has also increased due to which the increase is three, so we have added that also. Net, this is just one more. Only our answer is Medicare Pure Healthy Dabe Quattrocchi What is the change in it if we have to do any tax on it Structure This time Shankar Its till this page I take 36th side and it is 10 If we have to make 108 representatives then I have to do only one thing This is the first one The loop is it doesn't need to be maintained it goes on in it until we have to see that our which it needs like 3m injection maximum limit because we can just start the way to limit us with up to N. If so please with which it is presented then it doesn't make any sense just we will run it mix element jaat this what I will do with it I will run it in front element in its place so I used the steel which is there 4 maths and score element equipped vacancy intact So this is what will happen, it will return the login and this is what is this road * In the place of going into this road * In the place of going into this road * In the place of going into groups of good size, there is a complete seven bar cylinder mixture, it will run till the middle of the service and for a lot of time. Comment about this from today's group. karke dikha data hoon and inventors video suraj si in the preparation pastor hai and memory usage examples for a person hai koi jaane expert fast solution hai thank you for watching this video 2018 subscribe servi and keep supporting a on do
Group the People Given the Group Size They Belong To
number-of-valid-words-for-each-puzzle
There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`. You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`. Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_. Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input. **Example 1:** **Input:** groupSizes = \[3,3,3,3,3,1,3\] **Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\] **Explanation:** The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1. The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3. The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3. Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\]. **Example 2:** **Input:** groupSizes = \[2,1,3,3,3,2\] **Output:** \[\[1\],\[0,5\],\[2,3,4\]\] **Constraints:** * `groupSizes.length == n` * `1 <= n <= 500` * `1 <= groupSizes[i] <= n`
Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask.
Array,Hash Table,String,Bit Manipulation,Trie
Hard
null
4
hey what's up everybody and welcome to coding with roby and in this video we're gonna be going over a top interview question now this question is in that hard category on leak code this question you have to find the median of a list and as we know lists can have x amount of numbers it does not have to be decided so it makes it extremely hard to find the medium because if there's an even number there's really two in the middle so you have to find the two in the middle and divide by two and all this kind of fun stuff so don't feel bad if you get stuck on this question because i took way longer than i thought it was going to take so make sure you can pause the video to read the question before continuing on to see the solution if you want and before we jump in make sure you hit that subscribe button so now without further ado let's jump into this top coding interview question hey what's up everybody and welcome to coding with roby and in this series we're going to be going over how to solve coding exercises off of leak code and in this video we'll be solving question number four median of two sorted arrays so the question of meeting of two sorted arrays is given two sorted arrays nums one and nums two of size m and n respectively return the median of two sorted arrays so we need to be able to combine two lists and find the exact middle of these two lists if it's an odd number then the exact middle number is going to be the median and if the number is even then we need to find the two numbers in the middle and divide by two which will solve for the median so in example one we can see that nums one is equal to one and three and nums 2 is equal to 2. therefore after we sort the list it's going to be 1 2 3 with 2 as the output in the median in the second example we can see 1 2 is nums 1 num2 is 3 4 after we combine both lists we'll get 1 2 3 4. therefore the median is 2 plus 3 divided by 2 which is equal to 2.5 and that's by 2 which is equal to 2.5 and that's by 2 which is equal to 2.5 and that's because the median is not a single number it's uh the two numbers in the middle added together and divided by two so this question can be pretty challenging if you're unaware of how to add two lists together or how to find out if there's a number right in the middle based on it being odd or even or if we're gonna have to divide by two so let's start by creating a new list which we're going to call added list of nums one and nums two added together now right at the top adding these two numbers together just kind of merges the two lists where nums two will end at the end of nums one and we really need these numbers to be sorted um luckily sort comes already with python so we can just say added list dot sort this will just sort the list automatically by the number since we're dealing with numbers and integers this will be very easy just to be able to sort the list the first thing we want to do is check to make sure that added list is at least equal to one and if it is equal to one then we know the median is just the first element so with this we can see that we did if the length of added list is equal to one then we just want the median and we can just say return the median so right there we have the answer if added list is only equal to one but for this problem it's probably not going to be so let's keep going and let's do an l if we're going to check the length of added list is divisible of 2 which we're going to be using the modulus to make sure that it's equal to zero so modulus is just making sure of what's the remainder so if we divide this by two is the remainder going to be zero or is it going to be one so we're just checking to make sure that the modulus of 2 of the length of the added list is equal to 0. if it is then we want to say in which is going to be the length of one of the lists is equal to the int of the length of our added list divided by two and let's also create a variable m which is going to equal the integer length of added list divided by two minus one because now we're trying to find the two elements in the exact middle and then we can say the median is equal to parentheses added list of n plus added list of m divided by 2. so this is only going to get called if there's no number directly in the middle so if there's no number directly in the middle then we need to find n and m which is going to be the two numbers in the middle and then just add them together and divide by two if the modulus is not equal to zero then we know there's going to be a specific number right in the middle so we can say else n equals the length of added list two slashes two and then we can just say median is going to equal added list of n and then return the median let's try this live so right click and run solution we're going to get two and four so we passed in one three and two so one two three and then for the next one we got four when we passed in one two three four so something slightly wrong with the second equation okay i was able to find our issue so right here on this line we're saying median equals this added list in plus added list m divided by 2. well since we don't have parentheses right here ending this equation and we had the parentheses over the 2 it was actually calculating added list m divided by 2 plus n first so let's now rerun the application and there we have it we get 2 and 2.5 and there we have it we get 2 and 2.5 and there we have it we get 2 and 2.5 on our equation that we wrote now if we want to debug this we can hop in and i'm just going to put it on the if statement debug our solution and first thing first we can move right along where we're checking to make sure the added list is not equal to one if it is we'll just return zero well the element of zero of added list we have l of length added list is a modulus two which is equal to zero which it is not so we're gonna say n equals the length of added list slash 2 median equals added list of our index of n we're going to grab the item in the middle and return that median and now for the next one since there's gonna be four elements one two three and four we know that this first if is going to be false so it's going to move on and this time the lift is going to get called because the modulus of two of four is going to be 0. so we need to grab the number right in the middle divided by 2 and the second number in the middle just one element before divided by 2 which is going to be 2 and 1 and now we want to say 2 plus 1 where we want to say 2 in 1 so the element of added list in the element of added list m is divided by 2 and then we'll return that median so again if we look through the terminal and we run this application we'll see that we get 2 and 2.5 well this wraps up the question of meeting of two sorted arrays and i'll see you in the next video
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
1,004
hey guys this is it from brevity and today we're going to look at a very interesting lead code question maximum consider ones so the problem statement is actually quite simple we'll be given a array with zeros and ones and we need to return the longest continuous sub array with just has ones and here's the catch we can change up to k values from zero to one so i'll give you example here uh consider you have an array so we need to find the length of the longest array with just us once so here in this case this array one and one has just once so this could be the longest subarray but the catches we can change up to k values from zero to one so here in this case the k is two so we can change two zeros to one so this was the original array and we are changing this zero to one and even this zero to one so a new sub array becomes zero one zero and we can allow up to two zeros to be in the array so the new length we written here is six so now let's try to implement this in python so to solve this problem we're going to use an application of the two-point use an application of the two-point use an application of the two-point algorithm known as sliding window so if you want to understand how sliding window works for this problem you can check out my friend's bigness video where he explains beautifully it should be right on top so meanwhile i'll just keep waiting so now let's try to implement this using python so the first step is to obviously initialize both the pointer so i'm having a pointer i which points to zeroth index and the pointer j which also points to zeroth index now every iteration we need to keep track of the maximum length so i'm having a variable uh mx for maximum length uh and i'm initializing it to zero so every iteration if the new length increases we are basically updating the mx variable in each iteration so as the example we saw before every iteration we are basically incrementing j pointer by one and if the number of zeros exceeds the limit here is k we are incrementing i pointed till the limit comes back to uh the k limit so the first step is to have a while loop for the j pointer so it goes like this while j less than length of array so we are do we incrementing j pointed till it goes to the last index and for every iteration we have to increment j point by one now we have to check for one condition if the new incoming value j point is pointing to zero one because if it's zero we have to decrement the k limit by one so if the new value which is a of j is zero what we're doing here is decrementing the limit by one so while we're decrementing so that if the limit comes less than uh zero so if initializing k to three and every time we're having uh zero we are decrementing it by one so every time we are reducing it and if the limit goes below zero we know that uh the number of zeros is more than what it's supposed to be so we're having we're decrementing k by one and if the k limit if k goes less than zero what we're doing here is we are basically incrementing i pointer till it comes back to normal so we can uh automate this process you can say using the loop so we can just use a while loop and if k less than 0 we are incrementing i b 1 till the k goes back to where it supposed to be so if the new value which is a of i equal to 0 we are incrementing k by 1 and we do this till k goes back normal so we're incrementing i point in this case so every iteration uh j point i point is ready so now we need to uh find the maximum length in each iteration and update it in the maximum variable so to do that i can just use a variable mx equal to max of the maximum length so far and the new lens is j minus i plus 1 so now we can just return the maximum length mx and i think that's it uh we can just run this as you can see the code runs and it's actually quite fast so now to understand the time complexity for this code so the time complexity of this code is often because j point is just moving from the zeroth index to the last index and i point is also moving from zeroth index to up to almost the last index so we're just having up to n passes uh in the loop so you might get confused because you might see two loops so you might think it's n square but no we are only going up to n iterations and the space complexity in this case is of one because we are not having any extra array or a list we're just having three extra variables in this case so the space complexity is of one because it's no matter how big the input is we always just have three variables it's constant so thank you for watching and uh stay tuned for more sliding window videos
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
1,675
welcome to january's leeco challenge today's problem is minimize deviation in array you are given an array numbers of n positive integers you can perform two types of operations on any element of the array any number of times if the number is even divided by two so if it's like four then we can make it a two if the element is odd multiply it by two so one thing to note if it's odd we can only multiply it by two one time because once we multiply by two becomes even so we can't make it bigger than that now the deviation of the array is the maximum difference between any two elements in the array return the minimum deviation the array can have after performing some optimal number of operations okay so if we had uh this example here you can imagine when it's odd i'm sorry when it's even we can divide it by two any number of times so we can make this two we can make it a one 1. let's first start off and give you a hint by assuming to start with the minimum possible values for each number so we can do that pretty easily we can just go through this entire array and if it's even we could divide it by 2 until it's odd basically so this becomes a one this is already odd it's already odd this becomes a ten five and this remains a three so these are the minimum values for each one of these elements now what about max well max is pretty easy as well if it's odd we have to multiply it by two if it's even we have to keep it so it's before it's two this would be ten this would be no this would stay 20 this would be six so what does these two things represent well basically these two represent like the range right between um whatever number we have we could go to the minimum of this number or we can go to the maximum of this number but keep in mind with this there could be any number of numbers in between like here with the 5 and 20 we have like 5 and then that can become 10 that become 20 and we can imagine this could be like huge depending on what number is given to us luckily all we can do is start with the minimum and just multiply it by two all the way up to this limit here to know what the let's say candidates are now how do we find the max deviation well like say we couldn't do any operations what would we do to find the max range well it's pretty simple right if we sorted it in order uh basically we just take the minimum value and then the maximum value and subtract the maximum value here from the minimum that's going to be the max standard dv or what not standard deviation max deviation right because everything in between doesn't really matter all we care about is what's the minimum what's the max and what's the difference between the two okay so that's good um say that we had some sort of data structure to like store this information right and what we'd have to do then is take our number that we have and find our deviation and then maybe take that number and see if we increase it can we decrease our deviation so for example with one here uh say that this was the first element we know that we can multiply by two let's pop it off and insert it back in now it's a two if we sort it now it looks like this it doesn't change right one to five still the same what about here we pop that off we multiply by two put it back in now we see that the minimum difference is actually three it's decreased and we can just continue that unt until we get to the max for all of these guys now um that sounds simple enough and that would be enough but it doesn't account for uh the limits here because what if for example we had like this example three to five if we did that algorithm just as is what we would end up calculating is two right but that's not true because we could multiply this 3 to 6 and then keep that as 5 and the minimum deviation would actually be 1. uh-oh right so why not store some sort uh-oh right so why not store some sort uh-oh right so why not store some sort of global variable then to store that max value and we can start off with five and each time we multiply by two whatever number is the minimum we will update our global max if it's greater like here with three we multiply that by two and we find that six is greater than five so now it's going to be instead of five it'll be a six and each time when we calculate our output we will take our max value and subtract it by the number that we're calculating right now which would be the minimum at that point from this data structure so if we reformulate this a little bit what we could do is instead having two lists we'll have like um a tuple with the ranges so we'll have like one and four we'll have one and two and so on and so forth and we'll use these tuples sorted somehow and there's a couple approaches you could take you can use a tree set which is basically an ordered set of some sort but that's kind of difficult to implement in python um probably heap would just be fine so we'll start as a heap having the minimum value at the top and the max uh well i guess the max minimum value at the very end and we'll store that global max somewhere just calculate the deviation each time once we find that we can no longer add any more so say that we hit our range for one and four like we took this and now it's a four and then we pop that back off and we can't go further than that now we can't add back to our heap so now this is no longer the length of nums so then we'll have to stop our algorithm because that would be the end so let's start coding this out hopefully it'll start making sense as we code it so start off by initializing our heap and what we'll do is say 4n in nums let's finish first initialize some variables the temp wash say this is the min and this is the max i'll do it let's do this and we'll say look while the start with the min while the min is even we will divide it by two all the way up into points that's not even so if this is even we can use this well we will divide it by two and continue that all the way until we get our minimum now max is a little bit different remember that if it's odd so if our max is odd then we will actually multiply it by two because that's however many times we can multiply it'll only be able to multiply it once by two if it's not was it if it's not odd then we'll just keep it the same okay so now we want to add to our heap a tuple of the minimax right so we'll add to our heap a tuple of human and the max so let's take a look at what this looks like and should that's not the same example but you can see like here our range is going to be from one to two this will be from also one to two this will be for three and six and this will be from one to four okay great now what do we want to do here okay well let's first get our max value okay we want to store that max value like i said our global max and i'm just going to go straight forward here and just iterate down the whole heap i'll say 4 inj in our heap just take whatever i is and whatever the maximum that's going to be the max at first okay and our output we could do a couple ways but i'm just going to initialize a max infinite so this would be the max possible value in python and that way we can guarantee every time we calculate the min deviation it's going to be less than infinite right all right so while what well it's not while there's a heap it's basically while the length of the heap is equal to the length of nums uh because once we find any of our candidates are out of range then we can't really go further because we have to make sure to account for every single element in our numbers okay so first let's pop off whatever is the minimum here and i'll call this x and i'll call this limit and we will keep pop off of our heap and what do we want to do well let's calculate our output so the output is going to be what the minimum between the output and the maximum that we calculated before and the x right now if this x is less than limit we know that we can just multiply x by two and reinsert it into our heap right so um what we'll do is do another heat push back to our heap take our x multiply by two and keep the limit the same because the limits gonna remain unchanged uh one thing to note though is remember that kind of weird edge case that happens with the threes and fives we're gonna have to update our max if our x times two is greater so we'll take the max of max and x times two and as soon as this is greater than the max then we'll start using that as our upper bound to calculate our output now once this is finished we can just return our output and let's make sure this works okay it looks like it's working but let's get you examples let's try this one and there we go that looks like it's working so let's submit it and accept it yeah so i used a heap um i mean technically you could use a list append it and then sort it and do that but that just wasn't didn't really seem worth it um i seen some solutions that used you know the tree set but um i don't know like it's it was more complicated than it really needed to be i think the heap is a better option so all right thanks for watching my channel and seriously do not trust me remember because i know nothing
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
59
hey everyone welcome back and let's write some more neat code today so today let's solve the problem spiral Matrix 2. yesterday's Daily Elite code problem was the first variation of this problem which I solved on the main Channel and what's interesting about this problem is it's actually slightly easier than the first one in my opinion because in this case we're given an N by n Matrix which is a square Matrix which I think is kind of interesting that this is the follow-up question and you guys know follow-up question and you guys know follow-up question and you guys know that I always say that the order you solve problems in does matter and this is unfortunately an example where I think leak code got the order wrong but let's get into it we're actually only given a positive integer n and we want to generate an N by n Matrix where we fill the elements from 1 to n squared it makes sense that we'd go up until N squared because that's how many cells we're going to have in this grid if it's going to be n by n but the trick here is that we want to fill them in spiral order of course so we do start at the top left we're pretty used to doing that and we're pretty used to traversing to the right so starting it out we can fill in the first row pretty easily one two three but then we have to start going down four five and then we have to start going to the left six seven and then from here we have to start going up till eight and then this has been pretty much one layer of the Matrix we have to continue spiraling though and we do that by from this position moving in to the grid now this was a three by three grid but I'm sure you can imagine that much larger grids can exist and our algorithm should work on any of them as long as they are square matrixes we will consider a four by four grid because I think that's about as big as we need to get to actually get the main idea here so the first thing I want to say is that this problem is tricky but it's not conceptually that complicated we know what we're trying to do it's just so many edge cases that we're going to have to deal with and a lot of pointer manipulation making sure that we like go like this we go in down left up and we've done one spiral here and at this point we move inward so this sort of becomes our sub problem we had a four by four Matrix initially but then we did the outside stuff and now we're left with just this inside two by two which is another Square Matrix so we can kind of break this problem up at a high level to just doing one spiral and then dealing with the sub problem how exactly do we Define this problem though how do we know this is what we started out with and now we have a sub problem how do we represent that well I like to do it with four pointers there are other ways you can solve this problem but I think conceptually this one makes the most sense to me and I don't have to think too much about the edge cases what I mean is we can kind of Define the current problem we're at by having a left boundary pointer which tells us this is kind of our left boundary initially we know that once we do the outer problem and we're left with the sub problem here our left pointer should probably be over here to tell us that this is like a smaller Matrix now and initially our right pointer is going to do the same thing it's going to tell us where initially here this is our right boundary so that tells us we're dealing with like this part of the Matrix but we can go one step further and get like the vertical amount which would tell us like what the top of our Matrix is another pointer for that I'm going to call it t or top and another pointer at the bottom now you might be thinking since in this case we are dealing with a square Matrix left and right are always going to be the same as the top and the bottom aren't they like as the left and right pointers move inward as we get smaller sub matrixes won't the top and bottom pointers do pretty much the exact same thing yes you're right but I think being a little bit explicit and having a couple extra variables makes things a bit more readable and for me lets me kind of keep track of what I'm actually doing because it's really easy to get confused when you're dealing with like matrixes and pointer manipulation so if you're anything like me I recommend having a couple extra variables to make your life a little bit easier and also to actually name these pointers based on what they represent a lot of people try to use pointers like I and J but I've done interviews where people get really confused with what their variables even mean halfway through like their coding solution and if you become confused it's hard for your interviewer to actually help you so try to keep things as simple as possible but at this point believe it or not the problem isn't crazy hard we know the first step is always going to be fill in the first row which row well the top pointer is going to tell us which row we need to fill in that's good now how do we know which part we should start at and which part we should end at well that's what we have the left and right pointers for right it's making our life pretty easy we start with the value one and we just keep filling two three four now we are over here so now we want to start going down so what should we do well our right pointer is going to tell us which column we should be in and our top pointer and bottom pointer will tell us what range we should go through right we should go from here to here but if we do that we're going to end up filling a 5 over here so basically what I'm getting at is once we filled in the first row we should probably take our top pointer over here and move it down by one that's exactly what I'm going to do and move the top pointer here so now we know to iterate from the top to the bottom pointer filling in five six seven next we know we want to fill in the bottom row but the complicated part is we want to do it in reverse order now that's not super complicated but it just means that we want to go from our right pointer all the way up until our left pointer but once again do not forget that we don't want to have to revisit this position twice so before we actually start going through the bottom row let's make sure we take our right pointer and decrement it so I'm going to move the right pointer over here now continuing to fill in the bottom row from right pointer to the left pointer so I'm going to say 8 9 10. now here we want to go from this position up this left most column so we want to go from the bottom pointer to the top pointer but of course not visiting this position twice so before we start doing this we're going to take the bottom pointer and decrement this one so that it's up here now from here we're going to fill in the values 11 and then 12 and this is the position where we would stop at now we have filled in one of the layers of the Matrix we've kind of solved that portion of the problem now we need to start doing this sub problem so how do we do it's actually really simple the way we set up this problem I did this intentionally all we have to do is take the left pointer and shift it to the right because as you can see we moved the right pointer we moved the bottom pointer and we moved the top pointer the only one left for us to move is the left pointer so we take this one and shift it to the left over here now we're dealing with this sub problem on the inside and at this point the algorithm just continues exactly as we did it because at this point we don't even know what type of Matrix we started out with we don't care we know we just have a two by two Matrix and our pointers tell us everything else that we need to know and also of course that we already filled in 12 values so now we're going to be continuing at 13 14 15 and 16. now very quickly I want to show you how the algorithm is going to terminate because that's important that's probably the most important part about like the edge cases here so we're going to be over here we're going to try to fill in the first row so we're going to add a 13 here then we're going to add a 14 over here now we filled in the first row so what we're going to do is take the top pointer over here and now it's going to be in the same position as the bottom pointer so now over here we're going to be trying to fill in the right column we're going to go from the top pointer up until the bottom pointer so we just fill in a single value here 15. and at this point we would do the same operation take our right pointer and shift it to the left over here and now we know we need to fill in the bottom row going from the right pointer up until the left pointer so we fill in a 16 over here and once we've done that remember once we fill in the bottom row we take the bottom pointer and increment it by one so now the bottom pointer is going to be up over here now normally at this point we would fill in this Row the left column and we would go from the bottom pointer up until the top pointer in reverse order but you can see these pointers have already crossed each other so our Loop isn't going to do that and once we've executed that portion of the code which wouldn't do anything we're going to take our left pointer over here increment it by one to the point that it's going to be over here and whenever the pointers cross each other whether it's the bottom and top pointer or the right and left pointer we are going to stop so that is pretty much the entire algorithm as you can tell the time complexity is going to be Big O of N squared because we're just traversing this n by n Matrix and I guess the memory complexity is the same if you count this as additional memory if you don't count it as additional memory the memory complexity is constant so now let's code it up first thing I'm going to do is just initialize a two-dimensional Matrix in Python it's two-dimensional Matrix in Python it's two-dimensional Matrix in Python it's easy to do it so this is going to be the row it's initially going to have a zero and it's going to be of length n so this is pretty much an array filled with n zeros and how many of these rows do we want n of them so in Python this is called list comprehension we can say four underscore in the range of n the reason I call it underscore is because it's not being you used and this is a two-dimensional n by n Matrix filled two-dimensional n by n Matrix filled two-dimensional n by n Matrix filled with zeros now we know we want to iterate over the Matrix but before we even get to that point let's initialize our pointers because that's really the most important part of this problem we have our left and right pointers they're going to be equal to zero and N minus 1 respectively and I'm going to copy and paste this because we know the top and bottom pointer are going to be the same so let's go ahead and do that and lastly I'm going to initialize the value to be one because we do need to keep track of that as we continue to increment it and the condition I'm going to use here is continue while the left pointer has not crossed the right pointer they can be equal because in the case that we have like a three by three Matrix we might get to a point where left and right pointers are equal that's perfectly fine but they should not cross each other now I could do the exact same thing with the top and bottom corner I could put top here and bottom here it will work out the same you just need to put one of those conditionals in here before I actually write any code in this while loop I'm just going to tell you exactly what I'm going to do I'm going to fill in every value in the top row after I'm done with that I'm going to fill every value in the right column after I do that I'm Gonna Fill every value in the bottom row and lastly we know we're going to fill every value in the left column and I guess it's worth clarifying that the bottom row and the left column should be filled in reverse order so I guess I'll add that clarification but I guess it's not super necessary so now we know what we're trying to do and after we're done with that we're simply going to return the Matrix now it's just a matter of writing a few for Loops now filling in the top row is pretty easy because we're kind of used to iterating from left to right so you could call this variable I but I'm actually going to call it column because I think it makes it easier to keep track of what we're doing because we're iterating in the top row but we're going from the leftmost column up until the rightmost column including the rightmost column so in Python if we want to actually include this value in our for Loop we have to add that plus one because by default it won't include this value I personally don't like for Loops in Python for that reason I find that being more explicit like in languages like JavaScript is a little bit better but oh well here is the part that you might kind of get tripped up at how are we going to fill in this Matrix remember what your pointers are doing we're filling in the top row so tell me what pointer should we use to indicate which row that we're in well of course top that tells us which row that we're in now which column should we pass in well that's exactly why I created this variable and I called it C to make it obvious for us this is the column that we want to be at and what value are we going to assign it to well just our variable up above and then after for that we should probably increment this and after we have filled in the top row we're going to fill in the other columns and rows but don't forget to take your top pointer and increment it by one because now that we've filled in the top row we can shift this guy down and at this point the rest of the solution is going to be similar so at this point we're filling in the rightmost column so we want to iterate through every Row in the range from top to the bottom row but I'm adding once again that plus one because we actually want to include the bottom row so now I'm going to have Matrix at this row and at this column the rightmost column is going to be assigned to this value and Value Plus One and after we fill in the rightmost column we should probably take our right pointer and decrement it by one this is starting to make sense isn't it well the next two are going to be a little bit more tricky not conceptually just because it's really easy to get an off by one error in Python so what we want to do here is fill in the bottom row so we want to go column by column in the bottom row we want to go from the rightmost column of course up until the left most column but we actually want to include the leftmost column so here instead of doing a plus one though we're actually going to do a minus one and here I'm going to pass in a negative 1 because this tells python that we want to iterate through starting from here up until this value in reverse order and we add that minus 1 because we actually want to include the leftmost value we minus one here because we're going in reverse order now to fill in The Matrix which row are we at we're in the bottom row well which column are we filling in well that's why we have this variable C and then we assign it to this value and Value Plus One when you fill in the bottom row you should take the bottom pointer and decrement it by one to shift it up now lastly the leftmost column we're going to go row by row starting at the bottom of the Matrix all the way up until the top I'm doing minus one because we want to include this and then iterating in reverse order and then the Matrix at this row at the leftmost column is going to be assigned to this value and we're going to take the value and increment it by one and then after that's said and done we are going to take our left pointer and increment it because we just filled in the left column after that is said and done you can see this is quite a bit of code none of it is really super complicated though as long as you can kind of set up the problem properly so let's run this to make sure that it works and as you can see yes it does and it's about as efficient as we can get if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has interviews check out neatcode.io it has interviews check out neatcode.io it has a ton of free resources to help you prepare recently I added a quiz feature that I'm actively working on to help you quickly review coding interview problems so definitely check that out if you're interested
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
1,292
hello so continuing on this contest 177 167 third problem is maximum side length of a square with some less than or equal to threshold so the problem says we have a matrix M by n and an integer threshold and we want to return the max side length of a square that the square has the sum such that the square has a sum less than or equal to threshold and we return 0 if there is no such square is actually so in the example here we have this matrix 3-shot is equal to 4 so the maximum side 3-shot is equal to 4 so the maximum side 3-shot is equal to 4 so the maximum side we can make is the one in this the one with the red contour here or also the yellow contour that one also can be done the both side lengths are two and that's the maximum side length we can make for a square of threshold less than or equal to 4 and so we returned that and so yeah that's the problem the other examples just similar to this and thresholds can be all the way to 10 to the power of 5 and an M and n are 300 and so in the matrix values can be this and so because of the threshold value here we need to be careful not to have a loop if we have two loops let's say for I in shape for 300 and then have 10 to the power of 5 that would be 9 multiplied by 10 to the power of 4 multiplied by 10 to the power of 5 so that would be 9 multiplied by 10 to the power of 9 so it will be really big so we can't make a triple loop like that so we'd have the Calphalon ik when coming up with the solution here ok so let's see how okay so let's see how we can solve this problem so the first thing we can realize here is that the problem really asks us for a sum that is less than or equal to threshold that maximizes the side length right this is very important make samosas the side lengths we need to get the maximum side length that is less than or equal to threshold such that the sum of the square loss is less than or equal to threshold so this tells us that we need to try multiple side lengths maybe all the possible side lengths even and for each one of them try the sum check the sum and see if it's less than or equal to threshold and pick the best side length or the bigger side like right so this means we need a really efficient way to compute a sum of a square in this matrix here and in if we represent our matrix like this the square can be like this that there is has one side on the border but it may be also in the middle right so we need an efficient way to come to compute this and whenever you have something like this in the matrix or a 2d array where you need to compute this with the song in a fast way we can use directly prefix up right so that means that right now we know that our first step is compute prefix up now once we know the prefix sum we can just try all the trial try all the possible positions start position for a square and check the threshold shake the site try side lengths that are really that are bigger than the best we have so far and then check if the sum of the square is less than equal to threshold if it is update the best side length right so that's our step 2 so our step 2 would be just going with the for loop trying all the possible starts of a square so rows and 40 this is a range of columns so this portion here just gives us the possible start of a square and now we try the side length right so let's try side length let's call it K in range of so we could try maybe from 1 2 all the way to the rows mind's eye and columns minus J right all the possible squares of length 1 2 3 and so the maximum length that we can make a square starting at I J we could do that but we'll be doing that for each starting position which would be really costly but instead of doing that we can notice we are looking for the best side length the one that maximizes the side line so we can just keep track of the best side length like this and then we could start so if we find if we found already a like loss a side length of 3 that works which we don't need to start from 2 right because we already have a better one so we start from best and try to find something better right that's what we are interested in and what is the maximum side length that we can get here that's min of rows mind's eye and columns - Jay why - here because if and columns - Jay why - here because if and columns - Jay why - here because if you are starting from this position right you have your square can only be like this right it can be the side length can be bigger than this right and this is just Rose - Rose - I right and this is just Rose - Rose - I right and this is just Rose - Rose - I and carbons - J so the maximum square and carbons - J so the maximum square and carbons - J so the maximum square you could make is this right and so will try all of them and let's say our best was 3 we will just try this portion here right there is no need to try these squares right because we already have a better one so now we will just need to check the sum of the square that it's that it matches this condition less than or equal to threshold so to do that we can just check if some of the square that starts at I and J and goes all the way so it starts at I and J like this and has a side length of K so you will go all the way to this here such that this is I plus K and J plus K this is the square that we are will be dealing with so it is represented by these two and so let's pass the other point here which is I plus K and J plus K and that needs to be less than or equal to threshold I will later I will write sum square in terms of prefix some it's really easy to do that so we also need to define how we can compute the prefix sum and how we can compute the sum of a square because a square that we are looking for here it can be in the middle but can be also here so we need to compute it but if we have that it's less than or equal to odd that means it's definitely a candidate and we know it's bigger than best because that's by definition how we set up our loop so we can just directly set the best to be k plus one now y plus one because this length here is K right so this length here is K but also we are counting the value at position IJ that's part of it so the entire length is this is plus one it's K plus 1 now else here what happened it's bigger than threshold right and so if we go and try another square it will always be bigger than this square so it will still be bigger than threshold so there is no reason to continue and we can just break and that's pretty much all there is to it and so at the end we can just return best now we just need to define two things for this to be complete and for us to be able to write it which is where is the prefix um how can we compute the prefix um and for the 2d array and how can we compute this sum squared right sum of a square using just the two points that define it here and here so for the prefix sum let's start with that so if we have a square let's say like this one I'm gonna say we are at this position let's call it I plus 1 and J plus 1 other scholars I and J here right so the prefix sum for this one you know what I'm going to call it I plus 1 and J plus 1 that'll be easier in terms of dimensions here so this is the square that we are looking for right and this is the matrix value actually sorry about going back and forth with this so this is I and J and prefix sum or I'm going to do because I'm going to write it in terms of prefix some of the previous position I'm just going to consider that prefix of I plus 1 J plus 1 this is just the prefix sum from 0 to I J this is just the definition that I'm choosing so that I don't need to deal with i minus 1 which will give me we from starting from 0 it will give me minus 1 which doesn't work so just to make it work I'm just going to offset or by or start counting for terrific sums from 1 and so prefix someone one would be the prefix sum from 0 to 0 and prefix sum for one let's say 2 it will be prefix sum from 0 to 1 right and so that means here that for our prefix sum here for this position IJ does prefix some I plus 1 J plus 1 and so if we want to compute that one is just this left portion here right Plus this upper portion here and you can notice that we added this comment section here twice right so we need to subtract it once so that we can count it only as one so this here means that this is equal to the left section plus the maybe let me write it in the color here that we so the left section plus the upper section the one in light blue - upper section the one in light blue - upper section the one in light blue - the one in yellow section in the yellow section because we added it twice so and we'll need to add the value at the matrix position itself and so that would be plus the value at matrix of inj and so must cut the loss right left upper and yet at the yellow portion in terms of prefix the previous values of prefix and so left is just the prefix some four so if you look at the green portion here it's the same row as the current prefix but it's one column to the left of it right so that would mean it's prefixed so the same row so I plus 1 and one column left of it so that's J and the upper section that's the same column as the current prefix this but just one row above it right so that would mean prefix of something wrong but the same column so J sorry the same column yeah so J plus one and just the row above I plus one so that's I the yellow section is you can see here it's one row above the current prefix and one column to the left of it so it's prefix of one row above of I plus 1 thus I and one column to the left of it that's J and then we'll need to add matrix at I and J so we know how to compute a prefix some now let's see how we can compute the sum of the square at any position using only prefix samples of course so let's say we have this matrix here and let's say the square is in this position so how can we obtain that sum so if we take the large section here so let's define these values for a second here let's say this is our 1 C 1 and this is our 2 C 2 these are the holders so what we are looking for is the sum square of some of the square starting at our 1 C 1 and ending at R 2 C 2 right so what this equals to is well the blue section the one that I just drawn in blue here so this section sorry this section here starting from this zero position minus this upper section because this shouldn't be included right let me draw it and maybe green so this upper section here we need to remove it from the blue one so that we can get only the square that we are looking for which is this one and we need to remove this section here also right with light to blow here so that we can remove this side here right and the problem is that we remove this section twice so we'll need just need to add it once to make up for that the same reasoning as previously right so that would mean that here our sum square would be the entire prefix sum for our to see - right that's prefix sum for our to see - right that's prefix sum for our to see - right that's the blue section so that's less a prefix for maybe it'll slide an envelope so it's prefix for our to see - - the so it's prefix for our to see - - the so it's prefix for our to see - - the green section right which is the upper section right - the light blue section right - the light blue section right - the light blue section which is let's call it the left section plus the yellow section that we added that will move it twice so we need to add it once so it's plus the yellow section here and now let's write these in terms of prefix some so the prefix for our - C - a - just prefix for our 2 for our - C - a - just prefix for our 2 for our - C - a - just prefix for our 2 + 1 remember the indexing we add 1 C 2 + 1 remember the indexing we add 1 C 2 + 1 remember the indexing we add 1 C 2 plus 1 the upper section that prefix for well it had the same row as a 1 C 1 so it has lower one it has the same column as R 2 C 2 so it has its C 2 + 1 of as R 2 C 2 so it has its C 2 + 1 of as R 2 C 2 so it has its C 2 + 1 of course and it has the same and then we have the left section which has the same row as R 2 C 2 so it's prefix for R 2 plus 1 and it has the same column as our 1 C 1 so it has C 1 and then the yellow section has the same row as L 1 C 1 so we added so it's prefix of R 1 and has the same problem as the as L 1 C 1 also so it's C 1 and so now we have the 4 bit of Awesome square jewel so we have the formula for sum square we have the formula for prefix son and we know the algorithm that we need to do is first compute the prefix sum using this formula here and after that we will need to do these two lobes here for looking through all the possible starting positions for the squirrels keeping track of the best side lengths we have so far and every time trying to improve on our side best side link length and then checking if the sum square is less than or equal to threshold matches the criteria that we want if it is that means we found a better side length so it's sign it otherwise it's bigger so there is no need in trying more bigger values because they will still be bigger so we break and at the end we return the best that we found yeah and that's pretty much it so let's code this solution up and see if it passes the test cases okay so let's try now to code the solution that we just saw in the overview so so the first thing is we need to compute the prefix right as we said according to the formula so and then the length of D so that just to find the rows and columns and then prefix some size is going to be zero for this in range of columns plus one and this is going to be four and range of rows plus one because we are going to start indexing from one and just populate the terrific son so range of rows range of columns and we apply the formula that we just defined so prefix of IJ is equal to I plus 1 sorry J plus 1 again indexing from 1 to avoid the case for the zero index so it's the matrix of IJ plus the prefix for the left portion plus the prefix sum for the upper portion - the section that we upper portion - the section that we upper portion - the section that we added twice so we remove it once so that will leave just once and now let's try to find the best side lines so go through the all the starting possible start position for the square and we try side lengths that are better than the one we found so far so men of clothes - I and colleagues - I and we clothes - I and colleagues - I and we clothes - I and colleagues - I and we check if there's some square for that is less than or equal to threshold we check basically that matches the criteria so that we want and so check if it's less than or equal to threshold if it is that's the best we can do so that's we update the best we can do so it's now K plus 1 because it's K and then we are adding the value at position I J so that's part of the square otherwise it's bigger so trying more won't give us anything less so we just break and at the end we return best and we need to define the sum square so let's define it here so the columns would be the start position for the square and the ending position for the square which is our to see to here and so the first what we do is we return the prefix some of the entirely remember the large section which is our 2 plus 1 C 2 plus 1 and then we need to move the left section which is same row column C 1 and the upper section which is same column but row 1 R 1 and then we need to add the yellow section you remember in the overview that we add because we removed it twice we need to add it once so that we can leave just adding it once so that's prefix of some of our 1 C 1 and that's pretty much it so responders so index out of range I columns - J actually and then the rest I columns - J actually and then the rest I columns - J actually and then the rest should be good okay so that looks good must met okay so that passes for one slight different way we can do this is the following so instead of doing this best here and trying all the best side lengths just binary search for a side length that is less than or equal to threshold and take the largest one we can find using binary search so to do that we will we need binary search so what is our low and high values so it starts from zero and the highest side length we can find is of course the entire square that we can make in the matrix so those minimum of rows and columns and then we do normal binary search here and then we take the mid and mid here present remember the side length and so we check if the square exists that is less than or equal to threshold that has mid as a sideline right so check if there is a square with some than or equal to threshold and side length equal to me that's especially if we find one then that means that because the criteria here is that so if we find a square that has side length mid that means if we increase the mid so it has threshold less than or equal to some lost Anacortes ratio so if we increase the side length we will still find we will either find false right or it will still be true so essentially what I'm saying here is if so our f of X less than or equal to threshold here X is side length and the f of X is sum of square that has side length x right so if I find one that is less than or equal to threshold if I have some why that is so if I have some Y that is less than X and X f of X is less than or equal to threshold that means that f of Y would let's say will have this and f of X is less than or equal to threshold so that would mean that f of Y is certainly less than or equal pressure all right so that means I will keep having truth until I reach a point where the value is bigger than threshold and then it will start being false and what I'm looking for is this last true here the last truth the last side length which means the bigger side length for which threshold is at an equal to this so that means if I find a square that has mid side length equal to mid that is also equal to threshold so maybe I'm here but maybe also I'm here and so I need to go where I need to go right to find a better solution or maybe find false right and so I need to go right which means I need to set my low to mid plus 1 right otherwise if it's false let's say I'm here want the only way to obtain something that it because I'm looking for the last true remember so I need to go left so that either I find another false or I will find the true that I'm looking for and so I need to go left and so to go left we say a high equal to mid minus one and once I'm done we have both are equal I can just return low so now I just need to write this square exists function so any square there's that has side length so this is the side line and that there is less than or thought official so let's try on the possible starting position of the square so that's of course Rose mine sideline we can't go all the way he tells Rose because we want a square that has side length right and same thing for J but it would be columns and we just check if this there is a sum of square starting at I and J and that has side length basically side length that without us as a parameter so I plus that and J plus side line that is less than or equal to threshold remember that's exactly my form what I'm looking for here that's my f of X here so I could even call this f of X you can call this f and can call this X right but let's just give them more expressive names so threshold if it is then I could return true otherwise I just return false I couldn't find it right so this would check if there is a square of sum must not equal to threshold that has this side length right and that's pretty much it okay so lots of it okay so that passes so one last solution that we can make here which is even a lot better is you could realize that okay actually I don't need I can do it while computing the prefix why is that because I can so I will still need this definition of some square I'll just put it here you need we don't need all of this actually we can just well computing the prefix sum here at this point I could just check if so I could keep track of the best side length I have so far right and have a side length that I keep increasing trying to find it if it's if it forms a square that is less than or equal to threshold so the best is zero at the start side length at least one right for it to be a square so I would check here if I can have a square that has some so that starts from I minus sideline and J minus side length of course plus one because I want this size the length of the squares to be side line and goes all the way until J and is less than or equal to threshold basically I'm checking if there is a square ending at IJ right basically meaning that it's bottom right position is IJ oops that has some less than or equal to threshold right and if I find that means my best is now side length and I want to look for only things better sides the squares that have side lengths bigger than this because anything else would be less and want to give me best so I increase sideline to get that and here are just some things to avoid having out-of-bounds I things to avoid having out-of-bounds I things to avoid having out-of-bounds I will need to check that I is bigger or equal to side length minus one right for this to work it has to be right otherwise it would be some kind of square that starts from minus one which is not correct which can be so just some boundary safety here and otherwise this the main point here is that once I have a best side length plus a of two I shouldn't be looking for squares of size two or one I should be looking only for squares of size three four and things like that and so to do that I keep in once I find a better side length I increase my side length so next time I look for something bigger than my current best right so that's the main idea and if I'm doing this then I don't I can do it while doing the prefix sum because I'm looking only for squirrels that add and a tie and J and those are already computed you know and so my some square here would give me the right result so I can do it while computing even the prefix son yes so that's pretty much it's all submit okay there is an indentation problem okay so that passes all test cases yeah so we saw three ways to solve this problem and yeah so if you learn something from this video please like and subscribe and share it thanks for watching and see you next time bye
Maximum Side Length of a Square with Sum Less than or Equal to Threshold
immediate-food-delivery-ii
Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_. **Example 1:** **Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4 **Output:** 2 **Explanation:** The maximum side length of square with sum less than 4 is 2 as shown. **Example 2:** **Input:** mat = \[\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\],\[2,2,2,2,2\]\], threshold = 1 **Output:** 0 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 300` * `0 <= mat[i][j] <= 104` * `0 <= threshold <= 105`
null
Database
Medium
null
4
hello and welcome to another video in this video we're going to be working on a median of two sorted arrays and I will start by saying this problem is very unintuitive to get but I think we're going to be able to work it out and kind of give you some intuition on how to do it and then from there what I would definitely recommend is once you get the intuition like once I draw the pictures I would definitely recommend doing the problem yourself before uh seeing the solution but let's get started so you're given two sorted arrays nums one and nums two of size m and n and you want to return the median of the two sorted arrays and the overall time complexity should be low of log M plus n so in this first one you have 132 so essentially if you get a median they're basically saying like combine these together and what's the medians if you combine these together in a sorted order it would be one two three and the median remember is just the middle number right so it'll be two and then similarly here we have one two and three four so if we combine those together so the median of an even array is just going to be the mean of the two numbers in the middle so you take these two numbers in the middle and you get their mean and that's two and a half and so the problem with this problem is like it would be very easy or not maybe not very easy but it would definitely not be a hard problem if you could like merge sort these or not even merge store if you can combine these arrays right like if you could just take one two and three four and you can just say okay let me just combine those into one array right like Loop through them combine them they're already sorted you don't even need to do a merge sort of just a normal like walk through them find which number smaller and so on the problem though is that would be M plus n time complexity so that's going to be too slow but yeah if you could do that would be an easy problem or not an easy but you know easy to medium but the problem is you can't you need to be able to do it faster and so we're going to actually find the median without actually combining these two rays and it's definitely tricky so let's just get an example here of two arrays and we're going to go through two examples and we're going to figure out like what we actually do so let's get two examples so the first example would just be an array of one two three four five six seven eight and the second example will be of one two three four so what we're going to do is we're going to figure out first thing how many total items are there right and we can just say that's like T or something or total so the total items that's pretty straight for you just combine the link so it'd be 12. then we want to figure out what the half of that is also pretty straightforward it's going to be six so then what we need to do is we need to actually and you can do this through either one but we're going to choose to binary search through the smaller array you could do either one but you can just say like let's say this is you know nums one and this is nums two if it's the other order you can just reverse them because you have to binary search through one of them and so it's going to be fast search obviously do binary search through the smaller one because then your time complexity will be log of the minimum of M plus n instead of the you know whatever random one so essentially if you think about it we have to split our array here into two parts the part that comes before the median or like the left part and then the part that comes after the median and so let's figure out what that's going to be essentially so here we have a half a six so that six has to be some part of this array and some part of this array so for example let's say I chose to pick this part right let's just say randomly I chose to pick this part is before and this part is after then we're going to try to split it as evenly as possible so if we have 2 and 2 we're gonna have to split this into four and four so essentially this part and this part need to come before this part and we can verify that by making sure that all of these numbers are less than all of these numbers right so clearly this wouldn't be a good split because this 4 is actually you know greater than this three so this wouldn't be a good split but that's kind of an example once you figure out one possible split for this one you can figure out the rest right like once you figure out possible split here let's say you're going to use two elements that means you have to use four elements for the second one to get that split before the median so essentially we're just going to binary search through possible splits and there's going to be like a way to tell if our split is correct or if our split is incorrect and essentially we're going to use the midpoint to figure out where our split is and because we're going to bind your search it's going to be pretty fast and so there are our midpoint is going to represent the last number in the left part of the split and so it can be any index actually it can also be outside of the array so our actual our midpoint here can actually be outside which means our left side has nothing right and our right side has this so then to have an even split then our left side here would have to have six elements and our right side would have to have two right so we have six and zero and four and two which would be like a split would it be a good split obviously not because you can see that like this has to come before this but we'll get into that but that's possible right so the midpoint can be anywhere from one out of bounds to here any one of these is valid so essentially we're just going to pick we're just gonna pick our midpoint and kind of see what happens and we're going to walk through this so let's say we pick this midpoint right just the middle number right over here that means our split will be this is going to be the left side right this section is going to be the left side so and now we need to figure out what's going to be like the last number in the left side of the top so if there's two numbers in the left side here remember we need six per half that means there needs to be four numbers in the left side here so we can just take this value right so we can use it from this value we can easily get this value and I'm actually going to show those in different colors because that's going to be important so the green is going to be the end of the left side and then the Brown is going to be the start of the right side so it's going to be like this and now how do we check for a valid split well that part is pretty straightforward because they're sorted this number has to be less than or equal to this number and in which case it is and this number has to be less than or equal to this number and here it's clearly not right so this 4 is greater than this 3 which means we would want to include the three instead of the four right like we were we're going to want to have a split here that is going to include the three instead of the four we didn't know exactly how many numbers but we know this needs to be longer like our split right now is this and we know our split needs to be longer so we're going to say okay this is not a valid midpoint so let's actually move all right now to be or sorry our left to be uh over here because this was not a valid midpoint we need this part to be longer so now that there is a midpoint somewhere here and there is there's always going to be a valid midpoint but now we kind of do the same thing we're going to say okay we're going to try one of these and so let's just try this one over here as our left which means we have three numbers here so we have to have three numbers here so we're going to put that over here and then our right side will be this and this it's just the number after now we can check again so we can check okay so this 3 has to come before the four it does and this three has to come before the four it does as well so these numbers are actually the first six numbers that have to be in the array and that makes sense right we have one two three and one two three which makes sense because one two three and one two three have to come before the rest of this whole thing so we have like a valid solution now and then once you have a valid solution now we need to figure out what's the median and there's going to be two cases here and we're going to go through both of them but essentially in this case remember we have a um we have an even number so to get the median of an even number what you have to do is figure out like when you add these two arrays they're going to be combined into one right and the biggest number in that left side is going to be either this number or this number so we need to get the bigger number out of these two and that's going to be like our left side right whatever the bigger numbers here is going to be our left side so we can say like the max of these two in this case they're the same it's just going to be three similarly on the right side they're going to be a right array right so if you have a left array of a bunch of numbers and you have a right array of a bunch of numbers and they're equal size the median is the biggest number here and the smallest number here added together divided by two so that's kind of what we're doing here we're essentially getting the biggest number on the left side which is the bigger number out of these two and the smaller number out of these two in this case they're both four but if they weren't we take the smaller number we would add them together and we would divide by two and that would be our median so it'd be 3.5 right and that's how you calculate a median on a in an uh even number array because there is no midpoint the median represents the midpoint but there is no midpoint and let's just say we drew this sorted let's see what that would look like right just to make sure we have what we wanted so if we had one two three four and we actually combine those so be one two right three or I'll be one two three four and then it would be five six seven eight like this and so this is length 12. so we would take the sixth number and the seventh number and then get their average which would be 3.5 so that their average which would be 3.5 so that their average which would be 3.5 so that is correct so that's essentially what you do is you just check you just set some kind of like starting point for your left and your right and then you can always check is my left or right too big or too small or just the right number right and like I said in order for it just to be the right thing this number has to be less than or equal to this number and if one of these isn't true then you just um you know move this midpoint accordingly and then you'll eventually get a midpoint so we did this with a uh we did this with a even number array now let's try an odd number right so we'll just add a five here for Simplicity and let's just redo all of this in fact we can even make it harder right instead of adding a five let's add like a nine or something right there we go okay and so as long as they're both sorted it will work so let's just go through our algorithm again so for our total we have eight numbers and five numbers so we have 13. so for the half for the left half we're always going to want to have if it's an odd number we're always going to want to have total over two but lower divided so we're going to want to have 6 here we're going to want to have six on the left side and then it's going to be easier to get the median so let's do that so remember our right pointer is over here and our left pointer can technically be out of bounds because technically the left side can be an empty array and the right side can be this whole thing right that's totally fine that is a possibility which would mean that this whole array comes before this whole array which is totally possible Right like this can be one two three four five six seven eight and then this can be like nine ten eleven twelve and so on and so this whole array would need to come before this whole array also what we need to do in our actual problem is we need to represent like we can be out of bounds in both of these and so the way we're going to do this is represent left by negative Infinity if we're out of bounds on the left side we're going to make that negative infinity and if we're out of bounds on the right side we're going to make that positive Infinity which makes a lot of sense because let's say this whole array needs to come before this whole array then list left should be negative Infinity right because then you have negative Infinity and then you have this whole array which makes sense right that would be in the right order then you would have this whole array similarly you know if you had it the other way like let's say you had let's say uh in this case this whole array needed to come before this whole array right like this was one two three four five then we had six seven eight nine ten and so on so one three or five would be here and then our midpoint would be here and then our right side would be Infinity which would also make sense because it would be this left side right we'll call that left then this thing right then this whole thing so right and then Infinity is going to come afterwards which makes sense right so that's the way we're gonna represent being out of bounds but anyway let's go through this so we're gonna have a right here we're gonna have a left here and we are going to get a midpoint once again so our midpoint on this will be over here right because essentially our midpoint will be the middle of these two which will be you know we always lower divide so it's going to be and we want to get the smaller right we always want to like divide it smaller okay so if we're midpoint is here we have two numbers here that means we need to have four numbers here right because we need to have six numbers on the left side so if we have four numbers here our end of the left will be here and these are very easy to calculate right like if you know that if you know this index you can get this index just by a simple math calculation you can get it in of one because you know exactly how many numbers you need so then similarly our right side will be here and now we are going to check is their stuff fine so remember this 2 needs to be smaller than the five it is right this is fine but this 4 is greater than the 3 which is a problem so this 3 needs to be included before this 4. so that means this was our left side but it was too small it needs to be bigger right so if it needs to be bigger we're going to reassign our left and our right or our right is going to stay the same but our left will move over here right like this left side needs to be bigger and then we're going to do this again so we are going to say okay what's the midpoint here the midpoint is right over here so how many numbers do we have four that means we need to have two in this side so we're gonna have two in this side and then we're gonna have the right side and we're going to compare again okay so we can check if our if we met our criteria right so this left thing needs to be smaller than this right thing and it is right 2 is smaller than nine but this left thing needs to be small in this right thing and it's not so this 4 is too big so this four is included in our left side the right if we drew our left arrays here it would be this one and this one but as you can see we included this four and we did include this three so now our array is too big on this side so if our array is too big we need to make it smaller this left array so what we need to do to make it smaller is pretty straightforward we need to make the right over here now right from like a binary search now our midpoint will be this value and let's figure out what we need on the right what we need on the top so we have three values here so we need three values here now let's try it and this should work because this is only the number we have left so hopefully it does so now this is the right side and this is the right side now let's check it's three less than four yes right and it's three less than four yes and if you think about it this would be our ideal split right like our deal split would be just like this it would literally be one two three four five six seven eight nine and so if you took the left side of that it would be six numbers so this these six numbers right here which are the same as these six numbers right here so it is the same and now our right side would be this and our median would be the middle number so let's go over the let's go over how to get the medium when you when the median when you have an odd number array right so you have 13 numbers you have six on the left and six on the right so this median is guaranteed to be one of these two numbers right because you have the left and you have the right but which one is it well if you think about it right this is increasing so it's going to be the smaller one of these two numbers is going to be the median once again they're equal but if they're not it would be the smaller one like if this was a four and a 9 or something you would take the smaller one because the median is going to be the number that's right after the biggest number here right after which means a smaller one of these so in this case we would return four which would make sense so now we kind of have everything we need to be doing we are essentially binary searching through the smaller array getting some kind of like left side and then from that we're getting the left side for the top array just because they have to add up to some half and then we are simply checking is this green thing smaller than this brown thing and is this green thing smaller than this brown thing which means our arrays are partitioned perfectly and if not we just update our uh our pointers accordingly until we're out of bounds and we're guaranteed to have an answer and the answer might include not using any part of this array or using this whole array but that's going to be in our bounds so now we have enough to code it up and it's going to be a decent amount of code so let's go through that so first what I'm actually going to do is I'm just going to rename these to X and Y just to make it a little easier because I'm going to reuse these variables a lot and it's going to be kind of Hefty amount of code so the first thing I'm going to say is if length of x is greater than length of Y I'm just going to swap them and this is an o1 operation in Python because you're not actually like moving elements around you're just changing pointers you could also uh instead of swapping them you could also just call this function again and pass in the arguments backwards right so you could call this on YX and that would work too because essentially you want X to be smaller because we want a binary search through the smaller array because that's going to be faster now we're going to make our left and our right for the binary surge so like I said it can be out of bounds or length of x minus 1 could be the final index now we're going to make a total also pretty straightforward so length of X Plus length of Y and then we're going to make a half that's going to be total lower divided by two now we are going to do a normal binary search we're guaranteed to have an answer because our bounds are correct now we are we need to get two pivots essentially so first we're going to get like a normal pivot so we can call this pivot x equals left plus right Plus or lowered over by two but now we need to get a pivot Y and this is going to symbolize I'm going to go back to this picture a lot this is going to symbolize this green arrow on the top array right we got the pivot for this one but we need to figure out what it is for this other one and the way that's going to be is it's actually going to be half right however many elements you have minus pivot X and then you also have so have to subtract 2 because arrays are zero indexed right so in order to actually get the right index it would because they're both zero index you have to subtract two and you can work out the math you can just do some examples like if you do some example here like if this is the number here and the half is some number what index should this be and you can kind of see that and figure it out but yeah essentially because there's zero index and there's two of them you have to subtract two now we are essentially going to break this code down into the right side and the left side like I showed so the left is going to be the rightmost value in the left side right just like I showed you in this picture the left is going to be the rightmost value in the left half and the right is going to be the leftmost value in the right half and so we're going to do that so we're going to say uh we can do the right side maybe first or we could do the left like either one's fine I think let's just do the left side first Maybe so we could say left X equals it's going to be X and then pivot X if pivot X is greater than or equal to zero otherwise remember if we're out of bounds we're just going to initialize that to negative Infinity similarly for the right side we're going to say right x equals X pivot X plus one right the one right after it if pivot X plus one is less than length x otherwise we're out of bounds again so we'll make that Infinity so slow Infinity here and then we do the same thing for the Y so we're going to say left y equals y pivot y if pivot Y is greater than or equal to zero else float negative Infinity and the same thing for the right y it's going to be y pivot y plus one if pivot y plus 1 is less than length y else float Infinity so literally the same thing hopefully I don't screw up anything here so now we have to essentially check if our stuff is correct right like if our logic is correct so what we have to do is we have to say okay if left X so remember going back to the picture so the left X is going to be this bottom one this green has to be less than this brown right so this is left X this is right Y and similarly left y has to be less than right X so we have to check for both of those so reflect if left X is less than or equal to right Y and left Y is less than or equal to right X then we have to check do we have a even or odd number for the median because you're going to calculate a different area is our total odd or even so we could say if total mod 2 right if it's odd let's do that first and so that one is going to be return Min of left X and uh right y or actually it's going to be left X and left y right so it's going to be Min of left X and is that red actually no it's going to be there it's going to be the uh the right one yeah so right X and right y right going back to this picture so this was actually a um this wasn't odd number so you're going to take the two right sides and you're going to get the minimum number there yeah okay otherwise it's a little trickier you're going to return the maximum of the left side so left X left y plus the minimum of the right side so right X right y EP you're going to get both of those and you're going to divide by two and it's not going to be an integer divide it's gonna be a floating point five and so that'll take care of both of those now we have to check for our two cases essentially right so we can check for one of these so we can just check like if right X is greater than left y let's see what actually and we want it the other way though so we want it left X is greater than right y so let's kind of look at the picture to show where should we should be going so if this left is greater than one of these that means we're including too many numbers here right that means that like if this is greater that means like let's say we're including this whole thing and then the number we're comparing to is this that means this is too big so if it's too big we're going to want to make it smaller so how do we make it smaller that's going to be right equals pivot minus one and then otherwise we're going to want to make it bigger so else left equals pivot plus one and we shouldn't have to return a default value and I would be highly shocked if this worked uh without any errors but let's see so I do need to actually get rid of this I can see some stuff here let's take a look oh yeah so this needs to be uh pivot X and pivot X see what happens if that's okay nice and so this is pretty much as efficient as you can get with this problem like yeah you basically it's all over the place but essentially it's as efficient as you can get with this problem so let's actually go through the time and space now let's actually minimize this and let's do that so for the time let's kind of look to see what we're doing so essentially what we're doing is this part is of one this part is all of One this binary search is essentially looking through the smaller array right if you have like M and N it's looking through the smaller one and it's doing a binary search and all of these are of one like this is all of one this is all over one this is all of one so essentially every single operation here is of one so this would just be o of the log of the minimum of M and N because we're essentially search we're essentially saying let's just binary search through the smaller array right and if we have the big array we just swap them and so for the space we have some variables but we didn't ever actually declare it we never actually made any Ura we have a ton of constant variables we never made a new array so it's actually going to be a one but yeah I think this problem is quite tough especially I would say it's very tough to like get started and then once you get started it's still not easy to code so I definitely recommend at least for me even once I saw the solution to this one I still kind of like forgot in a while so I definitely recommend to either code it up uh before you see the solution like once you kind of get the Intuition or save this one and try to code it up in like a week or two when you don't remember the exact solution because there's still like a lot of edge cases and it's not very intuitive and it's definitely a good one to practice and I definitely I'm not a huge fan of this problem because it doesn't really use like an algorithm you know it's very unintuitive like it's just kind of weird it's like you have to get the intuition for it but it's definitely um and like I said even if you know kind of what you're doing it's still not that easy to code right there's a ton of edge cases there's all these like out of bounds errors so I would definitely strongly recommend to code this one up again I think this is one of the harder ones to even if you see a solution to remember and to go to uh on your own but yeah it's gonna be for this problem hopefully you enjoyed it and if you did also by the way so the other thing is this is a really common interview question apparently this is like in the top 20 interview questions so if you are going to be interviewing strongly recommend to know this one especially for like the harder problems definitely strongly recommend you know this one but yeah it's gonna be it for this one and if you liked it please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
7
liek code problem 7 reverse integer given a 32-bit signed integer reverse given a 32-bit signed integer reverse given a 32-bit signed integer reverse digits of an integer assume we are dealing with an environment which we could only store integers within the 32-bit signed integer range of negative 32-bit signed integer range of negative 32-bit signed integer range of negative 2 to the power of 31 and 2 to the power of 31 minus 1 for the purpose of this problem assume that your function returns zero when the reversed integer overflows so 2 to the 31 power minus 1 is 2 billion 147 million 480 3647 negative two to the 31st power is negative 2 billion 147 million 480 3648 so we must stay within range of these numbers so here's an example number when reversed is the closest possible number that we can use to get to the max integer number this number when reversed will be the same as max in except for the last digit 7 will be a 1 we will see how this is useful to look at later so let's reverse our number here we pass in the example number into our reverse method here's our reverse method taking in an integer of X so the key part of this method to look at is that we're taking modulus of X to get the last number of the number that we passed in and then on each iteration of our loop we multiply our previous result by 10 and then add the remainder number that we got from doing X modulus 10 and this will shift the last digit of the number that we passed in by one position on each iteration since we have a basic idea of how this method works let's look at the space-time complexity since we at the space-time complexity since we at the space-time complexity since we are only dealing with a few basic variables and not an array our space complexity is Big O of 1 since we are essentially looping through a list of digits based on the number that is passed in our time complexity is Big O of log base 10 of X you can see this is true as for every power of ten we gained approximately another digit for example log base ten of the max integer value is equal to approximately nine point three one nine and there are ten digits in the max integer value in Reverse ten to the power of about nine point three one nine will bring us back to the number of max int so now let's step through the method we set our initial result to zero then we have a while loop to go through each digit of the number passed in we will end on our base case when X is equal to zero because every time we loop through we divide X by ten since we have positive and negative integers passed in we cannot do X is greater than zero we must do X is not equal to zero so here we have our number that we passed in and you see if we take modulus base ten of this number then we get the number two at the end of the number here we have our bounds checking for our Max and minimum values I'll look at this again after we walk through the rest of the function so on our first iteration we take our current result which is zero and multiply it by ten and then add the remainder which is two so now our current result will simply be two and since now we have two in our result we must remove it from the original number so we divide X by ten now on our second iteration you can see that two has been removed and we take modulus of ten of the current number now we have a remainder of one which one is the last digit in the current number so now we take our current result two and we shifted over by one digit by multiplying by ten and then we add our remainder that we just got by taking modulus of the current number so now our result is 21 now we remove the last digit just like we did by four by dividing X by 10 and we will continue to do this until we reach X is equal to zero thus our entire number will be reversed so now let's look at our edge cases now that we're looking at the last digit to be reversed we must compare the current value to the max your value divided by ten because once our current value is multiplied by ten we could have integer overflow if it is greater than the max integer value so in this case the next number since the remainder is one will end in a 1 so in this case the numbers are the same once you divide in max by ten leak code also points out that you can check if the result is equal to the max value of integer divided by 10 and the remainder is greater than 7 conversely we do the same thing we check if the result is equal to the min value divided by 10 and then we check if the remainder is less than 8 because of course here if we append 8 to this number in our result that is greater than the max integer value but in the case of c-sharp value but in the case of c-sharp value but in the case of c-sharp this is unnecessary because the highest last digit that we can pass in is a 1 this will be true in other languages as well however this other condition is useful to look at if you're looking at different types like the long type where you could have a result equal to the max value and then you would have to check the last digit so here we get our number reversed 2 billion 147 million four hundred eighty three thousand six hundred forty-one the last digit in X is hundred forty-one the last digit in X is hundred forty-one the last digit in X is 1 once we divide by 10 we will be at 0 and we will break out of our loop and then we return our result and that's about it for reversing an integer an alternative approach because of the range of the integer is to multiply the negative integer by negative 1 if X is equal to the min value we simply return 0 otherwise we can multiply X by negative 1 and then it will be a positive integer and this number will have the same constraints as the regular positive integer so as we loop through all we have to do is the positive integer check and then after our loop is over and reversed our number we simply check if the bit is flipped and then we can multiply the result by negative 1 and return the result this is simply just an interesting alternative to the integer version of this problem as mentioned before if you're looking at Long's or a different Atta type then you'll want to do the original version right here of this problem the actual leak code solution and add the or case but since we were dealing with integers we do not need to use this or case and we don't even have to look at the negative number case if you found this video helpful please give it a like and a comment below if you'd like to see more videos like this please subscribe to the channel thanks for watching you
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
380
2019 Vishwas Interview Talk About The Very Mission Problem Only And Should Pages Have A Certificate Conducting Oven In This Problem With 2.3 Different Operations Research With 2.3 Different Operations Research With 2.3 Different Operations Research Institute Of But They Can Set Up Numbers The List Number From Ujjain Saint Of Numbers And To Find The Number Of The Friend Numbers and Work Yorkers Operation Co Fold Complexity of Skin Problems Due Date of Birth Change Band Expectation Is That You Need to Create Some Canter Co Combination of Boxing Data Structures Cyclist Exams Page Central Idea Good Enough to Handle All These Operations Next Time You Can Solve This Problem Should Start With Them Understand Very Simple Data Structure For Bride From All Also Operation Was After And Withdraw Into It Improves Solution Distance Of Door Turn Over Time In Last Moments Of MP3 Operation Naxal Operation Surface 1965 One Over A Great Friend Special Operation This Trend Rate Monitor Number 90 Reasons Set Up Number Dial Present In The Hague Decided Equitable Probability Of Getting Any Updates Numbers In All The Language Of The Dawn Is The Time Support Software President Generator Number Like Inch Sexual Class And You Can Do Something Random A Daughter And That I Will Provide Arrange Electronic Is Free Number Se 0.2 Generate Random Numbers Between Free Number Se 0.2 Generate Random Numbers Between Free Number Se 0.2 Generate Random Numbers Between 0 And Two Wheeler Equitable Property Absolute Se It Generator Number One 22122 Pimple property cigarette or hair oil defeated were required to greater number like current edit plus counter of the number element greater back one hundred crore lighting and 300 joint maintain quintal and account it is equal to three four that 1965 overhead tank like soft science insult se 0524 notes6 122 5 mein nazar application hai straight line and old men generate random number a random thoughts and a pipe vikas vihar count this favor sudhir and number of any formal office number in this has got immediate operation delete five to the first time encounter delete Operation selected OA then 1.5 small and not Operation selected OA then 1.5 small and not Operation selected OA then 1.5 small and not usually without tears liter number but amazed at how will I go out with a twist to left side effect right to find the number in the research head delete 500 vit from collision left side and use this point Nawaz K Urs This Point Mintu Is The Bea From All The Number Represent The Light Of Off Shift All The Number 01 2011 Element 300 Tractor That Van Episode 106 Debit The Third Tips And Sacrifice And Get Pad To Remove From Alien Automatically And Don't Forget You To For R Great Leaders Were Reduced Problem Numbers Flash Light On Unnecessary Derivatives Liability Character In The Left Hand Set To Find The Number And Worshiped In All Elements By One Interested Left And Observations Of Undertaking Old Time Complexity Vijay Not Allowed Perse Hain To Kuch Typing This Point S letter to the second partition opened intelligence volume setting numbers by government service more pressure late interdependent random northern operations of independent of how did not involved in the current and so instead of just shifting my workplace what we can do it is the different types Of lord two numbers the first the number delete and last elemental 111 digest game co intermittent temporary number one to this sign into this loot sit on maximum just taste the two numbers of but in order to avoid them have five thursday endeavor to reduce after To 4 5 To Basically Due To A Delicate Remote Saja Current Affairs And I Have These Magic Tricks Warning 6376 Seervi Elements And Birds Pair How To High Rate Of Growth And Tried To Find Another Instance When Who And Time Complexity Flash Light On Strength Of Cricket Videos The Sunao Kisi Ko Hair Oil Problems Basically Reduces To Searching Of Element Observance Of Elements In Just One Time Complexity Slaps For Advanced Scientific And In This Shubhendra Different Types Of Data Structures And Awali Baghwa Kharachat Undertaker Teacher Main Doosra Card Gaya Bhi Currently Using Debit The Best Option Unitech Co And Time Complexity To Search Is Otherwise To Order Data Word Date Things Where Are You Are Smart Enough To Meeting's Solid List Of Elements Of Examples Of Decit Basically Now And Research Team Also Significant For Searching Life In The City Under Threat of Director Anil Is Basically a Festival On Ka Noha Travels Kya Welcome To Find The Element In Just One Time Complexity Indiscriminate Good Luck Growth Different Programming Languages ​​In Uth Jaao Different Programming Languages ​​In Uth Jaao Different Programming Languages ​​In Uth Jaao Tabiyat Safed Ho On Karo 116 Side Isi Ho Ya 125 This Element Udhar Infections 100MB God this shirt operation v12 insult to national apart from putting them into the end 111 to maintain hand mein aa synthetic 2l 102 enrollment 2.20 that dandruff bansal test inactive 12521 at the moment 3 minute map 2.2 at the moment 3 minute map 2.2 at the moment 3 minute map 2.2 indiscriminately two three A6 also person and convenience Dashma No Way To Avoid Operation Beerwah Man Tried To See What Is The That Bollywood Corresponds * That Bollywood Corresponds * That Bollywood Corresponds * 25 In This World To Give The Correct Velvet Should Avoid 512 Is Active We Are Trying To Form Of Operation In The Next And Appointed As They Forgive Vibration Battery Saver dad counter on ki bijli counter - one morning-evening operation ki bijli counter - one morning-evening operation ki bijli counter - one morning-evening operation like this and great soul all rich operation visit quarter inch updated on and tell how are you and come home and gave praise dandruff and delete operations can we want and complexity while tuition week enter adapter Hear developer tightening a solution take striker different approach the different data structures on tuesday and different operation daily point 209 existed the first word used oil basically an account number by deleting counters on the number elements of president data structure in the gallows basically a roadways folding the Value Data Presented in the Structure Third in the next9 Previous Earth Map for Valuable Taxes In Value Celebrate That Girls Doctor Appointment That Was Appointed Setting Element in 2G Data Structure What We Do It Back Been Appointed to Values ​​Are We the Intex Appointed to Values ​​Are We the Intex Appointed to Values ​​Are We the Intex Newly Created Basically number to indecent justin chronic penn number elements in the best option is increase the mother of making grand wedding bride number second war random number generator to formation number between 0 and a minor get separated numbers elements present size data structure in versus the volume printout Intex third most important operation is pure digit operation which is also tried to find and access point to the number from the in a duos value for kids with the last statement indirect basically in r values ​​and know what basically in r values ​​and know what basically in r values ​​and know what is the just want to develop this element witch software one to reduce saavn counter angela statement has been deleted witch can prove its employees from marvel intact meghnad the subset in this yoga har disha mein ba bcom honors operation in just one time complexity pleasure watching this video plz solution for this video can not Link Will Love This Be Found in the Description
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
1,371
Yes, this time we will solve problem number 1 of Date 5370. The problem uses the open trust technique, so if you know it, I think there will be a place where it can be useful. And I would like to ask for a lot of likes. And the reason why I keep making videos here is torpedo. The code issue itself may be important and meaningful, but I keep uploading videos because I think things like how to approach these problems when they come up and the flow of electricity are more important. I think you can focus a little more on it. Hey, the problem is literally to find the length of the longest substring that contains an even number of vowels. So, here, the number of even vowels refers to the body, here, after o 5. It is defined as these 5, and these 5 are each even number, so it is two with 3 bays, and this child is not a total number like this in one place, but a is an even number, and this is an even number, and so on. For example, you want to find the strongest section among those sections. In the case of this character, it will be from here to here. For example, after writing this type of character, both of them will be two sections. Even if it deviates significantly from there, it will be from here to here. 5 becomes an odd number, so even if I deviate just one space from this side, the number becomes odd, so if I talk about this length, I think it is 13. This will be the smallest cup. These two, what? Ah, two, it works well, so it will be the longest section between Kim Gu. In order to handle this, the first thing that comes to mind is that it will be easier if you consider all sections. Yes, it will be easy to ride all September, but in order to do that, ah, this size is too tall. l The fan is now 5 inches long. Since it's a multiplier of 10, the maximum is already 10 It becomes a very large number because it goes over the last name. So in this case, you can't consider all sections like that and you have to find a more efficient way. Usually, when a problem like this comes up, you have to know the basics first. It shouldn't be basic, but what I mean is, Ah. Example 2 You must have information about how many times the number 5 means. For example, here, for each section, here, it's all about Yong and Dayoung. This is the second, and here, this is the third, and here, the first, what, the second mission, the third notation is 2. Um, after that, all of these will be 00 days. After that, this will be 3 people. Playing in the dark goes on again, and then it changes to 4. This information Assuming that we are creating and collecting it, how can we use this information to find an even number of sections? God is now very important. Then, we need to do something called a prefix island. I will create separate content for the two-piece fight. I'm preparing it, so I'll explain it in more detail later. Let's say that they I will create separate content for the two-piece fight. I'm preparing it, so I'll explain it in more detail later. Let's say that they have the letters 70 in this order. Then, the first occurrence of the letter a is here. 1 2 3 Let's say the number in front is zero. The number above is here. It comes from the front. The fourth value here is the fourth cup. The letter is the sixth. And there is significance in the open wall. It will be the seventh. Then, within this section, how can I determine how many there are? The entire request in front of this. From the number 5 to the one right in front of the 2nd section, if you subtract the total number of a, you get the number in this. In other words, this is the rap, this is not the country, this is the market section of the section, and if the section ends, the point and section before the start of the section If you subtract the number between the beginning and the end of the section, the difference in there becomes a cardinal number, right? You have to create this tab with that basic information. Then, how do you make it in this case? This table is like this. Does that work? You have to do it like this. For example, based on this, if you create information by text, Ben, at first, this is 1 dragon, there is 1 tooth, 2 teeth, 3. The concept is nothing new, right? It's a European thing. All you have to do is create a table like this. Oh, did you really create a tab like this? That's not true. If you look at it later, you'll see that now we're really creating this tag. No, but we're starting from this concept. But in this problem, we're looking for an even number. Because it is an even number system and an even clock, not the actual number, there is no real need for this. That's because if we were to find out how many other people's teeth are in the 2nd section on the right that we talked about earlier, what would happen? So far. It is said that you can find out how many teeth are in this by subtracting how many teeth appear in the section before this, right? This is now the concept of a full fix island. But let's think about it. Even numbers. To get an even clock, the only way to get an even number is to subtract an odd number from an odd number. Only when these two cases are met can you get this even number. So, this is not the actual number at that time, but this even section. In order to judge whether the vowel appears in an even number or not, you just have to say whether this position is an even number or an odd number. This coloring can be used like this. This is where the kelp becomes like this. This is where the limit is. That can be it. It's big here. This is the second one, so it's an even number. Let's say we mark the masterpiece as 0. Let's just call it a bottle as 1. This here is completely cool, so it becomes work again. Here, it will continue to be work again. Since there is 1, this is an even number, so it is an even number of 0. Try it. Let's say yes, brother. Then, at this location, the story was an even number and there was a blessing in front of this, so these two are not the same. 1 This is a hole and this is an even number. So, this means that this wife has an odd number. Do you understand? What happens when you raise it? Ah, what happens when you widen it up to here? Since this is an even number and this is also an even number, there are more doubles in this section. This means that there are more doubles in this section. So, this information is the flex that represents the diagonal, vowel, and diagonal. When we go in order from the front, here is the even number translation, this is the lake where we started to absorb. After creating the information like this, if we select the section we want for the next two sections, the car from the front of this section and up to this section will be the even number. If so, then that section is an odd number or an even number. So in the end, if this value is the same, then that section has an even chance. Now, let's figure out how to actually find the longest section using this table. Let 's take a look. It's 's take a look. It's 's take a look. It's too difficult to check all 5 of the letters first, so let's just take this one letter and check it in this example. Witcher heroes 234 here. 1 0 Ugh, this must be the work. Yes, I'm chasing it like this. Oh, I'm chasing it like this, and I'm so focused on it. But there's no need to keep making it in the media like this. I'm checking it as I go. Now, think about it. 0 Im Record the last point. You can leave it. The last edge is 1. Because as I said before, it is a case when you take out the source of an odd number and use an even number. From the standard of work, you can always use the odd number, the first better odd number, and the first male even number, without forgetting. Then, the first even number. As for the binary, it can be said that it is actually Ben's first time. Yes, because researchers also have an even number, so even the ones that do not appear even once are used in pairs. So the section where this vowel does not appear at all also has an important meaning. So, let's get the person in front of this. You just have to think of it as an even number, right? Then, it just comes out like this. Then, the even number of inches will always be like this. Then, how about this? Here, it's always ah, the understanding is 0. It came out right from the spring. Then, let's see the next picture. 1 came out. This is not an odd number. Then, when this comes out. When I come out here. To make it an even number in front of it, you have to find and write the one-person play 1 in front of it. Now there is no work. There have to find and write the one-person play 1 in front of it. Now there is no work. There have to find and write the one-person play 1 in front of it. Now there is no work. There is no work. Let's get this in between. There was nothing. Then, this happened again. The same goes for this, because there was no previous incident, so there is no salvation. After that, the spirit was perfect. It was used forever. Then, the last 0 was recorded. And this is the first. The location of the first toll number is also recorded in English. So what should we do? This is the first zero here, so subtract the area. Then, how much is this? If you subtract 800 from the index here, the length of Sam 3 is 3. Here, the even-numbered section is 3. It becomes this. Here, the even-numbered section is 3. It becomes this. Here, the even-numbered section is 3. It becomes this. Then, here and here. When we look at this as the end, when we look at this as the end of the problem, what should we do? This is an odd number again. And where can we come to the front? It was here. Then, in the end, the number of pains here was always 0, so society Subtracting 0 from git gives 2332. Like this, we get an even number here as well, and this becomes an even number. Then, when we process t, it is a work, so it is an odd number. So what should we do? If we subtract the Hush niche, the length is 4 here, and it continues to increase. 6 Here, it is also a work. The 7th total is 13 14 and then this one comes out. When 2 e comes out, this becomes an even number again. It becomes a number. When it becomes 0, where is the last number that comes out? - 0, where is the last number that comes out? - It's crazy. Then, how much does this have to be to get to 17? Ah, 15. becomes 16 And then here, it's still 0, so it's 17. So 2, the length of the entire section is 17. So the answer is the longest one, 17. This whole thing is an even number, including the whole thing. When you use just this one, it becomes 16. That's right, but what are the conditions here? There's a, there's this child, and there's this oo. All of this has to be taken into consideration. Then, even for a reason, if Todd Hall Ho is expressed in terms of that, it's the hero's acceptance. This is why section 1 mourning is 0 to 0. This is why in section 1, Lee Do-young, 0. This is why section 1, Lee Do-young, 0. This is why section 1, Lee Do-young, 0. This is why section 1 goes like this. 2 This whole thing is not an even number song, so this is all the end condition. 2 0 1 You have to check all of them. At the beginning, this is everything. Ah, everything is the hero section. Yes, this one also has to have a section of 0 Ingo 0 and 1 person. Right, this is mine, continues here and here, and everything is given to me by my brother. Just The amount of this guy is also in front of the first here, so it's a bottle * and it's a good thing because a bottle * and it's a good thing because a bottle * and it's a good thing because I come in here as 1, so it's 1. That's right. If you divide by the even number, then this guy is also 0 Idea 1 0 Yes 1 0 1 It'll be like this. Oh, yeah, that again. The person next and here too, byung 0 Bottle 1 This came out once. There will be 1 0 people. o is 0 1 It will be like this. 0 Now, if you think of these five bodies as a whole from both sides. In the end, things have to be the same for him, and he has to be the same, so I have to find the section where this is the same. be the same, and he has to be the same, so I have to find the section where this is the same. So what I mean is, this section wasn't in the education. This section here is pretty. It's right here. It's the station, so the same value is 5. So, this can be an even number. Kise, right. There are many even numbers that can be an even number. Since two teeth have appeared, what is this next? This one here, this one, is the same as the previous one, right? So, this can also be an even number. Right, yes, here too, this person is 3, this place is 3, and then this place was also in front. Because the director was here, 4, 5, it came up to here, o, but then suddenly, , there is no same value here. Because it is came up to here, o, but then suddenly, , there is no same value here. Because it is came up to here, o, but then suddenly, , there is no same value here. Because it is not in front, I can't go here, but there is also here. Since the same value was in front, ki is now in the section again. From here to this 1 Oh, this is to this point 2 Because the moment beyond this side includes the child, when including this 1 Then when processing here and here, this was in front again. Where was it? Here it is. Then, this section is here. That's it, right? Then again, it's the same from here to the truck beast. It's the same, so it's the same. Anyway, it's the same. If you keep going, it's the last from here to here. How far will it go? Ah, the same value comes out. Because it's the next one, the curse that the section from here to here is an even number is the same here. Gi and we are the same, right. This place is the same, so it's the same thing from the front to the back. The request to include it is really redundant. That vowel 2. Even number. Individual. It becomes 9 times with each u number containing an even number. What is it in the end? This eventually became a 0 1 pattern, and this became an integer of 5 100t opto. It became an integer of obd. When the previous value expressed as an integer of odt appears again, From the section that came before that, the position that came before that big, the distance from the next position to the position that came out now becomes a person. In the end, when I process this letter in front of me, I process the number of letters in the time and process the number of letters in front of me. Sometimes, we check how many of them appear, and the first one that appears in front becomes the distance to the first one. Then, when we calculate here again, we calculate our own and then see if there is another pattern that appears in front of us, and then we look at the distance to that one. Here is the distance from here to here. Then, the contents of this place will be drawn. The distance from here to here becomes the maximum length that I can extend to the end, including my son. Processing all lengths from the front, from each location to the end point. When you think about it, when you go up from the front, Giselle, which has an even number composition, goes up to the far side. It is a way to check whether it is an even number. The easy way is to check whether each letter appears an even number of times and is the even or absorbed number from the front. After continuing to check and expressing 0 and 1 for each of them, the 2-foot pattern that is grouped together is the 2-foot pattern that is grouped together is the distance to the next bit pattern in front of the currently calculated pit pattern and the same bit pattern in front. If you calculate it, you will get the longest distance. Now that you know how to process it like this, let's translate it into code and implement it. Now, as we said earlier, we said there are 5 bit patterns, and we explained the reason for each. Since we have to develop in bit positions, I'll give you just one function that changes those letters into indexes. Even if I find out, I'll give you a name. Since I said, the number that can be expanded to 5 digits is from here to 30 days. So, it's just the 5 numbers within it. Rest is the only one. So - Ah, I need an indication of whether it exists or not later - Why get this - It will be revealed later whether it worked or not. - Why get this - It will be revealed later whether it worked or not. - Why get this - It will be revealed later whether it worked or not. Of course, this is a method of my implementation. This is all completely familiar, and this is the only correct answer. This is not like that. Then, I compile the text and what to receive. This is 2 currents inside. I process Adler t. When doing this, you have to create a 2-foot pattern that represents the tee. It have to create a 2-foot pattern that represents the tee. It have to create a 2-foot pattern that represents the tee. It represents the pit pattern. All you have to do is create beat patterns. Then, at the beginning, you need this 00. The first effect will be displayed as - 2. This and yet. It's not set up. There will be displayed as - 2. This and yet. It's not set up. There will be displayed as - 2. This and yet. It's not set up. There aren't any traces yet. There are a lot of 0000s. The D patterns in the rest of the stitches didn't come out. I deliberately lost it for 9 minutes. It's not my intention to follow it. If I get the hang of it later and use a map or a hash map, I don't have to use a 2g pet like this. It will work. Anyway, I have to do it like this. I will try to do it without crying. So, Min, I will process the whole thing from the beginning. Change it to a mat. The car is pretty. Change the letter in the i-th position to the car is pretty. Change the letter in the i-th position to the car is pretty. Change the letter in the i-th position to the number of seconds. After changing it to a deck, if If this index value is greater than 0, it means that i in a pole or 2 Ah, one of the ioio below has been used, so please toggle this as the font. Yes, do you have an index? Shift pt like this and keep the width. It gives you 0 to 1, so if you change that bit to 104 with If you subtract the location, you will get the distance. When you reach that distance, it becomes a special vacation. Since the maximum value among the distances is searched, it is not the case. Since nothing is less than now, it means that nothing has been found, so the current location is claimed for the first time. It is stored on the 2nd floor. All you have to do is find the most urgent one, so you can select 3 colors, and when that happens, you just need to beta the longest number among them. You can check the rest current in the 20-minute trine. Now here, just process it with 32 arrays like this. can check the rest current in the 20-minute trine. Now here, just process it with 32 arrays like this. can check the rest current in the 20-minute trine. Now here, just process it with 32 arrays like this. But here, you can use the core app. It is also possible to write a test. In this code, if you call it to the core in ancient times, you can see it. If you get a house, you can use it more precisely than wholesale, so ah, 2 5, pad transformer blast, and then do this for lst. Then, the only thing that changes is here. Yes, this is in it. This car is in it during Paiz S in the resentful race. Uh, at 10%, I check it like this. Is it possible to check whether it is in the example map or not? Uh, at 10%, I check it like this. Is it possible to check whether it is in the example map or not? Uh, at 10%, I check it like this. Is it possible to check whether it is in the example map or not? After that, it just changes to crying. You can bow like this. Here's an example. How did you hit the enemy app? Is it odd or even? Is it the odd number? This is now very important. If it is an expression that represents whether it is an odd number or an even number, it can be conveniently used as 0 and 1, respectively. After expressing it with 0 and 1, I saw that 1l a5 can be expressed as an integer of 5 bits, each of which is expressed as one btc. At that position, whether IU comes out in an even number or 23 comes out, you can do it with one way of feet. If there is a pit pattern in front, if you calculate the distance to there is an even section in that section, and if you calculate the distance, you can calculate it with this pattern at each location, for example, here, and up to the high shown in front. If you calculate the distance, you can calculate the maximum length of the Cheong, which is the end of the string that ends here, and even numbers can be the Shen that appears in Ta, and when you go through all the Buddhist characters and end the letters, the tallest end is 9 letters. When you keep chasing the longest distance backwards and calculate it, you can find the answer by finding the biggest one among them. One thing is enough. As for Zhao, I will stop here.
Find the Longest Substring Containing Vowels in Even Counts
minimum-remove-to-make-valid-parentheses
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**. **Example 2:** **Input:** s = "leetcodeisgreat " **Output:** 5 **Explanation:** The longest substring is "leetc " which contains two e's. **Example 3:** **Input:** s = "bcbcbc " **Output:** 6 **Explanation:** In this case, the given string "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times. **Constraints:** * `1 <= s.length <= 5 x 10^5` * `s` contains only lowercase English letters. It is the empty string, or 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.
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
String,Stack
Medium
2095,2221
7
what's up everyone today we're gonna be going over we code number seven reverse integer there's a pretty simple problem conceptually pretty much they give us a number like this we just swap the digits around and the basic is you mod the number to get the number in the ones place and then you divide the number by 10 to eliminate that and then it becomes 5 now the tricky part is when they give us the overflows and it goes outside the answer wants us to return zero in that case and this solution comes from the recode solution tab itself so make sure you just read that before you get into it okay so inte R is equal to zero they want an integer so this is what we declare first and then while X is not equal to zero this one is it gonna be what we operate on and we want to get the edge first so it's gonna be in T for temp is gonna be X mod 10 and then we decrement X every time by 10 so first we're holding 7 and then we divide 57 by 10 and we get 5 so that's what X is gonna become now I'm gonna leave this blank for now I'll come back to it once I read this part now res is gonna be res times 10 plus T now what this basically does is it shifts over whatever arrest was initially by one to the by 10 times and then it adds the T which is gonna go in the ones place and then we return where as now let's write the ifs if res is greater than integer maxvill by 10:00 I'll tell you why this is by 10:00 I'll tell you why this is by 10:00 I'll tell you why this is by 10 it's because at this point in time on this iteration of the while loop res is not the same length as integer DUP max value it's going to be one digit less than so that's why we have to divide this by 10 and we can compare res is going to be greater than or if res is equal to integer dot max value and T is equal to 7 because the greatest one we can have is 2 power 31 minus 1 and this ending number so we put that then we return 0 return zero or if the same thing if it's less than the minimum value by ten because the length of res this point in time is not going to be equal he's not going to be the same length as these guys or FRS is equal to integer the main value by 10 again yeah by 10 again and T is equal to 8 then we return zero okay so that's how you solve we code number seven please let me know in the comment section below what other problems you like me to solve and if I could improve my videos in any way and please subscribe and share it or like it and whatever and yeah just keep watching thank you
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
890
hey everybody this is larry this is day 21st of the may nico daily challenge end of three weeks yay hit the like button hit the subscribe button join me in discord let me know what you think about today's farm fine and replace pla pattern so i usually sub just live so it's a little bit slow let me know uh or well i mean i'm going as fast as i can so you know skip ahead and watch it on 2x whatever you need to do to kind of um you know whatever you do this is the beauty of a video or technology excuse me i am recording these live so yeah okay give them a list of string words and pattern okay get return a list of words that we run by okay um where's abb oh okay so if so basically um it matches the pattern if there's a one to one relationship between the characters um each word length is going to be 50 but it doesn't oops it almost doesn't even matter oh could do it like roughly uh well in on the order of the alphabet so it should be okay maybe yeah um yeah so that's so i think doing it naively giving given these constraints during and i leave area naively should be good enough um you can do and i'm gonna do some pre-processing pre-processing pre-processing because we have only one pattern um but i think that should be good and it so my idea here uh and my first thought and probably the thought that i'm gonna go with and if something goes tragically wrong uh it's just abusing the frequency map um so we can do something like this so and because the pattern is not changing we can actually compile the pattern um oh wait does it have to be in the same order maybe that's the part that i okay so it has to be in the same order so with the frequency um okay so i was wrong about it for a second because i think i read permutation but then i misunderstood a little bit but yeah it has to be have the same uh pattern so it has to be one to one so we can do it just naively uh maybe we could pre-compile things but uh maybe we could pre-compile things but uh maybe we could pre-compile things but um but i don't even think it's necessary given this constraint because each pattern is 20. um and each length has 20 so you can do some 20 square you know n or n square type thing where n is the number of characters and that should be good enough so let's do it um let's just write a fit function for now we'll do it one at a time um and then you know the other one is just a for loop so it should be good so word and a pattern how do we want to do this right so we assume that these two already have the same uh same length because they tell you that um oops keep doing that so okay so we have we need a lookup and a reverse lookup um okay so let's see if x in lookup well if yeah if let's see i'm trying to think about my conditions in a way that is just um just concise so basically what this is going to be false if and lookup of x is not equal to y return force also if y is in reverse lookup and reverse lookup of y is not x then return force otherwise lookup of x is equal to y lookup of y to x so i do take some time to think sometimes and then when i type it out i just type it out and that depends on the problem of course and what edges edge cases come up um but yeah and then we turn true otherwise so i'm trying to think whether um i think this should be good maybe not uh this is a little greedy um i think the thing that i'm thinking about is whether uh you can accidentally have something map to two things but i think the reverse lookup fixes from that so uh so yeah so then now we just go return um word for word and pad of words if fit or maybe this is match that's fine better word and that's pretty much it converted to lists well that the idea this is pretty much it whether this is correct or not is another story okay i should just copy it and paste oh looks okay so let's give it a quick summit cool i know that earlier i said that uh n squared for this function is okay um i'm just saying that in the worst case i like i think at the time i wasn't quite sure that what i wrote here is correct off my head but given that the constraint is only you know 20 i'm just saying that like even if you do something like really silly it'll be okay right that's what i was going at not that this is the um goal of my complexity it turns out that of course if you look at this an assuming constant lookup on hash tables uh then well this is okay i mean i use the hash table but you could actually use them you know because uh you could use like an array of 26 characters or something to the order of the alphabet the size of the alphabet um but in any case this is going to be o of n where n is the number of characters and this is going to be linear in total in the size of the input because for every word we look at it once and for pattern we look at it uh m times where m is the number of words so this is linear in the size of the input and in terms of space in the worst case this is going to be linear space um just because well okay depending how you wanna i mean you can maybe put in a better way but this list can be linear so that's why it could be uh in linear space um but this function of course just takes over one space quantum quote or o if alpha space where alpha is the size of the alphabet or u depending on you know whatever the size of the universe because basically all we do is just look at character at a time and have a alphabet look up um but this one will take extra linear space but you know that's what i have for this one um i think this is just trying to figure out this bijection thing by having a lookup and a reverse lookup i think probably i've done this before i jumped to this really quickly i think but without honestly proving it uh super concretely uh i probably have i don't i haven't done this particular problem per se or maybe i have actually i don't even remember i don't remember doing it but you know the um this kind of thing does happen a bit where is the bijection from a to b and you kind of match them and then you know you just have to make sure that um like if you kind of visualize it you have a left thing a function and a right function and you want make sure that is one to one on both sides and that's why i you know with that visualization that's why i made this implementation and was like relatively okay about confidence um but lately i've been sloppy with the confidence that's why i'm a little bit less confident than usual but that doesn't uh that's not because i don't know this i don't think but yeah uh that's i don't know i don't think i could do much better so let me know what you think i'll see you later have a great weekend and stay cool stay good to good mental health bye
Find and Replace Pattern
lemonade-change
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Array,Greedy
Easy
null